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

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.242   ! anton      64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007,2008,2009,2010,2011,2012 Free Software Foundation, Inc.
1.29      crook      65: 
1.113     anton      66: @quotation
                     67: Permission is granted to copy, distribute and/or modify this document
                     68: under the terms of the GNU Free Documentation License, Version 1.1 or
                     69: any later version published by the Free Software Foundation; with no
                     70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
                     71: and with the Back-Cover Texts as in (a) below.  A copy of the
                     72: license is included in the section entitled ``GNU Free Documentation
                     73: License.''
                     74: 
                     75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
                     76: this GNU Manual, like GNU software.  Copies published by the Free
                     77: Software Foundation raise funds for GNU development.''
                     78: @end quotation
                     79: @end copying
1.10      anton      80: 
1.113     anton      81: @dircategory Software development
                     82: @direntry
                     83: * Gforth: (gforth).             A fast interpreter for the Forth language.
                     84: @end direntry
                     85: @c The Texinfo manual also recommends doing this, but for Gforth it may
                     86: @c  not make much sense
                     87: @c @dircategory Individual utilities
                     88: @c @direntry
                     89: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
                     90: @c @end direntry
1.1       anton      91: 
                     92: @titlepage
1.113     anton      93: @title Gforth
                     94: @subtitle for version @value{VERSION}, @value{UPDATED}
                     95: @author Neal Crook
                     96: @author Anton Ertl
1.114     anton      97: @author David Kuehling
1.113     anton      98: @author Bernd Paysan
                     99: @author Jens Wilke
1.1       anton     100: @page
                    101: @vskip 0pt plus 1filll
1.113     anton     102: @insertcopying
                    103: @end titlepage
1.1       anton     104: 
1.113     anton     105: @contents
1.1       anton     106: 
1.113     anton     107: @ifnottex
                    108: @node Top, Goals, (dir), (dir)
                    109: @top Gforth
1.1       anton     110: 
1.113     anton     111: @insertcopying
1.49      anton     112: @end ifnottex
1.1       anton     113: 
                    114: @menu
1.26      crook     115: * Goals::                       About the Gforth Project
1.29      crook     116: * Gforth Environment::          Starting (and exiting) Gforth
1.48      anton     117: * Tutorial::                    Hands-on Forth Tutorial
1.21      crook     118: * Introduction::                An introduction to ANS Forth
1.1       anton     119: * Words::                       Forth words available in Gforth
1.24      anton     120: * Error messages::              How to interpret them
1.1       anton     121: * Tools::                       Programming tools
                    122: * ANS conformance::             Implementation-defined options etc.
1.65      anton     123: * Standard vs Extensions::      Should I use extensions?
1.1       anton     124: * Model::                       The abstract machine of Gforth
                    125: * Integrating Gforth::          Forth as scripting language for applications
                    126: * Emacs and Gforth::            The Gforth Mode
                    127: * Image Files::                 @code{.fi} files contain compiled code
                    128: * Engine::                      The inner interpreter and the primitives
1.13      pazsan    129: * Cross Compiler::              The Cross Compiler
1.1       anton     130: * Bugs::                        How to report them
                    131: * Origin::                      Authors and ancestors of Gforth
1.21      crook     132: * Forth-related information::   Books and places to look on the WWW
1.113     anton     133: * Licenses::                    
1.1       anton     134: * Word Index::                  An item for each Forth word
                    135: * Concept Index::               A menu covering many topics
1.12      anton     136: 
1.91      anton     137: @detailmenu
                    138:  --- The Detailed Node Listing ---
1.12      anton     139: 
1.29      crook     140: Gforth Environment
                    141: 
1.32      anton     142: * Invoking Gforth::             Getting in
                    143: * Leaving Gforth::              Getting out
                    144: * Command-line editing::        
1.48      anton     145: * Environment variables::       that affect how Gforth starts up
1.32      anton     146: * Gforth Files::                What gets installed and where
1.112     anton     147: * Gforth in pipes::             
1.204     anton     148: * Startup speed::               When 14ms is not fast enough ...
1.48      anton     149: 
                    150: Forth Tutorial
                    151: 
                    152: * Starting Gforth Tutorial::    
                    153: * Syntax Tutorial::             
                    154: * Crash Course Tutorial::       
                    155: * Stack Tutorial::              
                    156: * Arithmetics Tutorial::        
                    157: * Stack Manipulation Tutorial::  
                    158: * Using files for Forth code Tutorial::  
                    159: * Comments Tutorial::           
                    160: * Colon Definitions Tutorial::  
                    161: * Decompilation Tutorial::      
                    162: * Stack-Effect Comments Tutorial::  
                    163: * Types Tutorial::              
                    164: * Factoring Tutorial::          
                    165: * Designing the stack effect Tutorial::  
                    166: * Local Variables Tutorial::    
                    167: * Conditional execution Tutorial::  
                    168: * Flags and Comparisons Tutorial::  
                    169: * General Loops Tutorial::      
                    170: * Counted loops Tutorial::      
                    171: * Recursion Tutorial::          
                    172: * Leaving definitions or loops Tutorial::  
                    173: * Return Stack Tutorial::       
                    174: * Memory Tutorial::             
                    175: * Characters and Strings Tutorial::  
                    176: * Alignment Tutorial::          
1.190     anton     177: * Floating Point Tutorial::     
1.87      anton     178: * Files Tutorial::              
1.48      anton     179: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                    180: * Execution Tokens Tutorial::   
                    181: * Exceptions Tutorial::         
                    182: * Defining Words Tutorial::     
                    183: * Arrays and Records Tutorial::  
                    184: * POSTPONE Tutorial::           
                    185: * Literal Tutorial::            
                    186: * Advanced macros Tutorial::    
                    187: * Compilation Tokens Tutorial::  
                    188: * Wordlists and Search Order Tutorial::  
1.29      crook     189: 
1.24      anton     190: An Introduction to ANS Forth
                    191: 
1.67      anton     192: * Introducing the Text Interpreter::  
                    193: * Stacks and Postfix notation::  
                    194: * Your first definition::       
                    195: * How does that work?::         
                    196: * Forth is written in Forth::   
                    197: * Review - elements of a Forth system::  
                    198: * Where to go next::            
                    199: * Exercises::                   
1.24      anton     200: 
1.12      anton     201: Forth Words
                    202: 
                    203: * Notation::                    
1.65      anton     204: * Case insensitivity::          
                    205: * Comments::                    
                    206: * Boolean Flags::               
1.12      anton     207: * Arithmetic::                  
                    208: * Stack Manipulation::          
                    209: * Memory::                      
                    210: * Control Structures::          
                    211: * Defining Words::              
1.65      anton     212: * Interpretation and Compilation Semantics::  
1.47      crook     213: * Tokens for Words::            
1.81      anton     214: * Compiling words::             
1.65      anton     215: * The Text Interpreter::        
1.111     anton     216: * The Input Stream::            
1.65      anton     217: * Word Lists::                  
                    218: * Environmental Queries::       
1.12      anton     219: * Files::                       
                    220: * Blocks::                      
                    221: * Other I/O::                   
1.121     anton     222: * OS command line arguments::   
1.78      anton     223: * Locals::                      
                    224: * Structures::                  
                    225: * Object-oriented Forth::       
1.12      anton     226: * Programming Tools::           
1.150     anton     227: * C Interface::                 
1.12      anton     228: * Assembler and Code Words::    
                    229: * Threading Words::             
1.65      anton     230: * Passing Commands to the OS::  
                    231: * Keeping track of Time::       
                    232: * Miscellaneous Words::         
1.12      anton     233: 
                    234: Arithmetic
                    235: 
                    236: * Single precision::            
1.67      anton     237: * Double precision::            Double-cell integer arithmetic
1.12      anton     238: * Bitwise operations::          
1.67      anton     239: * Numeric comparison::          
1.32      anton     240: * Mixed precision::             Operations with single and double-cell integers
1.12      anton     241: * Floating Point::              
                    242: 
                    243: Stack Manipulation
                    244: 
                    245: * Data stack::                  
                    246: * Floating point stack::        
                    247: * Return stack::                
                    248: * Locals stack::                
                    249: * Stack pointer manipulation::  
                    250: 
                    251: Memory
                    252: 
1.32      anton     253: * Memory model::                
                    254: * Dictionary allocation::       
                    255: * Heap Allocation::             
                    256: * Memory Access::               
                    257: * Address arithmetic::          
                    258: * Memory Blocks::               
1.12      anton     259: 
                    260: Control Structures
                    261: 
1.41      anton     262: * Selection::                   IF ... ELSE ... ENDIF
                    263: * Simple Loops::                BEGIN ...
1.32      anton     264: * Counted Loops::               DO
1.67      anton     265: * Arbitrary control structures::  
                    266: * Calls and returns::           
1.12      anton     267: * Exception Handling::          
                    268: 
                    269: Defining Words
                    270: 
1.67      anton     271: * CREATE::                      
1.44      crook     272: * Variables::                   Variables and user variables
1.67      anton     273: * Constants::                   
1.44      crook     274: * Values::                      Initialised variables
1.67      anton     275: * Colon Definitions::           
1.44      crook     276: * Anonymous Definitions::       Definitions without names
1.236     anton     277: * Quotations::                  
1.71      anton     278: * Supplying names::             Passing definition names as strings
1.67      anton     279: * User-defined Defining Words::  
1.170     pazsan    280: * Deferred Words::              Allow forward references
1.67      anton     281: * Aliases::                     
1.47      crook     282: 
1.63      anton     283: User-defined Defining Words
                    284: 
                    285: * CREATE..DOES> applications::  
                    286: * CREATE..DOES> details::       
                    287: * Advanced does> usage example::  
1.155     anton     288: * Const-does>::                 
1.63      anton     289: 
1.47      crook     290: Interpretation and Compilation Semantics
                    291: 
1.67      anton     292: * Combined words::              
1.12      anton     293: 
1.71      anton     294: Tokens for Words
                    295: 
                    296: * Execution token::             represents execution/interpretation semantics
                    297: * Compilation token::           represents compilation semantics
                    298: * Name token::                  represents named words
                    299: 
1.82      anton     300: Compiling words
                    301: 
                    302: * Literals::                    Compiling data values
                    303: * Macros::                      Compiling words
                    304: 
1.21      crook     305: The Text Interpreter
                    306: 
1.67      anton     307: * Input Sources::               
                    308: * Number Conversion::           
                    309: * Interpret/Compile states::    
                    310: * Interpreter Directives::      
1.21      crook     311: 
1.26      crook     312: Word Lists
                    313: 
1.75      anton     314: * Vocabularies::                
1.67      anton     315: * Why use word lists?::         
1.75      anton     316: * Word list example::           
1.26      crook     317: 
                    318: Files
                    319: 
1.48      anton     320: * Forth source files::          
                    321: * General files::               
1.167     anton     322: * Redirection::                 
1.48      anton     323: * Search Paths::                
                    324: 
                    325: Search Paths
                    326: 
1.75      anton     327: * Source Search Paths::         
1.26      crook     328: * General Search Paths::        
                    329: 
                    330: Other I/O
                    331: 
1.32      anton     332: * Simple numeric output::       Predefined formats
                    333: * Formatted numeric output::    Formatted (pictured) output
                    334: * String Formats::              How Forth stores strings in memory
1.67      anton     335: * Displaying characters and strings::  Other stuff
1.236     anton     336: * String words::                Gforth's little string library
1.178     anton     337: * Terminal output::             Cursor positioning etc.
1.181     anton     338: * Single-key input::            
                    339: * Line input and conversion::   
1.112     anton     340: * Pipes::                       How to create your own pipes
1.149     pazsan    341: * Xchars and Unicode::          Non-ASCII characters
1.26      crook     342: 
                    343: Locals
                    344: 
                    345: * Gforth locals::               
                    346: * ANS Forth locals::            
                    347: 
                    348: Gforth locals
                    349: 
                    350: * Where are locals visible by name?::  
                    351: * How long do locals live?::    
1.78      anton     352: * Locals programming style::    
                    353: * Locals implementation::       
1.26      crook     354: 
1.12      anton     355: Structures
                    356: 
                    357: * Why explicit structure support?::  
                    358: * Structure Usage::             
                    359: * Structure Naming Convention::  
                    360: * Structure Implementation::    
                    361: * Structure Glossary::          
1.183     anton     362: * Forth200x Structures::        
1.12      anton     363: 
                    364: Object-oriented Forth
                    365: 
1.48      anton     366: * Why object-oriented programming?::  
                    367: * Object-Oriented Terminology::  
                    368: * Objects::                     
                    369: * OOF::                         
                    370: * Mini-OOF::                    
1.23      crook     371: * Comparison with other object models::  
1.12      anton     372: 
1.24      anton     373: The @file{objects.fs} model
1.12      anton     374: 
                    375: * Properties of the Objects model::  
                    376: * Basic Objects Usage::         
1.41      anton     377: * The Objects base class::      
1.12      anton     378: * Creating objects::            
                    379: * Object-Oriented Programming Style::  
                    380: * Class Binding::               
                    381: * Method conveniences::         
                    382: * Classes and Scoping::         
1.41      anton     383: * Dividing classes::            
1.12      anton     384: * Object Interfaces::           
                    385: * Objects Implementation::      
                    386: * Objects Glossary::            
                    387: 
1.24      anton     388: The @file{oof.fs} model
1.12      anton     389: 
1.67      anton     390: * Properties of the OOF model::  
                    391: * Basic OOF Usage::             
                    392: * The OOF base class::          
                    393: * Class Declaration::           
                    394: * Class Implementation::        
1.12      anton     395: 
1.24      anton     396: The @file{mini-oof.fs} model
1.23      crook     397: 
1.48      anton     398: * Basic Mini-OOF Usage::        
                    399: * Mini-OOF Example::            
                    400: * Mini-OOF Implementation::     
1.23      crook     401: 
1.78      anton     402: Programming Tools
                    403: 
1.150     anton     404: * Examining::                   Data and Code.
                    405: * Forgetting words::            Usually before reloading.
1.78      anton     406: * Debugging::                   Simple and quick.
                    407: * Assertions::                  Making your programs self-checking.
                    408: * Singlestep Debugger::         Executing your program word by word.
                    409: 
1.155     anton     410: C Interface
                    411: 
                    412: * Calling C Functions::         
                    413: * Declaring C Functions::       
1.180     anton     414: * Calling C function pointers::  
1.196     anton     415: * Defining library interfaces::  
                    416: * Declaring OS-level libraries::  
1.155     anton     417: * Callbacks::                   
1.178     anton     418: * C interface internals::       
1.155     anton     419: * Low-Level C Interface Words::  
                    420: 
1.78      anton     421: Assembler and Code Words
                    422: 
1.221     anton     423: * Assembler Definitions::       Definitions in assembly language
1.78      anton     424: * Common Assembler::            Assembler Syntax
                    425: * Common Disassembler::         
                    426: * 386 Assembler::               Deviations and special cases
1.221     anton     427: * AMD64 Assembler::             
1.78      anton     428: * Alpha Assembler::             Deviations and special cases
                    429: * MIPS assembler::              Deviations and special cases
1.167     anton     430: * PowerPC assembler::           Deviations and special cases
1.193     dvdkhlng  431: * ARM Assembler::               Deviations and special cases
1.78      anton     432: * Other assemblers::            How to write them
                    433: 
1.12      anton     434: Tools
                    435: 
                    436: * ANS Report::                  Report the words used, sorted by wordset.
1.127     anton     437: * Stack depth changes::         Where does this stack item come from?
1.12      anton     438: 
                    439: ANS conformance
                    440: 
                    441: * The Core Words::              
                    442: * The optional Block word set::  
                    443: * The optional Double Number word set::  
                    444: * The optional Exception word set::  
                    445: * The optional Facility word set::  
                    446: * The optional File-Access word set::  
                    447: * The optional Floating-Point word set::  
                    448: * The optional Locals word set::  
                    449: * The optional Memory-Allocation word set::  
                    450: * The optional Programming-Tools word set::  
                    451: * The optional Search-Order word set::  
                    452: 
                    453: The Core Words
                    454: 
                    455: * core-idef::                   Implementation Defined Options                   
                    456: * core-ambcond::                Ambiguous Conditions                
                    457: * core-other::                  Other System Documentation                  
                    458: 
                    459: The optional Block word set
                    460: 
                    461: * block-idef::                  Implementation Defined Options
                    462: * block-ambcond::               Ambiguous Conditions               
                    463: * block-other::                 Other System Documentation                 
                    464: 
                    465: The optional Double Number word set
                    466: 
                    467: * double-ambcond::              Ambiguous Conditions              
                    468: 
                    469: The optional Exception word set
                    470: 
                    471: * exception-idef::              Implementation Defined Options              
                    472: 
                    473: The optional Facility word set
                    474: 
                    475: * facility-idef::               Implementation Defined Options               
                    476: * facility-ambcond::            Ambiguous Conditions            
                    477: 
                    478: The optional File-Access word set
                    479: 
                    480: * file-idef::                   Implementation Defined Options
                    481: * file-ambcond::                Ambiguous Conditions                
                    482: 
                    483: The optional Floating-Point word set
                    484: 
                    485: * floating-idef::               Implementation Defined Options
                    486: * floating-ambcond::            Ambiguous Conditions            
                    487: 
                    488: The optional Locals word set
                    489: 
                    490: * locals-idef::                 Implementation Defined Options                 
                    491: * locals-ambcond::              Ambiguous Conditions              
                    492: 
                    493: The optional Memory-Allocation word set
                    494: 
                    495: * memory-idef::                 Implementation Defined Options                 
                    496: 
                    497: The optional Programming-Tools word set
                    498: 
                    499: * programming-idef::            Implementation Defined Options            
                    500: * programming-ambcond::         Ambiguous Conditions         
                    501: 
                    502: The optional Search-Order word set
                    503: 
                    504: * search-idef::                 Implementation Defined Options                 
                    505: * search-ambcond::              Ambiguous Conditions              
                    506: 
1.109     anton     507: Emacs and Gforth
                    508: 
                    509: * Installing gforth.el::        Making Emacs aware of Forth.
                    510: * Emacs Tags::                  Viewing the source of a word in Emacs.
                    511: * Hilighting::                  Making Forth code look prettier.
                    512: * Auto-Indentation::            Customizing auto-indentation.
                    513: * Blocks Files::                Reading and writing blocks files.
                    514: 
1.12      anton     515: Image Files
                    516: 
1.24      anton     517: * Image Licensing Issues::      Distribution terms for images.
                    518: * Image File Background::       Why have image files?
1.67      anton     519: * Non-Relocatable Image Files::  don't always work.
1.24      anton     520: * Data-Relocatable Image Files::  are better.
1.67      anton     521: * Fully Relocatable Image Files::  better yet.
1.24      anton     522: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.32      anton     523: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.24      anton     524: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     525: 
                    526: Fully Relocatable Image Files
                    527: 
1.27      crook     528: * gforthmi::                    The normal way
1.12      anton     529: * cross.fs::                    The hard way
                    530: 
                    531: Engine
                    532: 
                    533: * Portability::                 
                    534: * Threading::                   
                    535: * Primitives::                  
                    536: * Performance::                 
                    537: 
                    538: Threading
                    539: 
                    540: * Scheduling::                  
                    541: * Direct or Indirect Threaded?::  
1.109     anton     542: * Dynamic Superinstructions::   
1.12      anton     543: * DOES>::                       
                    544: 
                    545: Primitives
                    546: 
                    547: * Automatic Generation::        
                    548: * TOS Optimization::            
                    549: * Produced code::               
1.13      pazsan    550: 
                    551: Cross Compiler
                    552: 
1.67      anton     553: * Using the Cross Compiler::    
                    554: * How the Cross Compiler Works::  
1.13      pazsan    555: 
1.113     anton     556: Licenses
                    557: 
                    558: * GNU Free Documentation License::  License for copying this manual.
1.192     anton     559: * Copying::                     GPL (for copying this software).
1.113     anton     560: 
1.24      anton     561: @end detailmenu
1.1       anton     562: @end menu
                    563: 
1.113     anton     564: @c ----------------------------------------------------------
1.1       anton     565: @iftex
                    566: @unnumbered Preface
                    567: @cindex Preface
1.21      crook     568: This manual documents Gforth. Some introductory material is provided for
                    569: readers who are unfamiliar with Forth or who are migrating to Gforth
                    570: from other Forth compilers. However, this manual is primarily a
                    571: reference manual.
1.1       anton     572: @end iftex
                    573: 
1.28      crook     574: @comment TODO much more blurb here.
1.26      crook     575: 
                    576: @c ******************************************************************
1.113     anton     577: @node Goals, Gforth Environment, Top, Top
1.26      crook     578: @comment node-name,     next,           previous, up
                    579: @chapter Goals of Gforth
                    580: @cindex goals of the Gforth project
                    581: The goal of the Gforth Project is to develop a standard model for
                    582: ANS Forth. This can be split into several subgoals:
                    583: 
                    584: @itemize @bullet
                    585: @item
                    586: Gforth should conform to the ANS Forth Standard.
                    587: @item
                    588: It should be a model, i.e. it should define all the
                    589: implementation-dependent things.
                    590: @item
                    591: It should become standard, i.e. widely accepted and used. This goal
                    592: is the most difficult one.
                    593: @end itemize
                    594: 
                    595: To achieve these goals Gforth should be
                    596: @itemize @bullet
                    597: @item
                    598: Similar to previous models (fig-Forth, F83)
                    599: @item
                    600: Powerful. It should provide for all the things that are considered
                    601: necessary today and even some that are not yet considered necessary.
                    602: @item
                    603: Efficient. It should not get the reputation of being exceptionally
                    604: slow.
                    605: @item
                    606: Free.
                    607: @item
                    608: Available on many machines/easy to port.
                    609: @end itemize
                    610: 
                    611: Have we achieved these goals? Gforth conforms to the ANS Forth
                    612: standard. It may be considered a model, but we have not yet documented
                    613: which parts of the model are stable and which parts we are likely to
                    614: change. It certainly has not yet become a de facto standard, but it
                    615: appears to be quite popular. It has some similarities to and some
                    616: differences from previous models. It has some powerful features, but not
                    617: yet everything that we envisioned. We certainly have achieved our
1.65      anton     618: execution speed goals (@pxref{Performance})@footnote{However, in 1998
                    619: the bar was raised when the major commercial Forth vendors switched to
                    620: native code compilers.}.  It is free and available on many machines.
1.29      crook     621: 
1.26      crook     622: @c ******************************************************************
1.48      anton     623: @node Gforth Environment, Tutorial, Goals, Top
1.29      crook     624: @chapter Gforth Environment
                    625: @cindex Gforth environment
1.21      crook     626: 
1.45      crook     627: Note: ultimately, the Gforth man page will be auto-generated from the
1.29      crook     628: material in this chapter.
1.21      crook     629: 
                    630: @menu
1.29      crook     631: * Invoking Gforth::             Getting in
                    632: * Leaving Gforth::              Getting out
                    633: * Command-line editing::        
1.48      anton     634: * Environment variables::       that affect how Gforth starts up
1.29      crook     635: * Gforth Files::                What gets installed and where
1.112     anton     636: * Gforth in pipes::             
1.204     anton     637: * Startup speed::               When 14ms is not fast enough ...
1.21      crook     638: @end menu
                    639: 
1.49      anton     640: For related information about the creation of images see @ref{Image Files}.
1.29      crook     641: 
1.21      crook     642: @comment ----------------------------------------------
1.48      anton     643: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29      crook     644: @section Invoking Gforth
                    645: @cindex invoking Gforth
                    646: @cindex running Gforth
                    647: @cindex command-line options
                    648: @cindex options on the command line
                    649: @cindex flags on the command line
1.21      crook     650: 
1.30      anton     651: Gforth is made up of two parts; an executable ``engine'' (named
1.109     anton     652: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30      anton     653: will usually just say @code{gforth} -- this automatically loads the
                    654: default image file @file{gforth.fi}. In many other cases the default
                    655: Gforth image will be invoked like this:
1.21      crook     656: @example
1.30      anton     657: gforth [file | -e forth-code] ...
1.21      crook     658: @end example
1.29      crook     659: @noindent
                    660: This interprets the contents of the files and the Forth code in the order they
                    661: are given.
1.21      crook     662: 
1.109     anton     663: In addition to the @command{gforth} engine, there is also an engine
                    664: called @command{gforth-fast}, which is faster, but gives less
                    665: informative error messages (@pxref{Error messages}) and may catch some
1.166     anton     666: errors (in particular, stack underflows and integer division errors)
                    667: later or not at all.  You should use it for debugged,
1.109     anton     668: performance-critical programs.
                    669: 
                    670: Moreover, there is an engine called @command{gforth-itc}, which is
                    671: useful in some backwards-compatibility situations (@pxref{Direct or
                    672: Indirect Threaded?}).
1.30      anton     673: 
1.29      crook     674: In general, the command line looks like this:
1.21      crook     675: 
                    676: @example
1.30      anton     677: gforth[-fast] [engine options] [image options]
1.21      crook     678: @end example
                    679: 
1.30      anton     680: The engine options must come before the rest of the command
1.29      crook     681: line. They are:
1.26      crook     682: 
1.29      crook     683: @table @code
                    684: @cindex -i, command-line option
                    685: @cindex --image-file, command-line option
                    686: @item --image-file @i{file}
                    687: @itemx -i @i{file}
                    688: Loads the Forth image @i{file} instead of the default
                    689: @file{gforth.fi} (@pxref{Image Files}).
1.21      crook     690: 
1.39      anton     691: @cindex --appl-image, command-line option
                    692: @item --appl-image @i{file}
                    693: Loads the image @i{file} and leaves all further command-line arguments
1.65      anton     694: to the image (instead of processing them as engine options).  This is
                    695: useful for building executable application images on Unix, built with
1.39      anton     696: @code{gforthmi --application ...}.
                    697: 
1.29      crook     698: @cindex --path, command-line option
                    699: @cindex -p, command-line option
                    700: @item --path @i{path}
                    701: @itemx -p @i{path}
                    702: Uses @i{path} for searching the image file and Forth source code files
                    703: instead of the default in the environment variable @code{GFORTHPATH} or
                    704: the path specified at installation time (e.g.,
                    705: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                    706: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook     707: 
1.29      crook     708: @cindex --dictionary-size, command-line option
                    709: @cindex -m, command-line option
                    710: @cindex @i{size} parameters for command-line options
                    711: @cindex size of the dictionary and the stacks
                    712: @item --dictionary-size @i{size}
                    713: @itemx -m @i{size}
                    714: Allocate @i{size} space for the Forth dictionary space instead of
                    715: using the default specified in the image (typically 256K). The
                    716: @i{size} specification for this and subsequent options consists of
                    717: an integer and a unit (e.g.,
                    718: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
                    719: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                    720: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                    721: @code{e} is used.
1.21      crook     722: 
1.29      crook     723: @cindex --data-stack-size, command-line option
                    724: @cindex -d, command-line option
                    725: @item --data-stack-size @i{size}
                    726: @itemx -d @i{size}
                    727: Allocate @i{size} space for the data stack instead of using the
                    728: default specified in the image (typically 16K).
1.21      crook     729: 
1.29      crook     730: @cindex --return-stack-size, command-line option
                    731: @cindex -r, command-line option
                    732: @item --return-stack-size @i{size}
                    733: @itemx -r @i{size}
                    734: Allocate @i{size} space for the return stack instead of using the
                    735: default specified in the image (typically 15K).
1.21      crook     736: 
1.29      crook     737: @cindex --fp-stack-size, command-line option
                    738: @cindex -f, command-line option
                    739: @item --fp-stack-size @i{size}
                    740: @itemx -f @i{size}
                    741: Allocate @i{size} space for the floating point stack instead of
                    742: using the default specified in the image (typically 15.5K). In this case
                    743: the unit specifier @code{e} refers to floating point numbers.
1.21      crook     744: 
1.48      anton     745: @cindex --locals-stack-size, command-line option
                    746: @cindex -l, command-line option
                    747: @item --locals-stack-size @i{size}
                    748: @itemx -l @i{size}
                    749: Allocate @i{size} space for the locals stack instead of using the
                    750: default specified in the image (typically 14.5K).
                    751: 
1.176     anton     752: @cindex --vm-commit, command-line option
                    753: @cindex overcommit memory for dictionary and stacks
                    754: @cindex memory overcommit for dictionary and stacks
                    755: @item --vm-commit
                    756: Normally, Gforth tries to start up even if there is not enough virtual
                    757: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
                    758: on OSs that support it); so you can ask for a really big dictionary
                    759: and/or stacks, and as long as you don't use more virtual memory than
                    760: is available, everything will be fine (but if you use more, processes
                    761: get killed).  With this option you just use the default allocation
                    762: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
                    763: means that you cannot and should not ask for as big dictionary and
                    764: stacks, but once Gforth successfully starts up, out-of-memory won't
                    765: kill it.
                    766: 
1.48      anton     767: @cindex -h, command-line option
                    768: @cindex --help, command-line option
                    769: @item --help
                    770: @itemx -h
                    771: Print a message about the command-line options
                    772: 
                    773: @cindex -v, command-line option
                    774: @cindex --version, command-line option
                    775: @item --version
                    776: @itemx -v
                    777: Print version and exit
                    778: 
                    779: @cindex --debug, command-line option
                    780: @item --debug
                    781: Print some information useful for debugging on startup.
                    782: 
                    783: @cindex --offset-image, command-line option
                    784: @item --offset-image
                    785: Start the dictionary at a slightly different position than would be used
                    786: otherwise (useful for creating data-relocatable images,
                    787: @pxref{Data-Relocatable Image Files}).
                    788: 
                    789: @cindex --no-offset-im, command-line option
                    790: @item --no-offset-im
                    791: Start the dictionary at the normal position.
                    792: 
                    793: @cindex --clear-dictionary, command-line option
                    794: @item --clear-dictionary
                    795: Initialize all bytes in the dictionary to 0 before loading the image
                    796: (@pxref{Data-Relocatable Image Files}).
                    797: 
                    798: @cindex --die-on-signal, command-line-option
                    799: @item --die-on-signal
                    800: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                    801: or the segmentation violation SIGSEGV) by translating it into a Forth
                    802: @code{THROW}. With this option, Gforth exits if it receives such a
                    803: signal. This option is useful when the engine and/or the image might be
                    804: severely broken (such that it causes another signal before recovering
                    805: from the first); this option avoids endless loops in such cases.
1.109     anton     806: 
1.119     anton     807: @cindex --no-dynamic, command-line option
                    808: @cindex --dynamic, command-line option
1.109     anton     809: @item --no-dynamic
                    810: @item --dynamic
                    811: Disable or enable dynamic superinstructions with replication
                    812: (@pxref{Dynamic Superinstructions}).
                    813: 
1.119     anton     814: @cindex --no-super, command-line option
1.109     anton     815: @item --no-super
1.110     anton     816: Disable dynamic superinstructions, use just dynamic replication; this is
                    817: useful if you want to patch threaded code (@pxref{Dynamic
                    818: Superinstructions}).
1.119     anton     819: 
                    820: @cindex --ss-number, command-line option
                    821: @item --ss-number=@var{N}
                    822: Use only the first @var{N} static superinstructions compiled into the
                    823: engine (default: use them all; note that only @code{gforth-fast} has
                    824: any).  This option is useful for measuring the performance impact of
                    825: static superinstructions.
                    826: 
                    827: @cindex --ss-min-..., command-line options
                    828: @item --ss-min-codesize
                    829: @item --ss-min-ls
                    830: @item --ss-min-lsu
                    831: @item --ss-min-nexts
                    832: Use specified metric for determining the cost of a primitive or static
                    833: superinstruction for static superinstruction selection.  @code{Codesize}
                    834: is the native code size of the primive or static superinstruction,
                    835: @code{ls} is the number of loads and stores, @code{lsu} is the number of
                    836: loads, stores, and updates, and @code{nexts} is the number of dispatches
                    837: (not taking dynamic superinstructions into account), i.e. every
                    838: primitive or static superinstruction has cost 1. Default:
                    839: @code{codesize} if you use dynamic code generation, otherwise
                    840: @code{nexts}.
                    841: 
                    842: @cindex --ss-greedy, command-line option
                    843: @item --ss-greedy
                    844: This option is useful for measuring the performance impact of static
                    845: superinstructions.  By default, an optimal shortest-path algorithm is
                    846: used for selecting static superinstructions.  With @option{--ss-greedy}
                    847: this algorithm is modified to assume that anything after the static
                    848: superinstruction currently under consideration is not combined into
                    849: static superinstructions.  With @option{--ss-min-nexts} this produces
                    850: the same result as a greedy algorithm that always selects the longest
                    851: superinstruction available at the moment.  E.g., if there are
                    852: superinstructions AB and BCD, then for the sequence A B C D the optimal
                    853: algorithm will select A BCD and the greedy algorithm will select AB C D.
                    854: 
                    855: @cindex --print-metrics, command-line option
                    856: @item --print-metrics
                    857: Prints some metrics used during static superinstruction selection:
                    858: @code{code size} is the actual size of the dynamically generated code.
                    859: @code{Metric codesize} is the sum of the codesize metrics as seen by
                    860: static superinstruction selection; there is a difference from @code{code
                    861: size}, because not all primitives and static superinstructions are
                    862: compiled into dynamically generated code, and because of markers.  The
                    863: other metrics correspond to the @option{ss-min-...} options.  This
                    864: option is useful for evaluating the effects of the @option{--ss-...}
                    865: options.
1.109     anton     866: 
1.48      anton     867: @end table
                    868: 
                    869: @cindex loading files at startup
                    870: @cindex executing code on startup
                    871: @cindex batch processing with Gforth
                    872: As explained above, the image-specific command-line arguments for the
                    873: default image @file{gforth.fi} consist of a sequence of filenames and
                    874: @code{-e @var{forth-code}} options that are interpreted in the sequence
                    875: in which they are given. The @code{-e @var{forth-code}} or
1.121     anton     876: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
                    877: option takes only one argument; if you want to evaluate more Forth
                    878: words, you have to quote them or use @code{-e} several times. To exit
1.48      anton     879: after processing the command line (instead of entering interactive mode)
1.121     anton     880: append @code{-e bye} to the command line.  You can also process the
                    881: command-line arguments with a Forth program (@pxref{OS command line
                    882: arguments}).
1.48      anton     883: 
                    884: @cindex versions, invoking other versions of Gforth
                    885: If you have several versions of Gforth installed, @code{gforth} will
                    886: invoke the version that was installed last. @code{gforth-@i{version}}
                    887: invokes a specific version. If your environment contains the variable
                    888: @code{GFORTHPATH}, you may want to override it by using the
                    889: @code{--path} option.
                    890: 
                    891: Not yet implemented:
                    892: On startup the system first executes the system initialization file
                    893: (unless the option @code{--no-init-file} is given; note that the system
                    894: resulting from using this option may not be ANS Forth conformant). Then
                    895: the user initialization file @file{.gforth.fs} is executed, unless the
1.62      crook     896: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48      anton     897: then in @file{~}, then in the normal path (see above).
                    898: 
                    899: 
                    900: 
                    901: @comment ----------------------------------------------
                    902: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
                    903: @section Leaving Gforth
                    904: @cindex Gforth - leaving
                    905: @cindex leaving Gforth
                    906: 
                    907: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
                    908: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
                    909: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49      anton     910: data are discarded.  For ways of saving the state of the system before
                    911: leaving Gforth see @ref{Image Files}.
1.48      anton     912: 
                    913: doc-bye
                    914: 
                    915: 
                    916: @comment ----------------------------------------------
1.65      anton     917: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48      anton     918: @section Command-line editing
                    919: @cindex command-line editing
                    920: 
                    921: Gforth maintains a history file that records every line that you type to
                    922: the text interpreter. This file is preserved between sessions, and is
                    923: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
                    924: repeatedly you can recall successively older commands from this (or
                    925: previous) session(s). The full list of command-line editing facilities is:
                    926: 
                    927: @itemize @bullet
                    928: @item
                    929: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
                    930: commands from the history buffer.
                    931: @item
                    932: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
                    933: from the history buffer.
                    934: @item
                    935: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
                    936: @item
                    937: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
                    938: @item
                    939: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
                    940: closing up the line.
                    941: @item
                    942: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
                    943: @item
                    944: @kbd{Ctrl-a} to move the cursor to the start of the line.
                    945: @item
                    946: @kbd{Ctrl-e} to move the cursor to the end of the line.
                    947: @item
                    948: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
                    949: line.
                    950: @item
                    951: @key{TAB} to step through all possible full-word completions of the word
                    952: currently being typed.
                    953: @item
1.65      anton     954: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
                    955: using @code{bye}). 
                    956: @item
                    957: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
                    958: character under the cursor.
1.48      anton     959: @end itemize
                    960: 
                    961: When editing, displayable characters are inserted to the left of the
                    962: cursor position; the line is always in ``insert'' (as opposed to
                    963: ``overstrike'') mode.
                    964: 
                    965: @cindex history file
                    966: @cindex @file{.gforth-history}
                    967: On Unix systems, the history file is @file{~/.gforth-history} by
                    968: default@footnote{i.e. it is stored in the user's home directory.}. You
                    969: can find out the name and location of your history file using:
                    970: 
                    971: @example 
                    972: history-file type \ Unix-class systems
                    973: 
                    974: history-file type \ Other systems
                    975: history-dir  type
                    976: @end example
                    977: 
                    978: If you enter long definitions by hand, you can use a text editor to
                    979: paste them out of the history file into a Forth source file for reuse at
                    980: a later time.
                    981: 
                    982: Gforth never trims the size of the history file, so you should do this
                    983: periodically, if necessary.
                    984: 
                    985: @comment this is all defined in history.fs
                    986: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
                    987: @comment chosen?
                    988: 
                    989: 
                    990: @comment ----------------------------------------------
1.65      anton     991: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48      anton     992: @section Environment variables
                    993: @cindex environment variables
                    994: 
                    995: Gforth uses these environment variables:
                    996: 
                    997: @itemize @bullet
                    998: @item
                    999: @cindex @code{GFORTHHIST} -- environment variable
                   1000: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
                   1001: open/create the history file, @file{.gforth-history}. Default:
                   1002: @code{$HOME}.
                   1003: 
                   1004: @item
                   1005: @cindex @code{GFORTHPATH} -- environment variable
                   1006: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
                   1007: for Forth source-code files.
                   1008: 
                   1009: @item
1.147     anton    1010: @cindex @code{LANG} -- environment variable
                   1011: @code{LANG} -- see @code{LC_CTYPE}
                   1012: 
                   1013: @item
                   1014: @cindex @code{LC_ALL} -- environment variable
                   1015: @code{LC_ALL} -- see @code{LC_CTYPE}
                   1016: 
                   1017: @item
                   1018: @cindex @code{LC_CTYPE} -- environment variable
                   1019: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
                   1020: startup, Gforth uses the UTF-8 encoding for strings internally and
                   1021: expects its input and produces its output in UTF-8 encoding, otherwise
                   1022: the encoding is 8bit (see @pxref{Xchars and Unicode}).  If this
                   1023: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
                   1024: that is unset, in @code{LANG}.
                   1025: 
                   1026: @item
1.129     anton    1027: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
                   1028: 
                   1029: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
                   1030: of @code{system} before passing it to C's @code{system()}.  Default:
1.130     anton    1031: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs.  The prefix
1.129     anton    1032: and the command are directly concatenated, so if a space between them is
                   1033: necessary, append it to the prefix.
                   1034: 
                   1035: @item
1.48      anton    1036: @cindex @code{GFORTH} -- environment variable
1.49      anton    1037: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1038: 
                   1039: @item
                   1040: @cindex @code{GFORTHD} -- environment variable
1.62      crook    1041: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1042: 
                   1043: @item
                   1044: @cindex @code{TMP}, @code{TEMP} - environment variable
                   1045: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
                   1046: location for the history file.
                   1047: @end itemize
                   1048: 
                   1049: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
                   1050: @comment mentioning these.
                   1051: 
                   1052: All the Gforth environment variables default to sensible values if they
                   1053: are not set.
                   1054: 
                   1055: 
                   1056: @comment ----------------------------------------------
1.112     anton    1057: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48      anton    1058: @section Gforth files
                   1059: @cindex Gforth files
                   1060: 
                   1061: When you install Gforth on a Unix system, it installs files in these
                   1062: locations by default:
                   1063: 
                   1064: @itemize @bullet
                   1065: @item
                   1066: @file{/usr/local/bin/gforth}
                   1067: @item
                   1068: @file{/usr/local/bin/gforthmi}
                   1069: @item
                   1070: @file{/usr/local/man/man1/gforth.1} - man page.
                   1071: @item
                   1072: @file{/usr/local/info} - the Info version of this manual.
                   1073: @item
                   1074: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
                   1075: @item
                   1076: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
                   1077: @item
                   1078: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
                   1079: @item
                   1080: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
                   1081: @end itemize
                   1082: 
                   1083: You can select different places for installation by using
                   1084: @code{configure} options (listed with @code{configure --help}).
                   1085: 
                   1086: @comment ----------------------------------------------
1.112     anton    1087: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
                   1088: @section Gforth in pipes
                   1089: @cindex pipes, Gforth as part of
                   1090: 
                   1091: Gforth can be used in pipes created elsewhere (described here).  It can
                   1092: also create pipes on its own (@pxref{Pipes}).
                   1093: 
                   1094: @cindex input from pipes
                   1095: If you pipe into Gforth, your program should read with @code{read-file}
                   1096: or @code{read-line} from @code{stdin} (@pxref{General files}).
                   1097: @code{Key} does not recognize the end of input.  Words like
                   1098: @code{accept} echo the input and are therefore usually not useful for
                   1099: reading from a pipe.  You have to invoke the Forth program with an OS
                   1100: command-line option, as you have no chance to use the Forth command line
                   1101: (the text interpreter would try to interpret the pipe input).
                   1102: 
                   1103: @cindex output in pipes
                   1104: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
                   1105: 
                   1106: @cindex silent exiting from Gforth
                   1107: When you write to a pipe that has been closed at the other end, Gforth
                   1108: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
                   1109: into the exception @code{broken-pipe-error}.  If your application does
                   1110: not catch that exception, the system catches it and exits, usually
                   1111: silently (unless you were working on the Forth command line; then it
                   1112: prints an error message and exits).  This is usually the desired
                   1113: behaviour.
                   1114: 
                   1115: If you do not like this behaviour, you have to catch the exception
                   1116: yourself, and react to it.
                   1117: 
                   1118: Here's an example of an invocation of Gforth that is usable in a pipe:
                   1119: 
                   1120: @example
                   1121: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
                   1122:  type repeat ; foo bye"
                   1123: @end example
                   1124: 
                   1125: This example just copies the input verbatim to the output.  A very
                   1126: simple pipe containing this example looks like this:
                   1127: 
                   1128: @example
                   1129: cat startup.fs |
                   1130: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
                   1131:  type repeat ; foo bye"|
                   1132: head
                   1133: @end example
                   1134: 
                   1135: @cindex stderr and pipes
                   1136: Pipes involving Gforth's @code{stderr} output do not work.
                   1137: 
                   1138: @comment ----------------------------------------------
                   1139: @node Startup speed,  , Gforth in pipes, Gforth Environment
1.48      anton    1140: @section Startup speed
                   1141: @cindex Startup speed
                   1142: @cindex speed, startup
                   1143: 
                   1144: If Gforth is used for CGI scripts or in shell scripts, its startup
1.204     anton    1145: speed may become a problem.  On a 3GHz Core 2 Duo E8400 under 64-bit
                   1146: Linux 2.6.27.8 with libc-2.7, @code{gforth-fast -e bye} takes 13.1ms
                   1147: user and 1.2ms system time (@code{gforth -e bye} is faster on startup
                   1148: with about 3.4ms user time and 1.2ms system time, because it subsumes
                   1149: some of the options discussed below).
1.48      anton    1150: 
                   1151: If startup speed is a problem, you may consider the following ways to
                   1152: improve it; or you may consider ways to reduce the number of startups
1.204     anton    1153: (for example, by using Fast-CGI).  Note that the first steps below
                   1154: improve the startup time at the cost of run-time (including
                   1155: compile-time), so whether they are profitable depends on the balance
                   1156: of these times in your application.
                   1157: 
                   1158: An easy step that influences Gforth startup speed is the use of a
                   1159: number of options that increase run-time, but decrease image-loading
                   1160: time.
                   1161: 
                   1162: The first of these that you should try is @code{--ss-number=0
                   1163: --ss-states=1} because this option buys relatively little run-time
                   1164: speedup and costs quite a bit of time at startup.  @code{gforth-fast
                   1165: --ss-number=0 --ss-states=1 -e bye} takes about 2.8ms user and 1.5ms
                   1166: system time.
1.48      anton    1167: 
1.204     anton    1168: The next option is @code{--no-dynamic} which has a substantial impact
                   1169: on run-time (about a factor of 2 on several platforms), but still
                   1170: makes startup speed a little faster: @code{gforth-fast --ss-number=0
                   1171: --ss-states=1 --no-dynamic -e bye} consumes about 2.6ms user and 1.2ms
                   1172: system time.
                   1173: 
                   1174: The next step to improve startup speed is to use a data-relocatable
                   1175: image (@pxref{Data-Relocatable Image Files}).  This avoids the
                   1176: relocation cost for the code in the image (but not for the data).
                   1177: Note that the image is then specific to the particular binary you are
                   1178: using (i.e., whether it is @code{gforth}, @code{gforth-fast}, and even
                   1179: the particular build).  You create the data-relocatable image that
                   1180: works with @code{./gforth-fast} with @code{GFORTHD="./gforth-fast
                   1181: --no-dynamic" gforthmi gforthdr.fi} (the @code{--no-dynamic} is
                   1182: required here or the image will not work).  And you run it with
                   1183: @code{gforth-fast -i gforthdr.fi ... -e bye} (the flags discussed
                   1184: above don't matter here, because they only come into play on
                   1185: relocatable code).  @code{gforth-fast -i gforthdr.fi -e bye} takes
                   1186: about 1.1ms user and 1.2ms system time.
                   1187: 
                   1188: One step further is to avoid all relocation cost and part of the
                   1189: copy-on-write cost through using a non-relocatable image
                   1190: (@pxref{Non-Relocatable Image Files}).  However, this has the
                   1191: disadvantage that it does not work on operating systems with address
                   1192: space randomization (the default in, e.g., Linux nowadays), or if the
                   1193: dictionary moves for any other reason (e.g., because of a change of
                   1194: the OS kernel or an updated library), so we cannot really recommend
                   1195: it.  You create a non-relocatable image with @code{gforth-fast
                   1196: --no-dynamic -e "savesystem gforthnr.fi bye"} (the @code{--no-dynamic}
                   1197: is required here, too).  And you run it with @code{gforth-fast -i
                   1198: gforthnr.fi ... -e bye} (again the flags discussed above don't
                   1199: matter).  @code{gforth-fast -i gforthdr.fi -e bye} takes
                   1200: about 0.9ms user and 0.9ms system time.
                   1201: 
                   1202: If the script you want to execute contains a significant amount of
                   1203: code, it may be profitable to compile it into the image to avoid the
                   1204: cost of compiling it at startup time.
1.48      anton    1205: 
                   1206: @c ******************************************************************
                   1207: @node Tutorial, Introduction, Gforth Environment, Top
                   1208: @chapter Forth Tutorial
                   1209: @cindex Tutorial
                   1210: @cindex Forth Tutorial
                   1211: 
1.67      anton    1212: @c Topics from nac's Introduction that could be mentioned:
                   1213: @c press <ret> after each line
                   1214: @c Prompt
                   1215: @c numbers vs. words in dictionary on text interpretation
                   1216: @c what happens on redefinition
                   1217: @c parsing words (in particular, defining words)
                   1218: 
1.83      anton    1219: The difference of this chapter from the Introduction
                   1220: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
                   1221: be used while sitting in front of a computer, and covers much more
                   1222: material, but does not explain how the Forth system works.
                   1223: 
1.62      crook    1224: This tutorial can be used with any ANS-compliant Forth; any
1.206     anton    1225: Gforth-specific features are marked as such and you can skip them if
                   1226: you work with another Forth.  This tutorial does not explain all
                   1227: features of Forth, just enough to get you started and give you some
                   1228: ideas about the facilities available in Forth.  Read the rest of the
                   1229: manual when you are through this.
1.48      anton    1230: 
                   1231: The intended way to use this tutorial is that you work through it while
                   1232: sitting in front of the console, take a look at the examples and predict
                   1233: what they will do, then try them out; if the outcome is not as expected,
                   1234: find out why (e.g., by trying out variations of the example), so you
                   1235: understand what's going on.  There are also some assignments that you
                   1236: should solve.
                   1237: 
                   1238: This tutorial assumes that you have programmed before and know what,
                   1239: e.g., a loop is.
                   1240: 
                   1241: @c !! explain compat library
                   1242: 
                   1243: @menu
                   1244: * Starting Gforth Tutorial::    
                   1245: * Syntax Tutorial::             
                   1246: * Crash Course Tutorial::       
                   1247: * Stack Tutorial::              
                   1248: * Arithmetics Tutorial::        
                   1249: * Stack Manipulation Tutorial::  
                   1250: * Using files for Forth code Tutorial::  
                   1251: * Comments Tutorial::           
                   1252: * Colon Definitions Tutorial::  
                   1253: * Decompilation Tutorial::      
                   1254: * Stack-Effect Comments Tutorial::  
                   1255: * Types Tutorial::              
                   1256: * Factoring Tutorial::          
                   1257: * Designing the stack effect Tutorial::  
                   1258: * Local Variables Tutorial::    
                   1259: * Conditional execution Tutorial::  
                   1260: * Flags and Comparisons Tutorial::  
                   1261: * General Loops Tutorial::      
                   1262: * Counted loops Tutorial::      
                   1263: * Recursion Tutorial::          
                   1264: * Leaving definitions or loops Tutorial::  
                   1265: * Return Stack Tutorial::       
                   1266: * Memory Tutorial::             
                   1267: * Characters and Strings Tutorial::  
                   1268: * Alignment Tutorial::          
1.190     anton    1269: * Floating Point Tutorial::     
1.87      anton    1270: * Files Tutorial::              
1.48      anton    1271: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                   1272: * Execution Tokens Tutorial::   
                   1273: * Exceptions Tutorial::         
                   1274: * Defining Words Tutorial::     
                   1275: * Arrays and Records Tutorial::  
                   1276: * POSTPONE Tutorial::           
                   1277: * Literal Tutorial::            
                   1278: * Advanced macros Tutorial::    
                   1279: * Compilation Tokens Tutorial::  
                   1280: * Wordlists and Search Order Tutorial::  
                   1281: @end menu
                   1282: 
                   1283: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
                   1284: @section Starting Gforth
1.66      anton    1285: @cindex starting Gforth tutorial
1.48      anton    1286: You can start Gforth by typing its name:
                   1287: 
                   1288: @example
                   1289: gforth
                   1290: @end example
                   1291: 
                   1292: That puts you into interactive mode; you can leave Gforth by typing
                   1293: @code{bye}.  While in Gforth, you can edit the command line and access
                   1294: the command line history with cursor keys, similar to bash.
                   1295: 
                   1296: 
                   1297: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
                   1298: @section Syntax
1.66      anton    1299: @cindex syntax tutorial
1.48      anton    1300: 
1.171     anton    1301: A @dfn{word} is a sequence of arbitrary characters (except white
1.48      anton    1302: space).  Words are separated by white space.  E.g., each of the
                   1303: following lines contains exactly one word:
                   1304: 
                   1305: @example
                   1306: word
                   1307: !@@#$%^&*()
                   1308: 1234567890
                   1309: 5!a
                   1310: @end example
                   1311: 
1.205     anton    1312: A frequent beginner's error is to leave out necessary white space,
1.48      anton    1313: resulting in an error like @samp{Undefined word}; so if you see such an
                   1314: error, check if you have put spaces wherever necessary.
                   1315: 
                   1316: @example
                   1317: ." hello, world" \ correct
                   1318: ."hello, world"  \ gives an "Undefined word" error
                   1319: @end example
                   1320: 
1.65      anton    1321: Gforth and most other Forth systems ignore differences in case (they are
1.48      anton    1322: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
                   1323: your system is case-sensitive, you may have to type all the examples
                   1324: given here in upper case.
                   1325: 
                   1326: 
                   1327: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
                   1328: @section Crash Course
                   1329: 
1.209     anton    1330: Forth does not prevent you from shooting yourself in the foot.  Let's
                   1331: try a few ways to crash Gforth:
1.48      anton    1332: 
                   1333: @example
                   1334: 0 0 !
                   1335: here execute
                   1336: ' catch >body 20 erase abort
                   1337: ' (quit) >body 20 erase
                   1338: @end example
                   1339: 
1.209     anton    1340: The last two examples are guaranteed to destroy important parts of
                   1341: Gforth (and most other systems), so you better leave Gforth afterwards
                   1342: (if it has not finished by itself).  On some systems you may have to
                   1343: kill gforth from outside (e.g., in Unix with @code{kill}).
                   1344: 
                   1345: You will find out later what these lines do and then you will get an
                   1346: idea why they produce crashes.
1.48      anton    1347: 
                   1348: Now that you know how to produce crashes (and that there's not much to
                   1349: them), let's learn how to produce meaningful programs.
                   1350: 
                   1351: 
                   1352: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
                   1353: @section Stack
1.66      anton    1354: @cindex stack tutorial
1.48      anton    1355: 
                   1356: The most obvious feature of Forth is the stack.  When you type in a
1.205     anton    1357: number, it is pushed on the stack.  You can display the contents of the
1.48      anton    1358: stack with @code{.s}.
                   1359: 
                   1360: @example
                   1361: 1 2 .s
                   1362: 3 .s
                   1363: @end example
                   1364: 
                   1365: @code{.s} displays the top-of-stack to the right, i.e., the numbers
                   1366: appear in @code{.s} output as they appeared in the input.
                   1367: 
1.205     anton    1368: You can print the top element of the stack with @code{.}.
1.48      anton    1369: 
                   1370: @example
                   1371: 1 2 3 . . .
                   1372: @end example
                   1373: 
                   1374: In general, words consume their stack arguments (@code{.s} is an
                   1375: exception).
                   1376: 
1.141     anton    1377: @quotation Assignment
1.48      anton    1378: What does the stack contain after @code{5 6 7 .}?
1.141     anton    1379: @end quotation
1.48      anton    1380: 
                   1381: 
                   1382: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
                   1383: @section Arithmetics
1.66      anton    1384: @cindex arithmetics tutorial
1.48      anton    1385: 
                   1386: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
                   1387: operate on the top two stack items:
                   1388: 
                   1389: @example
1.67      anton    1390: 2 2 .s
                   1391: + .s
                   1392: .
1.48      anton    1393: 2 1 - .
                   1394: 7 3 mod .
                   1395: @end example
                   1396: 
                   1397: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
                   1398: as in the corresponding infix expression (this is generally the case in
                   1399: Forth).
                   1400: 
                   1401: Parentheses are superfluous (and not available), because the order of
                   1402: the words unambiguously determines the order of evaluation and the
                   1403: operands:
                   1404: 
                   1405: @example
                   1406: 3 4 + 5 * .
                   1407: 3 4 5 * + .
                   1408: @end example
                   1409: 
1.141     anton    1410: @quotation Assignment
1.48      anton    1411: What are the infix expressions corresponding to the Forth code above?
                   1412: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
                   1413: known as Postfix or RPN (Reverse Polish Notation).}.
1.141     anton    1414: @end quotation
1.48      anton    1415: 
                   1416: To change the sign, use @code{negate}:
                   1417: 
                   1418: @example
                   1419: 2 negate .
                   1420: @end example
                   1421: 
1.141     anton    1422: @quotation Assignment
1.48      anton    1423: Convert -(-3)*4-5 to Forth.
1.141     anton    1424: @end quotation
1.48      anton    1425: 
                   1426: @code{/mod} performs both @code{/} and @code{mod}.
                   1427: 
                   1428: @example
                   1429: 7 3 /mod . .
                   1430: @end example
                   1431: 
1.66      anton    1432: Reference: @ref{Arithmetic}.
                   1433: 
                   1434: 
1.48      anton    1435: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
                   1436: @section Stack Manipulation
1.66      anton    1437: @cindex stack manipulation tutorial
1.48      anton    1438: 
                   1439: Stack manipulation words rearrange the data on the stack.
                   1440: 
                   1441: @example
                   1442: 1 .s drop .s
                   1443: 1 .s dup .s drop drop .s
                   1444: 1 2 .s over .s drop drop drop
                   1445: 1 2 .s swap .s drop drop
                   1446: 1 2 3 .s rot .s drop drop drop
                   1447: @end example
                   1448: 
                   1449: These are the most important stack manipulation words.  There are also
                   1450: variants that manipulate twice as many stack items:
                   1451: 
                   1452: @example
                   1453: 1 2 3 4 .s 2swap .s 2drop 2drop
                   1454: @end example
                   1455: 
                   1456: Two more stack manipulation words are:
                   1457: 
                   1458: @example
                   1459: 1 2 .s nip .s drop
                   1460: 1 2 .s tuck .s 2drop drop
                   1461: @end example
                   1462: 
1.141     anton    1463: @quotation Assignment
1.48      anton    1464: Replace @code{nip} and @code{tuck} with combinations of other stack
                   1465: manipulation words.
                   1466: 
                   1467: @example
                   1468: Given:          How do you get:
                   1469: 1 2 3           3 2 1           
                   1470: 1 2 3           1 2 3 2                 
                   1471: 1 2 3           1 2 3 3                 
                   1472: 1 2 3           1 3 3           
                   1473: 1 2 3           2 1 3           
                   1474: 1 2 3 4         4 3 2 1         
                   1475: 1 2 3           1 2 3 1 2 3             
                   1476: 1 2 3 4         1 2 3 4 1 2             
                   1477: 1 2 3
                   1478: 1 2 3           1 2 3 4                 
                   1479: 1 2 3           1 3             
                   1480: @end example
1.141     anton    1481: @end quotation
1.48      anton    1482: 
                   1483: @example
                   1484: 5 dup * .
                   1485: @end example
                   1486: 
1.141     anton    1487: @quotation Assignment
1.48      anton    1488: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
                   1489: Write a piece of Forth code that expects two numbers on the stack
                   1490: (@var{a} and @var{b}, with @var{b} on top) and computes
                   1491: @code{(a-b)(a+1)}.
1.141     anton    1492: @end quotation
1.48      anton    1493: 
1.66      anton    1494: Reference: @ref{Stack Manipulation}.
                   1495: 
                   1496: 
1.48      anton    1497: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
                   1498: @section Using files for Forth code
1.66      anton    1499: @cindex loading Forth code, tutorial
                   1500: @cindex files containing Forth code, tutorial
1.48      anton    1501: 
                   1502: While working at the Forth command line is convenient for one-line
                   1503: examples and short one-off code, you probably want to store your source
                   1504: code in files for convenient editing and persistence.  You can use your
                   1505: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102     anton    1506: Gforth}) to create @var{file.fs} and use
1.48      anton    1507: 
                   1508: @example
1.102     anton    1509: s" @var{file.fs}" included
1.48      anton    1510: @end example
                   1511: 
                   1512: to load it into your Forth system.  The file name extension I use for
                   1513: Forth files is @samp{.fs}.
                   1514: 
                   1515: You can easily start Gforth with some files loaded like this:
                   1516: 
                   1517: @example
1.102     anton    1518: gforth @var{file1.fs} @var{file2.fs}
1.48      anton    1519: @end example
                   1520: 
                   1521: If an error occurs during loading these files, Gforth terminates,
                   1522: whereas an error during @code{INCLUDED} within Gforth usually gives you
                   1523: a Gforth command line.  Starting the Forth system every time gives you a
                   1524: clean start every time, without interference from the results of earlier
                   1525: tries.
                   1526: 
                   1527: I often put all the tests in a file, then load the code and run the
                   1528: tests with
                   1529: 
                   1530: @example
1.102     anton    1531: gforth @var{code.fs} @var{tests.fs} -e bye
1.48      anton    1532: @end example
                   1533: 
                   1534: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
                   1535: @code{-e bye} ensures that Gforth terminates afterwards so that I can
                   1536: restart this command without ado.
                   1537: 
                   1538: The advantage of this approach is that the tests can be repeated easily
                   1539: every time the program ist changed, making it easy to catch bugs
                   1540: introduced by the change.
                   1541: 
1.66      anton    1542: Reference: @ref{Forth source files}.
                   1543: 
1.48      anton    1544: 
                   1545: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
                   1546: @section Comments
1.66      anton    1547: @cindex comments tutorial
1.48      anton    1548: 
                   1549: @example
                   1550: \ That's a comment; it ends at the end of the line
                   1551: ( Another comment; it ends here: )  .s
                   1552: @end example
                   1553: 
                   1554: @code{\} and @code{(} are ordinary Forth words and therefore have to be
                   1555: separated with white space from the following text.
                   1556: 
                   1557: @example
                   1558: \This gives an "Undefined word" error
                   1559: @end example
                   1560: 
                   1561: The first @code{)} ends a comment started with @code{(}, so you cannot
                   1562: nest @code{(}-comments; and you cannot comment out text containing a
                   1563: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
                   1564: avoid @code{)} in word names.}.
                   1565: 
                   1566: I use @code{\}-comments for descriptive text and for commenting out code
                   1567: of one or more line; I use @code{(}-comments for describing the stack
                   1568: effect, the stack contents, or for commenting out sub-line pieces of
                   1569: code.
                   1570: 
                   1571: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
                   1572: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
                   1573: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
                   1574: with @kbd{M-q}.
                   1575: 
1.66      anton    1576: Reference: @ref{Comments}.
                   1577: 
1.48      anton    1578: 
                   1579: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
                   1580: @section Colon Definitions
1.66      anton    1581: @cindex colon definitions, tutorial
                   1582: @cindex definitions, tutorial
                   1583: @cindex procedures, tutorial
                   1584: @cindex functions, tutorial
1.48      anton    1585: 
                   1586: are similar to procedures and functions in other programming languages.
                   1587: 
                   1588: @example
                   1589: : squared ( n -- n^2 )
                   1590:    dup * ;
                   1591: 5 squared .
                   1592: 7 squared .
                   1593: @end example
                   1594: 
                   1595: @code{:} starts the colon definition; its name is @code{squared}.  The
                   1596: following comment describes its stack effect.  The words @code{dup *}
                   1597: are not executed, but compiled into the definition.  @code{;} ends the
                   1598: colon definition.
                   1599: 
                   1600: The newly-defined word can be used like any other word, including using
                   1601: it in other definitions:
                   1602: 
                   1603: @example
                   1604: : cubed ( n -- n^3 )
                   1605:    dup squared * ;
                   1606: -5 cubed .
                   1607: : fourth-power ( n -- n^4 )
                   1608:    squared squared ;
                   1609: 3 fourth-power .
                   1610: @end example
                   1611: 
1.141     anton    1612: @quotation Assignment
1.48      anton    1613: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
                   1614: @code{/mod} in terms of other Forth words, and check if they work (hint:
                   1615: test your tests on the originals first).  Don't let the
                   1616: @samp{redefined}-Messages spook you, they are just warnings.
1.141     anton    1617: @end quotation
1.48      anton    1618: 
1.66      anton    1619: Reference: @ref{Colon Definitions}.
                   1620: 
1.48      anton    1621: 
                   1622: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
                   1623: @section Decompilation
1.66      anton    1624: @cindex decompilation tutorial
                   1625: @cindex see tutorial
1.48      anton    1626: 
                   1627: You can decompile colon definitions with @code{see}:
                   1628: 
                   1629: @example
                   1630: see squared
                   1631: see cubed
                   1632: @end example
                   1633: 
                   1634: In Gforth @code{see} shows you a reconstruction of the source code from
                   1635: the executable code.  Informations that were present in the source, but
                   1636: not in the executable code, are lost (e.g., comments).
                   1637: 
1.65      anton    1638: You can also decompile the predefined words:
                   1639: 
                   1640: @example
                   1641: see .
                   1642: see +
                   1643: @end example
                   1644: 
                   1645: 
1.48      anton    1646: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
                   1647: @section Stack-Effect Comments
1.66      anton    1648: @cindex stack-effect comments, tutorial
                   1649: @cindex --, tutorial
1.48      anton    1650: By convention the comment after the name of a definition describes the
1.171     anton    1651: stack effect: The part in front of the @samp{--} describes the state of
1.48      anton    1652: the stack before the execution of the definition, i.e., the parameters
                   1653: that are passed into the colon definition; the part behind the @samp{--}
                   1654: is the state of the stack after the execution of the definition, i.e.,
                   1655: the results of the definition.  The stack comment only shows the top
                   1656: stack items that the definition accesses and/or changes.
                   1657: 
                   1658: You should put a correct stack effect on every definition, even if it is
                   1659: just @code{( -- )}.  You should also add some descriptive comment to
                   1660: more complicated words (I usually do this in the lines following
                   1661: @code{:}).  If you don't do this, your code becomes unreadable (because
1.117     anton    1662: you have to work through every definition before you can understand
1.48      anton    1663: any).
                   1664: 
1.141     anton    1665: @quotation Assignment
1.48      anton    1666: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
                   1667: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
                   1668: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
1.65      anton    1669: are done, you can compare your stack effects to those in this manual
1.48      anton    1670: (@pxref{Word Index}).
1.141     anton    1671: @end quotation
1.48      anton    1672: 
                   1673: Sometimes programmers put comments at various places in colon
                   1674: definitions that describe the contents of the stack at that place (stack
                   1675: comments); i.e., they are like the first part of a stack-effect
                   1676: comment. E.g.,
                   1677: 
                   1678: @example
                   1679: : cubed ( n -- n^3 )
                   1680:    dup squared  ( n n^2 ) * ;
                   1681: @end example
                   1682: 
                   1683: In this case the stack comment is pretty superfluous, because the word
                   1684: is simple enough.  If you think it would be a good idea to add such a
                   1685: comment to increase readability, you should also consider factoring the
                   1686: word into several simpler words (@pxref{Factoring Tutorial,,
1.60      anton    1687: Factoring}), which typically eliminates the need for the stack comment;
1.48      anton    1688: however, if you decide not to refactor it, then having such a comment is
                   1689: better than not having it.
                   1690: 
                   1691: The names of the stack items in stack-effect and stack comments in the
                   1692: standard, in this manual, and in many programs specify the type through
                   1693: a type prefix, similar to Fortran and Hungarian notation.  The most
                   1694: frequent prefixes are:
                   1695: 
                   1696: @table @code
                   1697: @item n
                   1698: signed integer
                   1699: @item u
                   1700: unsigned integer
                   1701: @item c
                   1702: character
                   1703: @item f
                   1704: Boolean flags, i.e. @code{false} or @code{true}.
                   1705: @item a-addr,a-
                   1706: Cell-aligned address
                   1707: @item c-addr,c-
                   1708: Char-aligned address (note that a Char may have two bytes in Windows NT)
                   1709: @item xt
                   1710: Execution token, same size as Cell
                   1711: @item w,x
                   1712: Cell, can contain an integer or an address.  It usually takes 32, 64 or
                   1713: 16 bits (depending on your platform and Forth system). A cell is more
                   1714: commonly known as machine word, but the term @emph{word} already means
                   1715: something different in Forth.
                   1716: @item d
                   1717: signed double-cell integer
                   1718: @item ud
                   1719: unsigned double-cell integer
                   1720: @item r
                   1721: Float (on the FP stack)
                   1722: @end table
                   1723: 
                   1724: You can find a more complete list in @ref{Notation}.
                   1725: 
1.141     anton    1726: @quotation Assignment
1.48      anton    1727: Write stack-effect comments for all definitions you have written up to
                   1728: now.
1.141     anton    1729: @end quotation
1.48      anton    1730: 
                   1731: 
                   1732: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
                   1733: @section Types
1.66      anton    1734: @cindex types tutorial
1.48      anton    1735: 
                   1736: In Forth the names of the operations are not overloaded; so similar
                   1737: operations on different types need different names; e.g., @code{+} adds
                   1738: integers, and you have to use @code{f+} to add floating-point numbers.
                   1739: The following prefixes are often used for related operations on
                   1740: different types:
                   1741: 
                   1742: @table @code
                   1743: @item (none)
                   1744: signed integer
                   1745: @item u
                   1746: unsigned integer
                   1747: @item c
                   1748: character
                   1749: @item d
                   1750: signed double-cell integer
                   1751: @item ud, du
                   1752: unsigned double-cell integer
                   1753: @item 2
                   1754: two cells (not-necessarily double-cell numbers)
                   1755: @item m, um
                   1756: mixed single-cell and double-cell operations
                   1757: @item f
                   1758: floating-point (note that in stack comments @samp{f} represents flags,
1.210     anton    1759: and @samp{r} represents FP numbers; also, you need to include the
                   1760: exponent part in literal FP numbers, @pxref{Floating Point Tutorial}).
1.48      anton    1761: @end table
                   1762: 
                   1763: If there are no differences between the signed and the unsigned variant
                   1764: (e.g., for @code{+}), there is only the prefix-less variant.
                   1765: 
                   1766: Forth does not perform type checking, neither at compile time, nor at
1.210     anton    1767: run time.  If you use the wrong operation, the data are interpreted
1.48      anton    1768: incorrectly:
                   1769: 
                   1770: @example
                   1771: -1 u.
                   1772: @end example
                   1773: 
                   1774: If you have only experience with type-checked languages until now, and
                   1775: have heard how important type-checking is, don't panic!  In my
                   1776: experience (and that of other Forthers), type errors in Forth code are
                   1777: usually easy to find (once you get used to it), the increased vigilance
                   1778: of the programmer tends to catch some harder errors in addition to most
                   1779: type errors, and you never have to work around the type system, so in
                   1780: most situations the lack of type-checking seems to be a win (projects to
                   1781: add type checking to Forth have not caught on).
                   1782: 
                   1783: 
                   1784: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
                   1785: @section Factoring
1.66      anton    1786: @cindex factoring tutorial
1.48      anton    1787: 
                   1788: If you try to write longer definitions, you will soon find it hard to
                   1789: keep track of the stack contents.  Therefore, good Forth programmers
                   1790: tend to write only short definitions (e.g., three lines).  The art of
                   1791: finding meaningful short definitions is known as factoring (as in
                   1792: factoring polynomials).
                   1793: 
                   1794: Well-factored programs offer additional advantages: smaller, more
                   1795: general words, are easier to test and debug and can be reused more and
                   1796: better than larger, specialized words.
                   1797: 
                   1798: So, if you run into difficulties with stack management, when writing
                   1799: code, try to define meaningful factors for the word, and define the word
                   1800: in terms of those.  Even if a factor contains only two words, it is
                   1801: often helpful.
                   1802: 
1.65      anton    1803: Good factoring is not easy, and it takes some practice to get the knack
                   1804: for it; but even experienced Forth programmers often don't find the
                   1805: right solution right away, but only when rewriting the program.  So, if
                   1806: you don't come up with a good solution immediately, keep trying, don't
                   1807: despair.
1.48      anton    1808: 
                   1809: @c example !!
                   1810: 
                   1811: 
                   1812: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
                   1813: @section Designing the stack effect
1.66      anton    1814: @cindex Stack effect design, tutorial
                   1815: @cindex design of stack effects, tutorial
1.48      anton    1816: 
                   1817: In other languages you can use an arbitrary order of parameters for a
1.65      anton    1818: function; and since there is only one result, you don't have to deal with
1.48      anton    1819: the order of results, either.
                   1820: 
1.117     anton    1821: In Forth (and other stack-based languages, e.g., PostScript) the
1.48      anton    1822: parameter and result order of a definition is important and should be
                   1823: designed well.  The general guideline is to design the stack effect such
                   1824: that the word is simple to use in most cases, even if that complicates
                   1825: the implementation of the word.  Some concrete rules are:
                   1826: 
                   1827: @itemize @bullet
                   1828: 
                   1829: @item
                   1830: Words consume all of their parameters (e.g., @code{.}).
                   1831: 
                   1832: @item
                   1833: If there is a convention on the order of parameters (e.g., from
                   1834: mathematics or another programming language), stick with it (e.g.,
                   1835: @code{-}).
                   1836: 
                   1837: @item
                   1838: If one parameter usually requires only a short computation (e.g., it is
                   1839: a constant), pass it on the top of the stack.  Conversely, parameters
                   1840: that usually require a long sequence of code to compute should be passed
                   1841: as the bottom (i.e., first) parameter.  This makes the code easier to
1.171     anton    1842: read, because the reader does not need to keep track of the bottom item
1.48      anton    1843: through a long sequence of code (or, alternatively, through stack
1.49      anton    1844: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48      anton    1845: address on top of the stack because it is usually simpler to compute
                   1846: than the stored value (often the address is just a variable).
                   1847: 
                   1848: @item
                   1849: Similarly, results that are usually consumed quickly should be returned
                   1850: on the top of stack, whereas a result that is often used in long
                   1851: computations should be passed as bottom result.  E.g., the file words
                   1852: like @code{open-file} return the error code on the top of stack, because
                   1853: it is usually consumed quickly by @code{throw}; moreover, the error code
                   1854: has to be checked before doing anything with the other results.
                   1855: 
                   1856: @end itemize
                   1857: 
                   1858: These rules are just general guidelines, don't lose sight of the overall
                   1859: goal to make the words easy to use.  E.g., if the convention rule
                   1860: conflicts with the computation-length rule, you might decide in favour
                   1861: of the convention if the word will be used rarely, and in favour of the
                   1862: computation-length rule if the word will be used frequently (because
                   1863: with frequent use the cost of breaking the computation-length rule would
                   1864: be quite high, and frequent use makes it easier to remember an
                   1865: unconventional order).
                   1866: 
                   1867: @c example !! structure package
                   1868: 
1.65      anton    1869: 
1.48      anton    1870: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
                   1871: @section Local Variables
1.66      anton    1872: @cindex local variables, tutorial
1.48      anton    1873: 
                   1874: You can define local variables (@emph{locals}) in a colon definition:
                   1875: 
                   1876: @example
                   1877: : swap @{ a b -- b a @}
                   1878:   b a ;
                   1879: 1 2 swap .s 2drop
                   1880: @end example
                   1881: 
                   1882: (If your Forth system does not support this syntax, include
1.187     anton    1883: @file{compat/anslocal.fs} first).
1.48      anton    1884: 
                   1885: In this example @code{@{ a b -- b a @}} is the locals definition; it
                   1886: takes two cells from the stack, puts the top of stack in @code{b} and
                   1887: the next stack element in @code{a}.  @code{--} starts a comment ending
                   1888: with @code{@}}.  After the locals definition, using the name of the
                   1889: local will push its value on the stack.  You can leave the comment
                   1890: part (@code{-- b a}) away:
                   1891: 
                   1892: @example
                   1893: : swap ( x1 x2 -- x2 x1 )
                   1894:   @{ a b @} b a ;
                   1895: @end example
                   1896: 
                   1897: In Gforth you can have several locals definitions, anywhere in a colon
                   1898: definition; in contrast, in a standard program you can have only one
                   1899: locals definition per colon definition, and that locals definition must
1.163     anton    1900: be outside any control structure.
1.48      anton    1901: 
                   1902: With locals you can write slightly longer definitions without running
                   1903: into stack trouble.  However, I recommend trying to write colon
                   1904: definitions without locals for exercise purposes to help you gain the
                   1905: essential factoring skills.
                   1906: 
1.141     anton    1907: @quotation Assignment
1.48      anton    1908: Rewrite your definitions until now with locals
1.141     anton    1909: @end quotation
1.48      anton    1910: 
1.66      anton    1911: Reference: @ref{Locals}.
                   1912: 
1.48      anton    1913: 
                   1914: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
                   1915: @section Conditional execution
1.66      anton    1916: @cindex conditionals, tutorial
                   1917: @cindex if, tutorial
1.48      anton    1918: 
                   1919: In Forth you can use control structures only inside colon definitions.
                   1920: An @code{if}-structure looks like this:
                   1921: 
                   1922: @example
                   1923: : abs ( n1 -- +n2 )
                   1924:     dup 0 < if
                   1925:         negate
                   1926:     endif ;
                   1927: 5 abs .
                   1928: -5 abs .
                   1929: @end example
                   1930: 
                   1931: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
                   1932: the following code is performed, otherwise execution continues after the
1.51      pazsan   1933: @code{endif} (or @code{else}).  @code{<} compares the top two stack
1.171     anton    1934: elements and produces a flag:
1.48      anton    1935: 
                   1936: @example
                   1937: 1 2 < .
                   1938: 2 1 < .
                   1939: 1 1 < .
                   1940: @end example
                   1941: 
                   1942: Actually the standard name for @code{endif} is @code{then}.  This
                   1943: tutorial presents the examples using @code{endif}, because this is often
                   1944: less confusing for people familiar with other programming languages
                   1945: where @code{then} has a different meaning.  If your system does not have
                   1946: @code{endif}, define it with
                   1947: 
                   1948: @example
                   1949: : endif postpone then ; immediate
                   1950: @end example
                   1951: 
                   1952: You can optionally use an @code{else}-part:
                   1953: 
                   1954: @example
                   1955: : min ( n1 n2 -- n )
                   1956:   2dup < if
                   1957:     drop
                   1958:   else
                   1959:     nip
                   1960:   endif ;
                   1961: 2 3 min .
                   1962: 3 2 min .
                   1963: @end example
                   1964: 
1.141     anton    1965: @quotation Assignment
1.48      anton    1966: Write @code{min} without @code{else}-part (hint: what's the definition
                   1967: of @code{nip}?).
1.141     anton    1968: @end quotation
1.48      anton    1969: 
1.66      anton    1970: Reference: @ref{Selection}.
                   1971: 
1.48      anton    1972: 
                   1973: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
                   1974: @section Flags and Comparisons
1.66      anton    1975: @cindex flags tutorial
                   1976: @cindex comparison tutorial
1.48      anton    1977: 
                   1978: In a false-flag all bits are clear (0 when interpreted as integer).  In
                   1979: a canonical true-flag all bits are set (-1 as a twos-complement signed
                   1980: integer); in many contexts (e.g., @code{if}) any non-zero value is
                   1981: treated as true flag.
                   1982: 
                   1983: @example
                   1984: false .
                   1985: true .
                   1986: true hex u. decimal
                   1987: @end example
                   1988: 
                   1989: Comparison words produce canonical flags:
                   1990: 
                   1991: @example
                   1992: 1 1 = .
                   1993: 1 0= .
                   1994: 0 1 < .
                   1995: 0 0 < .
                   1996: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
                   1997: -1 1 < .
                   1998: @end example
                   1999: 
1.66      anton    2000: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
                   2001: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
                   2002: these combinations are standard (for details see the standard,
                   2003: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48      anton    2004: 
1.171     anton    2005: You can use @code{and or xor invert} as operations on canonical flags.
                   2006: Actually they are bitwise operations:
1.48      anton    2007: 
                   2008: @example
                   2009: 1 2 and .
                   2010: 1 2 or .
                   2011: 1 3 xor .
                   2012: 1 invert .
                   2013: @end example
                   2014: 
                   2015: You can convert a zero/non-zero flag into a canonical flag with
                   2016: @code{0<>} (and complement it on the way with @code{0=}).
                   2017: 
                   2018: @example
                   2019: 1 0= .
                   2020: 1 0<> .
                   2021: @end example
                   2022: 
1.65      anton    2023: You can use the all-bits-set feature of canonical flags and the bitwise
1.48      anton    2024: operation of the Boolean operations to avoid @code{if}s:
                   2025: 
                   2026: @example
                   2027: : foo ( n1 -- n2 )
                   2028:   0= if
                   2029:     14
                   2030:   else
                   2031:     0
                   2032:   endif ;
                   2033: 0 foo .
                   2034: 1 foo .
                   2035: 
                   2036: : foo ( n1 -- n2 )
                   2037:   0= 14 and ;
                   2038: 0 foo .
                   2039: 1 foo .
                   2040: @end example
                   2041: 
1.141     anton    2042: @quotation Assignment
1.48      anton    2043: Write @code{min} without @code{if}.
1.141     anton    2044: @end quotation
1.48      anton    2045: 
1.66      anton    2046: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
                   2047: @ref{Bitwise operations}.
                   2048: 
1.48      anton    2049: 
                   2050: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
                   2051: @section General Loops
1.66      anton    2052: @cindex loops, indefinite, tutorial
1.48      anton    2053: 
                   2054: The endless loop is the most simple one:
                   2055: 
                   2056: @example
                   2057: : endless ( -- )
                   2058:   0 begin
                   2059:     dup . 1+
                   2060:   again ;
                   2061: endless
                   2062: @end example
                   2063: 
                   2064: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
                   2065: does nothing at run-time, @code{again} jumps back to @code{begin}.
                   2066: 
                   2067: A loop with one exit at any place looks like this:
                   2068: 
                   2069: @example
                   2070: : log2 ( +n1 -- n2 )
                   2071: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2072:   assert( dup 0> )
                   2073:   2/ 0 begin
                   2074:     over 0> while
                   2075:       1+ swap 2/ swap
                   2076:   repeat
                   2077:   nip ;
                   2078: 7 log2 .
                   2079: 8 log2 .
                   2080: @end example
                   2081: 
                   2082: At run-time @code{while} consumes a flag; if it is 0, execution
1.51      pazsan   2083: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48      anton    2084: continues behind the @code{while}.  @code{Repeat} jumps back to
                   2085: @code{begin}, just like @code{again}.
                   2086: 
1.211     anton    2087: In Forth there are a number of combinations/abbreviations, like
                   2088: @code{1+}.  However, @code{2/} is not one of them; it shifts its
                   2089: argument right by one bit (arithmetic shift right), and viewed as
                   2090: division that always rounds towards negative infinity (floored
                   2091: division).  In contrast, @code{/} rounds towards zero on some systems
                   2092: (not on default installations of gforth (>=0.7.0), however).
1.48      anton    2093: 
                   2094: @example
1.211     anton    2095: -5 2 / . \ -2 or -3
                   2096: -5 2/ .  \ -3
1.48      anton    2097: @end example
                   2098: 
                   2099: @code{assert(} is no standard word, but you can get it on systems other
1.198     anton    2100: than Gforth by including @file{compat/assert.fs}.  You can see what it
1.48      anton    2101: does by trying
                   2102: 
                   2103: @example
                   2104: 0 log2 .
                   2105: @end example
                   2106: 
                   2107: Here's a loop with an exit at the end:
                   2108: 
                   2109: @example
                   2110: : log2 ( +n1 -- n2 )
                   2111: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2112:   assert( dup 0 > )
                   2113:   -1 begin
                   2114:     1+ swap 2/ swap
                   2115:     over 0 <=
                   2116:   until
                   2117:   nip ;
                   2118: @end example
                   2119: 
1.235     anton    2120: @code{Until} consumes a flag; if it is zero, execution continues at
1.48      anton    2121: the @code{begin}, otherwise after the @code{until}.
                   2122: 
1.141     anton    2123: @quotation Assignment
1.48      anton    2124: Write a definition for computing the greatest common divisor.
1.141     anton    2125: @end quotation
1.48      anton    2126: 
1.66      anton    2127: Reference: @ref{Simple Loops}.
                   2128: 
1.48      anton    2129: 
                   2130: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
                   2131: @section Counted loops
1.66      anton    2132: @cindex loops, counted, tutorial
1.48      anton    2133: 
                   2134: @example
                   2135: : ^ ( n1 u -- n )
1.171     anton    2136: \ n = the uth power of n1
1.48      anton    2137:   1 swap 0 u+do
                   2138:     over *
                   2139:   loop
                   2140:   nip ;
                   2141: 3 2 ^ .
                   2142: 4 3 ^ .
                   2143: @end example
                   2144: 
                   2145: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
                   2146: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
                   2147: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
                   2148: times (or not at all, if @code{u3-u4<0}).
                   2149: 
                   2150: You can see the stack effect design rules at work in the stack effect of
                   2151: the loop start words: Since the start value of the loop is more
                   2152: frequently constant than the end value, the start value is passed on
                   2153: the top-of-stack.
                   2154: 
                   2155: You can access the counter of a counted loop with @code{i}:
                   2156: 
                   2157: @example
                   2158: : fac ( u -- u! )
                   2159:   1 swap 1+ 1 u+do
                   2160:     i *
                   2161:   loop ;
                   2162: 5 fac .
                   2163: 7 fac .
                   2164: @end example
                   2165: 
                   2166: There is also @code{+do}, which expects signed numbers (important for
                   2167: deciding whether to enter the loop).
                   2168: 
1.141     anton    2169: @quotation Assignment
1.48      anton    2170: Write a definition for computing the nth Fibonacci number.
1.141     anton    2171: @end quotation
1.48      anton    2172: 
1.65      anton    2173: You can also use increments other than 1:
                   2174: 
                   2175: @example
                   2176: : up2 ( n1 n2 -- )
                   2177:   +do
                   2178:     i .
                   2179:   2 +loop ;
                   2180: 10 0 up2
                   2181: 
                   2182: : down2 ( n1 n2 -- )
                   2183:   -do
                   2184:     i .
                   2185:   2 -loop ;
                   2186: 0 10 down2
                   2187: @end example
1.48      anton    2188: 
1.66      anton    2189: Reference: @ref{Counted Loops}.
                   2190: 
1.48      anton    2191: 
                   2192: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
                   2193: @section Recursion
1.66      anton    2194: @cindex recursion tutorial
1.48      anton    2195: 
                   2196: Usually the name of a definition is not visible in the definition; but
                   2197: earlier definitions are usually visible:
                   2198: 
                   2199: @example
1.166     anton    2200: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
1.48      anton    2201: : / ( n1 n2 -- n )
                   2202:   dup 0= if
                   2203:     -10 throw \ report division by zero
                   2204:   endif
                   2205:   /           \ old version
                   2206: ;
                   2207: 1 0 /
                   2208: @end example
                   2209: 
                   2210: For recursive definitions you can use @code{recursive} (non-standard) or
                   2211: @code{recurse}:
                   2212: 
                   2213: @example
                   2214: : fac1 ( n -- n! ) recursive
                   2215:  dup 0> if
                   2216:    dup 1- fac1 *
                   2217:  else
                   2218:    drop 1
                   2219:  endif ;
                   2220: 7 fac1 .
                   2221: 
                   2222: : fac2 ( n -- n! )
                   2223:  dup 0> if
                   2224:    dup 1- recurse *
                   2225:  else
                   2226:    drop 1
                   2227:  endif ;
                   2228: 8 fac2 .
                   2229: @end example
                   2230: 
1.141     anton    2231: @quotation Assignment
1.48      anton    2232: Write a recursive definition for computing the nth Fibonacci number.
1.141     anton    2233: @end quotation
1.48      anton    2234: 
1.66      anton    2235: Reference (including indirect recursion): @xref{Calls and returns}.
                   2236: 
1.48      anton    2237: 
                   2238: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
                   2239: @section Leaving definitions or loops
1.66      anton    2240: @cindex leaving definitions, tutorial
                   2241: @cindex leaving loops, tutorial
1.48      anton    2242: 
                   2243: @code{EXIT} exits the current definition right away.  For every counted
                   2244: loop that is left in this way, an @code{UNLOOP} has to be performed
                   2245: before the @code{EXIT}:
                   2246: 
                   2247: @c !! real examples
                   2248: @example
                   2249: : ...
                   2250:  ... u+do
                   2251:    ... if
                   2252:      ... unloop exit
                   2253:    endif
                   2254:    ...
                   2255:  loop
                   2256:  ... ;
                   2257: @end example
                   2258: 
                   2259: @code{LEAVE} leaves the innermost counted loop right away:
                   2260: 
                   2261: @example
                   2262: : ...
                   2263:  ... u+do
                   2264:    ... if
                   2265:      ... leave
                   2266:    endif
                   2267:    ...
                   2268:  loop
                   2269:  ... ;
                   2270: @end example
                   2271: 
1.65      anton    2272: @c !! example
1.48      anton    2273: 
1.66      anton    2274: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
                   2275: 
                   2276: 
1.48      anton    2277: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
                   2278: @section Return Stack
1.66      anton    2279: @cindex return stack tutorial
1.48      anton    2280: 
                   2281: In addition to the data stack Forth also has a second stack, the return
                   2282: stack; most Forth systems store the return addresses of procedure calls
                   2283: there (thus its name).  Programmers can also use this stack:
                   2284: 
                   2285: @example
                   2286: : foo ( n1 n2 -- )
                   2287:  .s
                   2288:  >r .s
1.50      anton    2289:  r@@ .
1.48      anton    2290:  >r .s
1.50      anton    2291:  r@@ .
1.48      anton    2292:  r> .
1.50      anton    2293:  r@@ .
1.48      anton    2294:  r> . ;
                   2295: 1 2 foo
                   2296: @end example
                   2297: 
                   2298: @code{>r} takes an element from the data stack and pushes it onto the
                   2299: return stack; conversely, @code{r>} moves an elementm from the return to
                   2300: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148     anton    2301: on the data stack.
1.48      anton    2302: 
                   2303: Forth programmers usually use the return stack for storing data
                   2304: temporarily, if using the data stack alone would be too complex, and
                   2305: factoring and locals are not an option:
                   2306: 
                   2307: @example
                   2308: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
                   2309:  rot >r rot r> ;
                   2310: @end example
                   2311: 
                   2312: The return address of the definition and the loop control parameters of
                   2313: counted loops usually reside on the return stack, so you have to take
                   2314: all items, that you have pushed on the return stack in a colon
                   2315: definition or counted loop, from the return stack before the definition
                   2316: or loop ends.  You cannot access items that you pushed on the return
                   2317: stack outside some definition or loop within the definition of loop.
                   2318: 
                   2319: If you miscount the return stack items, this usually ends in a crash:
                   2320: 
                   2321: @example
                   2322: : crash ( n -- )
                   2323:   >r ;
                   2324: 5 crash
                   2325: @end example
                   2326: 
                   2327: You cannot mix using locals and using the return stack (according to the
                   2328: standard; Gforth has no problem).  However, they solve the same
                   2329: problems, so this shouldn't be an issue.
                   2330: 
1.141     anton    2331: @quotation Assignment
1.48      anton    2332: Can you rewrite any of the definitions you wrote until now in a better
                   2333: way using the return stack?
1.141     anton    2334: @end quotation
1.48      anton    2335: 
1.66      anton    2336: Reference: @ref{Return stack}.
                   2337: 
1.48      anton    2338: 
                   2339: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
                   2340: @section Memory
1.66      anton    2341: @cindex memory access/allocation tutorial
1.48      anton    2342: 
                   2343: You can create a global variable @code{v} with
                   2344: 
                   2345: @example
                   2346: variable v ( -- addr )
                   2347: @end example
                   2348: 
                   2349: @code{v} pushes the address of a cell in memory on the stack.  This cell
                   2350: was reserved by @code{variable}.  You can use @code{!} (store) to store
                   2351: values into this cell and @code{@@} (fetch) to load the value from the
                   2352: stack into memory:
                   2353: 
                   2354: @example
                   2355: v .
                   2356: 5 v ! .s
1.50      anton    2357: v @@ .
1.48      anton    2358: @end example
                   2359: 
1.65      anton    2360: You can see a raw dump of memory with @code{dump}:
                   2361: 
                   2362: @example
                   2363: v 1 cells .s dump
                   2364: @end example
                   2365: 
                   2366: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
                   2367: generally, address units (aus)) that @code{n1 cells} occupy.  You can
                   2368: also reserve more memory:
1.48      anton    2369: 
                   2370: @example
                   2371: create v2 20 cells allot
1.65      anton    2372: v2 20 cells dump
1.48      anton    2373: @end example
                   2374: 
1.212     anton    2375: creates a variable-like word @code{v2} and reserves 20 uninitialized
                   2376: cells; the address pushed by @code{v2} points to the start of these 20
                   2377: cells (@pxref{CREATE}).  You can use address arithmetic to access
                   2378: these cells:
1.48      anton    2379: 
                   2380: @example
                   2381: 3 v2 5 cells + !
1.65      anton    2382: v2 20 cells dump
1.48      anton    2383: @end example
                   2384: 
                   2385: You can reserve and initialize memory with @code{,}:
                   2386: 
                   2387: @example
                   2388: create v3
                   2389:   5 , 4 , 3 , 2 , 1 ,
1.50      anton    2390: v3 @@ .
                   2391: v3 cell+ @@ .
                   2392: v3 2 cells + @@ .
1.65      anton    2393: v3 5 cells dump
1.48      anton    2394: @end example
                   2395: 
1.141     anton    2396: @quotation Assignment
1.48      anton    2397: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
                   2398: @code{u} cells, with the first of these cells at @code{addr}, the next
                   2399: one at @code{addr cell+} etc.
1.141     anton    2400: @end quotation
1.48      anton    2401: 
1.214     anton    2402: The difference between @code{variable} and @code{create} is that
                   2403: @code{variable} allots a cell, and that you cannot allot additional
                   2404: memory to a variable in standard Forth.
                   2405: 
1.48      anton    2406: You can also reserve memory without creating a new word:
                   2407: 
                   2408: @example
1.60      anton    2409: here 10 cells allot .
                   2410: here .
1.48      anton    2411: @end example
                   2412: 
1.211     anton    2413: The first @code{here} pushes the start address of the memory area, the
                   2414: second @code{here} the address after the dictionary area.  You should
                   2415: store the start address somewhere, or you will have a hard time
                   2416: finding the memory area again.
1.48      anton    2417: 
                   2418: @code{Allot} manages dictionary memory.  The dictionary memory contains
                   2419: the system's data structures for words etc. on Gforth and most other
                   2420: Forth systems.  It is managed like a stack: You can free the memory that
                   2421: you have just @code{allot}ed with
                   2422: 
                   2423: @example
                   2424: -10 cells allot
1.60      anton    2425: here .
1.48      anton    2426: @end example
                   2427: 
                   2428: Note that you cannot do this if you have created a new word in the
                   2429: meantime (because then your @code{allot}ed memory is no longer on the
                   2430: top of the dictionary ``stack'').
                   2431: 
                   2432: Alternatively, you can use @code{allocate} and @code{free} which allow
                   2433: freeing memory in any order:
                   2434: 
                   2435: @example
                   2436: 10 cells allocate throw .s
                   2437: 20 cells allocate throw .s
                   2438: swap
                   2439: free throw
                   2440: free throw
                   2441: @end example
                   2442: 
                   2443: The @code{throw}s deal with errors (e.g., out of memory).
                   2444: 
1.65      anton    2445: And there is also a
                   2446: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   2447: garbage collector}, which eliminates the need to @code{free} memory
                   2448: explicitly.
1.48      anton    2449: 
1.66      anton    2450: Reference: @ref{Memory}.
                   2451: 
1.48      anton    2452: 
                   2453: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
                   2454: @section Characters and Strings
1.66      anton    2455: @cindex strings tutorial
                   2456: @cindex characters tutorial
1.48      anton    2457: 
                   2458: On the stack characters take up a cell, like numbers.  In memory they
                   2459: have their own size (one 8-bit byte on most systems), and therefore
                   2460: require their own words for memory access:
                   2461: 
                   2462: @example
                   2463: create v4 
                   2464:   104 c, 97 c, 108 c, 108 c, 111 c,
1.50      anton    2465: v4 4 chars + c@@ .
1.65      anton    2466: v4 5 chars dump
1.48      anton    2467: @end example
                   2468: 
                   2469: The preferred representation of strings on the stack is @code{addr
                   2470: u-count}, where @code{addr} is the address of the first character and
                   2471: @code{u-count} is the number of characters in the string.
                   2472: 
                   2473: @example
                   2474: v4 5 type
                   2475: @end example
                   2476: 
                   2477: You get a string constant with
                   2478: 
                   2479: @example
                   2480: s" hello, world" .s
                   2481: type
                   2482: @end example
                   2483: 
                   2484: Make sure you have a space between @code{s"} and the string; @code{s"}
                   2485: is a normal Forth word and must be delimited with white space (try what
                   2486: happens when you remove the space).
                   2487: 
                   2488: However, this interpretive use of @code{s"} is quite restricted: the
                   2489: string exists only until the next call of @code{s"} (some Forth systems
                   2490: keep more than one of these strings, but usually they still have a
1.62      crook    2491: limited lifetime).
1.48      anton    2492: 
                   2493: @example
                   2494: s" hello," s" world" .s
                   2495: type
                   2496: type
                   2497: @end example
                   2498: 
1.62      crook    2499: You can also use @code{s"} in a definition, and the resulting
                   2500: strings then live forever (well, for as long as the definition):
1.48      anton    2501: 
                   2502: @example
                   2503: : foo s" hello," s" world" ;
                   2504: foo .s
                   2505: type
                   2506: type
                   2507: @end example
                   2508: 
1.141     anton    2509: @quotation Assignment
1.48      anton    2510: @code{Emit ( c -- )} types @code{c} as character (not a number).
                   2511: Implement @code{type ( addr u -- )}.
1.141     anton    2512: @end quotation
1.48      anton    2513: 
1.66      anton    2514: Reference: @ref{Memory Blocks}.
                   2515: 
                   2516: 
1.190     anton    2517: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
1.48      anton    2518: @section Alignment
1.66      anton    2519: @cindex alignment tutorial
                   2520: @cindex memory alignment tutorial
1.48      anton    2521: 
                   2522: On many processors cells have to be aligned in memory, if you want to
                   2523: access them with @code{@@} and @code{!} (and even if the processor does
1.62      crook    2524: not require alignment, access to aligned cells is faster).
1.48      anton    2525: 
                   2526: @code{Create} aligns @code{here} (i.e., the place where the next
                   2527: allocation will occur, and that the @code{create}d word points to).
                   2528: Likewise, the memory produced by @code{allocate} starts at an aligned
                   2529: address.  Adding a number of @code{cells} to an aligned address produces
                   2530: another aligned address.
                   2531: 
                   2532: However, address arithmetic involving @code{char+} and @code{chars} can
                   2533: create an address that is not cell-aligned.  @code{Aligned ( addr --
                   2534: a-addr )} produces the next aligned address:
                   2535: 
                   2536: @example
1.50      anton    2537: v3 char+ aligned .s @@ .
                   2538: v3 char+ .s @@ .
1.48      anton    2539: @end example
                   2540: 
                   2541: Similarly, @code{align} advances @code{here} to the next aligned
                   2542: address:
                   2543: 
                   2544: @example
                   2545: create v5 97 c,
                   2546: here .
                   2547: align here .
                   2548: 1000 ,
                   2549: @end example
                   2550: 
                   2551: Note that you should use aligned addresses even if your processor does
                   2552: not require them, if you want your program to be portable.
                   2553: 
1.66      anton    2554: Reference: @ref{Address arithmetic}.
                   2555: 
1.190     anton    2556: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
                   2557: @section Floating Point
                   2558: @cindex floating point tutorial
                   2559: @cindex FP tutorial
                   2560: 
                   2561: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
                   2562: might expect, but there are a few things worth noting:
                   2563: 
                   2564: The first point is not specific to Forth, but so important and yet not
                   2565: universally known that I mention it here: FP numbers are not reals.
                   2566: Many properties (e.g., arithmetic laws) that reals have and that one
                   2567: expects of all kinds of numbers do not hold for FP numbers.  If you
                   2568: want to use FP computations, you should learn about their problems and
                   2569: how to avoid them; a good starting point is @cite{David Goldberg,
                   2570: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
                   2571: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
                   2572: Computing Surveys 23(1):5@minus{}48, March 1991}.
                   2573: 
                   2574: In Forth source code literal FP numbers need an exponent, e.g.,
1.210     anton    2575: @code{1e0}; this can also be written shorter as @code{1e}, longer as
                   2576: @code{+1.0e+0}, and many variations in between.  The reason for this is
                   2577: that, for historical reasons, Forth interprets a decimal point alone
                   2578: (e.g., @code{1.}) as indicating a double-cell integer.  Examples:
                   2579: 
                   2580: @example
                   2581: 2e 2e f+ f.
                   2582: @end example
                   2583: 
                   2584: Another requirement for literal FP numbers is that the current base is
1.190     anton    2585: decimal; with a hex base @code{1e} is interpreted as an integer.
                   2586: 
                   2587: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
                   2588: ANS Forth system may implement the FP stack on the data stack, but
                   2589: virtually all systems implement a separate FP stack; and programming
                   2590: in a way that accommodates all models is so cumbersome that nobody
                   2591: does it.}  One advantage of this model is that cells are not in the
                   2592: way when accessing FP values, and vice versa.  Forth has a set of
                   2593: words for manipulating the FP stack: @code{fdup fswap fdrop fover
                   2594: frot} and (non-standard) @code{fnip ftuck fpick}.
                   2595: 
                   2596: FP arithmetic words are prefixed with @code{F}.  There is the usual
                   2597: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
                   2598: other functions, e.g., @code{fsqrt fsin fln fmin}.  One word that you
                   2599: might expect is @code{f=}; but @code{f=} is non-standard, because FP
                   2600: computation results are usually inaccurate, so exact comparison is
                   2601: usually a mistake, and one should use approximate comparison.
                   2602: Unfortunately, @code{f~}, the standard word for that purpose, is not
                   2603: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
                   2604: well.
                   2605: 
                   2606: And of course there are words for accessing FP numbers in memory
                   2607: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
                   2608: faligned}).  There are also variants of these words with an @code{sf}
                   2609: and @code{df} prefix for accessing IEEE format single-precision and
                   2610: double-precision numbers in memory; their main purpose is for
                   2611: accessing external FP data (e.g., that has been read from or will be
                   2612: written to a file).
                   2613: 
                   2614: Here is an example of a dot-product word and its use:
                   2615: 
                   2616: @example
                   2617: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   2618:   >r swap 2swap swap 0e r> 0 ?DO
                   2619:     dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
                   2620:   LOOP
                   2621:   2drop 2drop ;
1.48      anton    2622: 
1.190     anton    2623: create v 1.23e f, 4.56e f, 7.89e f,
                   2624: 
                   2625: v 1 floats  v 1 floats  3  v* f.
                   2626: @end example
                   2627: 
                   2628: @quotation Assignment
                   2629: Write a program to solve a quadratic equation.  Then read @cite{Henry
                   2630: G. Baker,
                   2631: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
                   2632: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
                   2633: 33(1):30@minus{}39, January 1998}, and see if you can improve your
                   2634: program.  Finally, find a test case where the original and the
                   2635: improved version produce different results.
                   2636: @end quotation
                   2637: 
                   2638: Reference: @ref{Floating Point}; @ref{Floating point stack};
                   2639: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
                   2640: arithmetic}.
                   2641: 
                   2642: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
1.84      pazsan   2643: @section Files
                   2644: @cindex files tutorial
                   2645: 
                   2646: This section gives a short introduction into how to use files inside
                   2647: Forth. It's broken up into five easy steps:
                   2648: 
                   2649: @enumerate 1
                   2650: @item Opened an ASCII text file for input
                   2651: @item Opened a file for output
                   2652: @item Read input file until string matched (or some other condition matched)
                   2653: @item Wrote some lines from input ( modified or not) to output
                   2654: @item Closed the files.
                   2655: @end enumerate
                   2656: 
1.153     anton    2657: Reference: @ref{General files}.
                   2658: 
1.84      pazsan   2659: @subsection Open file for input
                   2660: 
                   2661: @example
                   2662: s" foo.in"  r/o open-file throw Value fd-in
                   2663: @end example
                   2664: 
                   2665: @subsection Create file for output
                   2666: 
                   2667: @example
                   2668: s" foo.out" w/o create-file throw Value fd-out
                   2669: @end example
                   2670: 
                   2671: The available file modes are r/o for read-only access, r/w for
                   2672: read-write access, and w/o for write-only access. You could open both
                   2673: files with r/w, too, if you like. All file words return error codes; for
                   2674: most applications, it's best to pass there error codes with @code{throw}
                   2675: to the outer error handler.
                   2676: 
                   2677: If you want words for opening and assigning, define them as follows:
                   2678: 
                   2679: @example
                   2680: 0 Value fd-in
                   2681: 0 Value fd-out
                   2682: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
                   2683: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
                   2684: @end example
                   2685: 
                   2686: Usage example:
                   2687: 
                   2688: @example
                   2689: s" foo.in" open-input
                   2690: s" foo.out" open-output
                   2691: @end example
                   2692: 
                   2693: @subsection Scan file for a particular line
                   2694: 
                   2695: @example
                   2696: 256 Constant max-line
                   2697: Create line-buffer  max-line 2 + allot
                   2698: 
                   2699: : scan-file ( addr u -- )
                   2700:   begin
                   2701:       line-buffer max-line fd-in read-line throw
                   2702:   while
                   2703:          >r 2dup line-buffer r> compare 0=
                   2704:      until
                   2705:   else
                   2706:      drop
                   2707:   then
                   2708:   2drop ;
                   2709: @end example
                   2710: 
                   2711: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94      anton    2712: the buffer at addr, and returns the number of bytes read, a flag that is
                   2713: false when the end of file is reached, and an error code.
1.84      pazsan   2714: 
                   2715: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
                   2716: returns zero if both strings are equal. It returns a positive number if
                   2717: the first string is lexically greater, a negative if the second string
                   2718: is lexically greater.
                   2719: 
                   2720: We haven't seen this loop here; it has two exits. Since the @code{while}
                   2721: exits with the number of bytes read on the stack, we have to clean up
                   2722: that separately; that's after the @code{else}.
                   2723: 
                   2724: Usage example:
                   2725: 
                   2726: @example
                   2727: s" The text I search is here" scan-file
                   2728: @end example
                   2729: 
                   2730: @subsection Copy input to output
                   2731: 
                   2732: @example
                   2733: : copy-file ( -- )
                   2734:   begin
                   2735:       line-buffer max-line fd-in read-line throw
                   2736:   while
1.194     anton    2737:       line-buffer swap fd-out write-line throw
1.229     anton    2738:   repeat 
                   2739:   drop ;
1.84      pazsan   2740: @end example
1.194     anton    2741: @c !! does not handle long lines, no newline at end of file
1.84      pazsan   2742: 
                   2743: @subsection Close files
                   2744: 
                   2745: @example
                   2746: fd-in close-file throw
                   2747: fd-out close-file throw
                   2748: @end example
                   2749: 
                   2750: Likewise, you can put that into definitions, too:
                   2751: 
                   2752: @example
                   2753: : close-input ( -- )  fd-in close-file throw ;
                   2754: : close-output ( -- )  fd-out close-file throw ;
                   2755: @end example
                   2756: 
1.141     anton    2757: @quotation Assignment
1.84      pazsan   2758: How could you modify @code{copy-file} so that it copies until a second line is
                   2759: matched? Can you write a program that extracts a section of a text file,
                   2760: given the line that starts and the line that terminates that section?
1.141     anton    2761: @end quotation
1.84      pazsan   2762: 
                   2763: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48      anton    2764: @section Interpretation and Compilation Semantics and Immediacy
1.66      anton    2765: @cindex semantics tutorial
                   2766: @cindex interpretation semantics tutorial
                   2767: @cindex compilation semantics tutorial
                   2768: @cindex immediate, tutorial
1.48      anton    2769: 
                   2770: When a word is compiled, it behaves differently from being interpreted.
                   2771: E.g., consider @code{+}:
                   2772: 
                   2773: @example
                   2774: 1 2 + .
                   2775: : foo + ;
                   2776: @end example
                   2777: 
                   2778: These two behaviours are known as compilation and interpretation
                   2779: semantics.  For normal words (e.g., @code{+}), the compilation semantics
                   2780: is to append the interpretation semantics to the currently defined word
                   2781: (@code{foo} in the example above).  I.e., when @code{foo} is executed
                   2782: later, the interpretation semantics of @code{+} (i.e., adding two
                   2783: numbers) will be performed.
                   2784: 
                   2785: However, there are words with non-default compilation semantics, e.g.,
                   2786: the control-flow words like @code{if}.  You can use @code{immediate} to
                   2787: change the compilation semantics of the last defined word to be equal to
                   2788: the interpretation semantics:
                   2789: 
                   2790: @example
                   2791: : [FOO] ( -- )
                   2792:  5 . ; immediate
                   2793: 
                   2794: [FOO]
                   2795: : bar ( -- )
                   2796:   [FOO] ;
                   2797: bar
                   2798: see bar
                   2799: @end example
                   2800: 
1.198     anton    2801: Two conventions to mark words with non-default compilation semantics are
1.48      anton    2802: names with brackets (more frequently used) and to write them all in
                   2803: upper case (less frequently used).
                   2804: 
                   2805: In Gforth (and many other systems) you can also remove the
                   2806: interpretation semantics with @code{compile-only} (the compilation
                   2807: semantics is derived from the original interpretation semantics):
                   2808: 
                   2809: @example
                   2810: : flip ( -- )
                   2811:  6 . ; compile-only \ but not immediate
                   2812: flip
                   2813: 
                   2814: : flop ( -- )
                   2815:  flip ;
                   2816: flop
                   2817: @end example
                   2818: 
                   2819: In this example the interpretation semantics of @code{flop} is equal to
                   2820: the original interpretation semantics of @code{flip}.
                   2821: 
                   2822: The text interpreter has two states: in interpret state, it performs the
                   2823: interpretation semantics of words it encounters; in compile state, it
                   2824: performs the compilation semantics of these words.
                   2825: 
                   2826: Among other things, @code{:} switches into compile state, and @code{;}
                   2827: switches back to interpret state.  They contain the factors @code{]}
                   2828: (switch to compile state) and @code{[} (switch to interpret state), that
                   2829: do nothing but switch the state.
                   2830: 
                   2831: @example
                   2832: : xxx ( -- )
                   2833:   [ 5 . ]
                   2834: ;
                   2835: 
                   2836: xxx
                   2837: see xxx
                   2838: @end example
                   2839: 
                   2840: These brackets are also the source of the naming convention mentioned
                   2841: above.
                   2842: 
1.66      anton    2843: Reference: @ref{Interpretation and Compilation Semantics}.
                   2844: 
1.48      anton    2845: 
                   2846: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
                   2847: @section Execution Tokens
1.66      anton    2848: @cindex execution tokens tutorial
                   2849: @cindex XT tutorial
1.48      anton    2850: 
                   2851: @code{' word} gives you the execution token (XT) of a word.  The XT is a
                   2852: cell representing the interpretation semantics of a word.  You can
                   2853: execute this semantics with @code{execute}:
                   2854: 
                   2855: @example
                   2856: ' + .s
                   2857: 1 2 rot execute .
                   2858: @end example
                   2859: 
                   2860: The XT is similar to a function pointer in C.  However, parameter
                   2861: passing through the stack makes it a little more flexible:
                   2862: 
                   2863: @example
                   2864: : map-array ( ... addr u xt -- ... )
1.50      anton    2865: \ executes xt ( ... x -- ... ) for every element of the array starting
                   2866: \ at addr and containing u elements
1.48      anton    2867:   @{ xt @}
                   2868:   cells over + swap ?do
1.50      anton    2869:     i @@ xt execute
1.48      anton    2870:   1 cells +loop ;
                   2871: 
                   2872: create a 3 , 4 , 2 , -1 , 4 ,
                   2873: a 5 ' . map-array .s
                   2874: 0 a 5 ' + map-array .
                   2875: s" max-n" environment? drop .s
                   2876: a 5 ' min map-array .
                   2877: @end example
                   2878: 
                   2879: You can use map-array with the XTs of words that consume one element
                   2880: more than they produce.  In theory you can also use it with other XTs,
                   2881: but the stack effect then depends on the size of the array, which is
                   2882: hard to understand.
                   2883: 
1.51      pazsan   2884: Since XTs are cell-sized, you can store them in memory and manipulate
                   2885: them on the stack like other cells.  You can also compile the XT into a
1.48      anton    2886: word with @code{compile,}:
                   2887: 
                   2888: @example
                   2889: : foo1 ( n1 n2 -- n )
                   2890:    [ ' + compile, ] ;
1.229     anton    2891: see foo1
1.48      anton    2892: @end example
                   2893: 
                   2894: This is non-standard, because @code{compile,} has no compilation
                   2895: semantics in the standard, but it works in good Forth systems.  For the
                   2896: broken ones, use
                   2897: 
                   2898: @example
                   2899: : [compile,] compile, ; immediate
                   2900: 
                   2901: : foo1 ( n1 n2 -- n )
                   2902:    [ ' + ] [compile,] ;
                   2903: see foo
                   2904: @end example
                   2905: 
                   2906: @code{'} is a word with default compilation semantics; it parses the
                   2907: next word when its interpretation semantics are executed, not during
                   2908: compilation:
                   2909: 
                   2910: @example
                   2911: : foo ( -- xt )
                   2912:   ' ;
                   2913: see foo
                   2914: : bar ( ... "word" -- ... )
                   2915:   ' execute ;
                   2916: see bar
1.60      anton    2917: 1 2 bar + .
1.48      anton    2918: @end example
                   2919: 
                   2920: You often want to parse a word during compilation and compile its XT so
                   2921: it will be pushed on the stack at run-time.  @code{[']} does this:
                   2922: 
                   2923: @example
                   2924: : xt-+ ( -- xt )
                   2925:   ['] + ;
                   2926: see xt-+
                   2927: 1 2 xt-+ execute .
                   2928: @end example
                   2929: 
                   2930: Many programmers tend to see @code{'} and the word it parses as one
                   2931: unit, and expect it to behave like @code{[']} when compiled, and are
                   2932: confused by the actual behaviour.  If you are, just remember that the
                   2933: Forth system just takes @code{'} as one unit and has no idea that it is
                   2934: a parsing word (attempts to convenience programmers in this issue have
                   2935: usually resulted in even worse pitfalls, see
1.66      anton    2936: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
                   2937: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48      anton    2938: 
                   2939: Note that the state of the interpreter does not come into play when
1.51      pazsan   2940: creating and executing XTs.  I.e., even when you execute @code{'} in
1.48      anton    2941: compile state, it still gives you the interpretation semantics.  And
                   2942: whatever that state is, @code{execute} performs the semantics
1.66      anton    2943: represented by the XT (i.e., for XTs produced with @code{'} the
                   2944: interpretation semantics).
                   2945: 
                   2946: Reference: @ref{Tokens for Words}.
1.48      anton    2947: 
                   2948: 
                   2949: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
                   2950: @section Exceptions
1.66      anton    2951: @cindex exceptions tutorial
1.48      anton    2952: 
                   2953: @code{throw ( n -- )} causes an exception unless n is zero.
                   2954: 
                   2955: @example
                   2956: 100 throw .s
                   2957: 0 throw .s
                   2958: @end example
                   2959: 
                   2960: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
                   2961: it catches exceptions and pushes the number of the exception on the
                   2962: stack (or 0, if the xt executed without exception).  If there was an
                   2963: exception, the stacks have the same depth as when entering @code{catch}:
                   2964: 
                   2965: @example
                   2966: .s
                   2967: 3 0 ' / catch .s
                   2968: 3 2 ' / catch .s
                   2969: @end example
                   2970: 
1.141     anton    2971: @quotation Assignment
1.48      anton    2972: Try the same with @code{execute} instead of @code{catch}.
1.141     anton    2973: @end quotation
1.48      anton    2974: 
                   2975: @code{Throw} always jumps to the dynamically next enclosing
                   2976: @code{catch}, even if it has to leave several call levels to achieve
                   2977: this:
                   2978: 
                   2979: @example
                   2980: : foo 100 throw ;
                   2981: : foo1 foo ." after foo" ;
1.51      pazsan   2982: : bar ['] foo1 catch ;
1.60      anton    2983: bar .
1.48      anton    2984: @end example
                   2985: 
                   2986: It is often important to restore a value upon leaving a definition, even
                   2987: if the definition is left through an exception.  You can ensure this
                   2988: like this:
                   2989: 
                   2990: @example
                   2991: : ...
                   2992:    save-x
1.51      pazsan   2993:    ['] word-changing-x catch ( ... n )
1.48      anton    2994:    restore-x
                   2995:    ( ... n ) throw ;
                   2996: @end example
                   2997: 
1.172     anton    2998: However, this is still not safe against, e.g., the user pressing
                   2999: @kbd{Ctrl-C} when execution is between the @code{catch} and
                   3000: @code{restore-x}.
                   3001: 
                   3002: Gforth provides an alternative exception handling syntax that is safe
                   3003: against such cases: @code{try ... restore ... endtry}.  If the code
                   3004: between @code{try} and @code{endtry} has an exception, the stack
                   3005: depths are restored, the exception number is pushed on the stack, and
                   3006: the execution continues right after @code{restore}.
1.48      anton    3007: 
1.172     anton    3008: The safer equivalent to the restoration code above is
1.48      anton    3009: 
                   3010: @example
                   3011: : ...
                   3012:   save-x
                   3013:   try
1.92      anton    3014:     word-changing-x 0
1.172     anton    3015:   restore
                   3016:     restore-x
                   3017:   endtry
1.48      anton    3018:   throw ;
                   3019: @end example
                   3020: 
1.66      anton    3021: Reference: @ref{Exception Handling}.
                   3022: 
1.48      anton    3023: 
                   3024: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
                   3025: @section Defining Words
1.66      anton    3026: @cindex defining words tutorial
                   3027: @cindex does> tutorial
                   3028: @cindex create...does> tutorial
                   3029: 
                   3030: @c before semantics?
1.48      anton    3031: 
                   3032: @code{:}, @code{create}, and @code{variable} are definition words: They
                   3033: define other words.  @code{Constant} is another definition word:
                   3034: 
                   3035: @example
                   3036: 5 constant foo
                   3037: foo .
                   3038: @end example
                   3039: 
                   3040: You can also use the prefixes @code{2} (double-cell) and @code{f}
                   3041: (floating point) with @code{variable} and @code{constant}.
                   3042: 
                   3043: You can also define your own defining words.  E.g.:
                   3044: 
                   3045: @example
                   3046: : variable ( "name" -- )
                   3047:   create 0 , ;
                   3048: @end example
                   3049: 
                   3050: You can also define defining words that create words that do something
                   3051: other than just producing their address:
                   3052: 
                   3053: @example
                   3054: : constant ( n "name" -- )
                   3055:   create ,
                   3056: does> ( -- n )
1.50      anton    3057:   ( addr ) @@ ;
1.48      anton    3058: 
                   3059: 5 constant foo
                   3060: foo .
                   3061: @end example
                   3062: 
                   3063: The definition of @code{constant} above ends at the @code{does>}; i.e.,
                   3064: @code{does>} replaces @code{;}, but it also does something else: It
                   3065: changes the last defined word such that it pushes the address of the
                   3066: body of the word and then performs the code after the @code{does>}
                   3067: whenever it is called.
                   3068: 
                   3069: In the example above, @code{constant} uses @code{,} to store 5 into the
                   3070: body of @code{foo}.  When @code{foo} executes, it pushes the address of
                   3071: the body onto the stack, then (in the code after the @code{does>})
                   3072: fetches the 5 from there.
                   3073: 
                   3074: The stack comment near the @code{does>} reflects the stack effect of the
                   3075: defined word, not the stack effect of the code after the @code{does>}
                   3076: (the difference is that the code expects the address of the body that
                   3077: the stack comment does not show).
                   3078: 
                   3079: You can use these definition words to do factoring in cases that involve
                   3080: (other) definition words.  E.g., a field offset is always added to an
                   3081: address.  Instead of defining
                   3082: 
                   3083: @example
                   3084: 2 cells constant offset-field1
                   3085: @end example
                   3086: 
                   3087: and using this like
                   3088: 
                   3089: @example
                   3090: ( addr ) offset-field1 +
                   3091: @end example
                   3092: 
                   3093: you can define a definition word
                   3094: 
                   3095: @example
                   3096: : simple-field ( n "name" -- )
                   3097:   create ,
                   3098: does> ( n1 -- n1+n )
1.50      anton    3099:   ( addr ) @@ + ;
1.48      anton    3100: @end example
1.21      crook    3101: 
1.48      anton    3102: Definition and use of field offsets now look like this:
1.21      crook    3103: 
1.48      anton    3104: @example
                   3105: 2 cells simple-field field1
1.60      anton    3106: create mystruct 4 cells allot
                   3107: mystruct .s field1 .s drop
1.48      anton    3108: @end example
1.21      crook    3109: 
1.48      anton    3110: If you want to do something with the word without performing the code
                   3111: after the @code{does>}, you can access the body of a @code{create}d word
                   3112: with @code{>body ( xt -- addr )}:
1.21      crook    3113: 
1.48      anton    3114: @example
                   3115: : value ( n "name" -- )
                   3116:   create ,
                   3117: does> ( -- n1 )
1.50      anton    3118:   @@ ;
1.48      anton    3119: : to ( n "name" -- )
                   3120:   ' >body ! ;
1.21      crook    3121: 
1.48      anton    3122: 5 value foo
                   3123: foo .
                   3124: 7 to foo
                   3125: foo .
                   3126: @end example
1.21      crook    3127: 
1.141     anton    3128: @quotation Assignment
1.48      anton    3129: Define @code{defer ( "name" -- )}, which creates a word that stores an
                   3130: XT (at the start the XT of @code{abort}), and upon execution
                   3131: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
                   3132: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
                   3133: recursion is one application of @code{defer}.
1.141     anton    3134: @end quotation
1.29      crook    3135: 
1.66      anton    3136: Reference: @ref{User-defined Defining Words}.
                   3137: 
                   3138: 
1.48      anton    3139: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
                   3140: @section Arrays and Records
1.66      anton    3141: @cindex arrays tutorial
                   3142: @cindex records tutorial
                   3143: @cindex structs tutorial
1.29      crook    3144: 
1.48      anton    3145: Forth has no standard words for defining data structures such as arrays
                   3146: and records (structs in C terminology), but you can build them yourself
                   3147: based on address arithmetic.  You can also define words for defining
                   3148: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29      crook    3149: 
1.48      anton    3150: One of the first projects a Forth newcomer sets out upon when learning
                   3151: about defining words is an array defining word (possibly for
                   3152: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
                   3153: learn something from it.  However, don't be disappointed when you later
                   3154: learn that you have little use for these words (inappropriate use would
1.198     anton    3155: be even worse).  I have not found a set of useful array words yet;
1.48      anton    3156: the needs are just too diverse, and named, global arrays (the result of
                   3157: naive use of defining words) are often not flexible enough (e.g.,
1.66      anton    3158: consider how to pass them as parameters).  Another such project is a set
                   3159: of words to help dealing with strings.
1.29      crook    3160: 
1.48      anton    3161: On the other hand, there is a useful set of record words, and it has
                   3162: been defined in @file{compat/struct.fs}; these words are predefined in
                   3163: Gforth.  They are explained in depth elsewhere in this manual (see
                   3164: @pxref{Structures}).  The @code{simple-field} example above is
                   3165: simplified variant of fields in this package.
1.21      crook    3166: 
                   3167: 
1.48      anton    3168: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
                   3169: @section @code{POSTPONE}
1.66      anton    3170: @cindex postpone tutorial
1.21      crook    3171: 
1.48      anton    3172: You can compile the compilation semantics (instead of compiling the
                   3173: interpretation semantics) of a word with @code{POSTPONE}:
1.21      crook    3174: 
1.48      anton    3175: @example
                   3176: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51      pazsan   3177:  POSTPONE + ; immediate
1.48      anton    3178: : foo ( n1 n2 -- n )
                   3179:  MY-+ ;
                   3180: 1 2 foo .
                   3181: see foo
                   3182: @end example
1.21      crook    3183: 
1.48      anton    3184: During the definition of @code{foo} the text interpreter performs the
                   3185: compilation semantics of @code{MY-+}, which performs the compilation
                   3186: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
                   3187: 
                   3188: This example also displays separate stack comments for the compilation
                   3189: semantics and for the stack effect of the compiled code.  For words with
                   3190: default compilation semantics these stack effects are usually not
                   3191: displayed; the stack effect of the compilation semantics is always
                   3192: @code{( -- )} for these words, the stack effect for the compiled code is
                   3193: the stack effect of the interpretation semantics.
                   3194: 
                   3195: Note that the state of the interpreter does not come into play when
                   3196: performing the compilation semantics in this way.  You can also perform
                   3197: it interpretively, e.g.:
                   3198: 
                   3199: @example
                   3200: : foo2 ( n1 n2 -- n )
                   3201:  [ MY-+ ] ;
                   3202: 1 2 foo .
                   3203: see foo
                   3204: @end example
1.21      crook    3205: 
1.48      anton    3206: However, there are some broken Forth systems where this does not always
1.62      crook    3207: work, and therefore this practice was been declared non-standard in
1.48      anton    3208: 1999.
                   3209: @c !! repair.fs
                   3210: 
                   3211: Here is another example for using @code{POSTPONE}:
1.44      crook    3212: 
1.48      anton    3213: @example
                   3214: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
                   3215:  POSTPONE negate POSTPONE + ; immediate compile-only
                   3216: : bar ( n1 n2 -- n )
                   3217:   MY-- ;
                   3218: 2 1 bar .
                   3219: see bar
                   3220: @end example
1.21      crook    3221: 
1.48      anton    3222: You can define @code{ENDIF} in this way:
1.21      crook    3223: 
1.48      anton    3224: @example
                   3225: : ENDIF ( Compilation: orig -- )
                   3226:   POSTPONE then ; immediate
                   3227: @end example
1.21      crook    3228: 
1.141     anton    3229: @quotation Assignment
1.48      anton    3230: Write @code{MY-2DUP} that has compilation semantics equivalent to
                   3231: @code{2dup}, but compiles @code{over over}.
1.141     anton    3232: @end quotation
1.29      crook    3233: 
1.66      anton    3234: @c !! @xref{Macros} for reference
                   3235: 
                   3236: 
1.48      anton    3237: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
                   3238: @section @code{Literal}
1.66      anton    3239: @cindex literal tutorial
1.29      crook    3240: 
1.48      anton    3241: You cannot @code{POSTPONE} numbers:
1.21      crook    3242: 
1.48      anton    3243: @example
                   3244: : [FOO] POSTPONE 500 ; immediate
1.21      crook    3245: @end example
                   3246: 
1.48      anton    3247: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29      crook    3248: 
1.48      anton    3249: @example
                   3250: : [FOO] ( compilation: --; run-time: -- n )
                   3251:   500 POSTPONE literal ; immediate
1.29      crook    3252: 
1.60      anton    3253: : flip [FOO] ;
1.48      anton    3254: flip .
                   3255: see flip
                   3256: @end example
1.29      crook    3257: 
1.48      anton    3258: @code{LITERAL} consumes a number at compile-time (when it's compilation
                   3259: semantics are executed) and pushes it at run-time (when the code it
                   3260: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
                   3261: number computed at compile time into the current word:
1.29      crook    3262: 
1.48      anton    3263: @example
                   3264: : bar ( -- n )
                   3265:   [ 2 2 + ] literal ;
                   3266: see bar
                   3267: @end example
1.29      crook    3268: 
1.141     anton    3269: @quotation Assignment
1.48      anton    3270: Write @code{]L} which allows writing the example above as @code{: bar (
                   3271: -- n ) [ 2 2 + ]L ;}
1.141     anton    3272: @end quotation
1.48      anton    3273: 
1.66      anton    3274: @c !! @xref{Macros} for reference
                   3275: 
1.48      anton    3276: 
                   3277: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
                   3278: @section Advanced macros
1.66      anton    3279: @cindex macros, advanced tutorial
                   3280: @cindex run-time code generation, tutorial
1.48      anton    3281: 
1.66      anton    3282: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
                   3283: Execution Tokens}.  It frequently performs @code{execute}, a relatively
                   3284: expensive operation in some Forth implementations.  You can use
1.48      anton    3285: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
                   3286: and produce a word that contains the word to be performed directly:
                   3287: 
                   3288: @c use ]] ... [[
                   3289: @example
                   3290: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
                   3291: \ at run-time, execute xt ( ... x -- ... ) for each element of the
                   3292: \ array beginning at addr and containing u elements
                   3293:   @{ xt @}
                   3294:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50      anton    3295:     POSTPONE i POSTPONE @@ xt compile,
1.48      anton    3296:   1 cells POSTPONE literal POSTPONE +loop ;
                   3297: 
                   3298: : sum-array ( addr u -- n )
                   3299:  0 rot rot [ ' + compile-map-array ] ;
                   3300: see sum-array
                   3301: a 5 sum-array .
                   3302: @end example
                   3303: 
                   3304: You can use the full power of Forth for generating the code; here's an
                   3305: example where the code is generated in a loop:
                   3306: 
                   3307: @example
                   3308: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
                   3309: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50      anton    3310:   POSTPONE tuck POSTPONE @@
1.48      anton    3311:   POSTPONE literal POSTPONE * POSTPONE +
                   3312:   POSTPONE swap POSTPONE cell+ ;
                   3313: 
                   3314: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51      pazsan   3315: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48      anton    3316:   0 postpone literal postpone swap
                   3317:   [ ' compile-vmul-step compile-map-array ]
                   3318:   postpone drop ;
                   3319: see compile-vmul
                   3320: 
                   3321: : a-vmul ( addr -- n )
1.51      pazsan   3322: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48      anton    3323:  [ a 5 compile-vmul ] ;
                   3324: see a-vmul
                   3325: a a-vmul .
                   3326: @end example
                   3327: 
                   3328: This example uses @code{compile-map-array} to show off, but you could
1.66      anton    3329: also use @code{map-array} instead (try it now!).
1.48      anton    3330: 
                   3331: You can use this technique for efficient multiplication of large
                   3332: matrices.  In matrix multiplication, you multiply every line of one
                   3333: matrix with every column of the other matrix.  You can generate the code
                   3334: for one line once, and use it for every column.  The only downside of
                   3335: this technique is that it is cumbersome to recover the memory consumed
                   3336: by the generated code when you are done (and in more complicated cases
                   3337: it is not possible portably).
                   3338: 
1.66      anton    3339: @c !! @xref{Macros} for reference
                   3340: 
                   3341: 
1.48      anton    3342: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
                   3343: @section Compilation Tokens
1.66      anton    3344: @cindex compilation tokens, tutorial
                   3345: @cindex CT, tutorial
1.48      anton    3346: 
                   3347: This section is Gforth-specific.  You can skip it.
                   3348: 
                   3349: @code{' word compile,} compiles the interpretation semantics.  For words
                   3350: with default compilation semantics this is the same as performing the
                   3351: compilation semantics.  To represent the compilation semantics of other
                   3352: words (e.g., words like @code{if} that have no interpretation
                   3353: semantics), Gforth has the concept of a compilation token (CT,
                   3354: consisting of two cells), and words @code{comp'} and @code{[comp']}.
                   3355: You can perform the compilation semantics represented by a CT with
                   3356: @code{execute}:
1.29      crook    3357: 
1.48      anton    3358: @example
                   3359: : foo2 ( n1 n2 -- n )
                   3360:    [ comp' + execute ] ;
                   3361: see foo
                   3362: @end example
1.29      crook    3363: 
1.48      anton    3364: You can compile the compilation semantics represented by a CT with
                   3365: @code{postpone,}:
1.30      anton    3366: 
1.48      anton    3367: @example
                   3368: : foo3 ( -- )
                   3369:   [ comp' + postpone, ] ;
                   3370: see foo3
                   3371: @end example
1.30      anton    3372: 
1.51      pazsan   3373: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48      anton    3374: @code{comp'} is particularly useful for words that have no
                   3375: interpretation semantics:
1.29      crook    3376: 
1.30      anton    3377: @example
1.48      anton    3378: ' if
1.60      anton    3379: comp' if .s 2drop
1.30      anton    3380: @end example
                   3381: 
1.66      anton    3382: Reference: @ref{Tokens for Words}.
                   3383: 
1.29      crook    3384: 
1.48      anton    3385: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
                   3386: @section Wordlists and Search Order
1.66      anton    3387: @cindex wordlists tutorial
                   3388: @cindex search order, tutorial
1.48      anton    3389: 
                   3390: The dictionary is not just a memory area that allows you to allocate
                   3391: memory with @code{allot}, it also contains the Forth words, arranged in
                   3392: several wordlists.  When searching for a word in a wordlist,
                   3393: conceptually you start searching at the youngest and proceed towards
                   3394: older words (in reality most systems nowadays use hash-tables); i.e., if
                   3395: you define a word with the same name as an older word, the new word
                   3396: shadows the older word.
                   3397: 
                   3398: Which wordlists are searched in which order is determined by the search
                   3399: order.  You can display the search order with @code{order}.  It displays
                   3400: first the search order, starting with the wordlist searched first, then
                   3401: it displays the wordlist that will contain newly defined words.
1.21      crook    3402: 
1.48      anton    3403: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21      crook    3404: 
1.48      anton    3405: @example
                   3406: wordlist constant mywords
                   3407: @end example
1.21      crook    3408: 
1.48      anton    3409: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
                   3410: defined words (the @emph{current} wordlist):
1.21      crook    3411: 
1.48      anton    3412: @example
                   3413: mywords set-current
                   3414: order
                   3415: @end example
1.26      crook    3416: 
1.48      anton    3417: Gforth does not display a name for the wordlist in @code{mywords}
                   3418: because this wordlist was created anonymously with @code{wordlist}.
1.21      crook    3419: 
1.48      anton    3420: You can get the current wordlist with @code{get-current ( -- wid)}.  If
                   3421: you want to put something into a specific wordlist without overall
                   3422: effect on the current wordlist, this typically looks like this:
1.21      crook    3423: 
1.48      anton    3424: @example
                   3425: get-current mywords set-current ( wid )
                   3426: create someword
                   3427: ( wid ) set-current
                   3428: @end example
1.21      crook    3429: 
1.48      anton    3430: You can write the search order with @code{set-order ( wid1 .. widn n --
                   3431: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
                   3432: searched wordlist is topmost.
1.21      crook    3433: 
1.48      anton    3434: @example
                   3435: get-order mywords swap 1+ set-order
                   3436: order
                   3437: @end example
1.21      crook    3438: 
1.48      anton    3439: Yes, the order of wordlists in the output of @code{order} is reversed
                   3440: from stack comments and the output of @code{.s} and thus unintuitive.
1.21      crook    3441: 
1.141     anton    3442: @quotation Assignment
1.48      anton    3443: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
                   3444: wordlist to the search order.  Define @code{previous ( -- )}, which
                   3445: removes the first searched wordlist from the search order.  Experiment
                   3446: with boundary conditions (you will see some crashes or situations that
                   3447: are hard or impossible to leave).
1.141     anton    3448: @end quotation
1.21      crook    3449: 
1.48      anton    3450: The search order is a powerful foundation for providing features similar
                   3451: to Modula-2 modules and C++ namespaces.  However, trying to modularize
                   3452: programs in this way has disadvantages for debugging and reuse/factoring
                   3453: that overcome the advantages in my experience (I don't do huge projects,
1.55      anton    3454: though).  These disadvantages are not so clear in other
1.82      anton    3455: languages/programming environments, because these languages are not so
1.48      anton    3456: strong in debugging and reuse.
1.21      crook    3457: 
1.66      anton    3458: @c !! example
                   3459: 
                   3460: Reference: @ref{Word Lists}.
1.21      crook    3461: 
1.29      crook    3462: @c ******************************************************************
1.48      anton    3463: @node Introduction, Words, Tutorial, Top
1.29      crook    3464: @comment node-name,     next,           previous, up
                   3465: @chapter An Introduction to ANS Forth
                   3466: @cindex Forth - an introduction
1.21      crook    3467: 
1.83      anton    3468: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
                   3469: that it is slower-paced in its examples, but uses them to dive deep into
                   3470: explaining Forth internals (not covered by the Tutorial).  Apart from
                   3471: that, this chapter covers far less material.  It is suitable for reading
                   3472: without using a computer.
                   3473: 
1.29      crook    3474: The primary purpose of this manual is to document Gforth. However, since
                   3475: Forth is not a widely-known language and there is a lack of up-to-date
                   3476: teaching material, it seems worthwhile to provide some introductory
1.49      anton    3477: material.  For other sources of Forth-related
                   3478: information, see @ref{Forth-related information}.
1.21      crook    3479: 
1.29      crook    3480: The examples in this section should work on any ANS Forth; the
                   3481: output shown was produced using Gforth. Each example attempts to
                   3482: reproduce the exact output that Gforth produces. If you try out the
                   3483: examples (and you should), what you should type is shown @kbd{like this}
                   3484: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    3485: that, where the example shows @key{RET} it means that you should
1.29      crook    3486: press the ``carriage return'' key. Unfortunately, some output formats for
                   3487: this manual cannot show the difference between @kbd{this} and
                   3488: @code{this} which will make trying out the examples harder (but not
                   3489: impossible).
1.21      crook    3490: 
1.29      crook    3491: Forth is an unusual language. It provides an interactive development
                   3492: environment which includes both an interpreter and compiler. Forth
                   3493: programming style encourages you to break a problem down into many
                   3494: @cindex factoring
                   3495: small fragments (@dfn{factoring}), and then to develop and test each
                   3496: fragment interactively. Forth advocates assert that breaking the
                   3497: edit-compile-test cycle used by conventional programming languages can
                   3498: lead to great productivity improvements.
1.21      crook    3499: 
1.29      crook    3500: @menu
1.67      anton    3501: * Introducing the Text Interpreter::  
                   3502: * Stacks and Postfix notation::  
                   3503: * Your first definition::       
                   3504: * How does that work?::         
                   3505: * Forth is written in Forth::   
                   3506: * Review - elements of a Forth system::  
                   3507: * Where to go next::            
                   3508: * Exercises::                   
1.29      crook    3509: @end menu
1.21      crook    3510: 
1.29      crook    3511: @comment ----------------------------------------------
                   3512: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   3513: @section Introducing the Text Interpreter
                   3514: @cindex text interpreter
                   3515: @cindex outer interpreter
1.21      crook    3516: 
1.30      anton    3517: @c IMO this is too detailed and the pace is too slow for
                   3518: @c an introduction.  If you know German, take a look at
                   3519: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   3520: @c to see how I do it - anton 
                   3521: 
1.44      crook    3522: @c nac-> Where I have accepted your comments 100% and modified the text
                   3523: @c accordingly, I have deleted your comments. Elsewhere I have added a
                   3524: @c response like this to attempt to rationalise what I have done. Of
                   3525: @c course, this is a very clumsy mechanism for something that would be
                   3526: @c done far more efficiently over a beer. Please delete any dialogue
                   3527: @c you consider closed.
                   3528: 
1.29      crook    3529: When you invoke the Forth image, you will see a startup banner printed
                   3530: and nothing else (if you have Gforth installed on your system, try
1.30      anton    3531: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    3532: its command line interpreter, which is called the @dfn{Text Interpreter}
                   3533: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.49      anton    3534: about the text interpreter as you read through this chapter, for more
                   3535: detail @pxref{The Text Interpreter}).
1.21      crook    3536: 
1.29      crook    3537: Although it's not obvious, Forth is actually waiting for your
1.30      anton    3538: input. Type a number and press the @key{RET} key:
1.21      crook    3539: 
1.26      crook    3540: @example
1.30      anton    3541: @kbd{45@key{RET}}  ok
1.26      crook    3542: @end example
1.21      crook    3543: 
1.29      crook    3544: Rather than give you a prompt to invite you to input something, the text
                   3545: interpreter prints a status message @i{after} it has processed a line
                   3546: of input. The status message in this case (``@code{ ok}'' followed by
                   3547: carriage-return) indicates that the text interpreter was able to process
                   3548: all of your input successfully. Now type something illegal:
                   3549: 
                   3550: @example
1.30      anton    3551: @kbd{qwer341@key{RET}}
1.134     anton    3552: *the terminal*:2: Undefined word
                   3553: >>>qwer341<<<
                   3554: Backtrace:
                   3555: $2A95B42A20 throw 
                   3556: $2A95B57FB8 no.extensions 
1.29      crook    3557: @end example
1.23      crook    3558: 
1.134     anton    3559: The exact text, other than the ``Undefined word'' may differ slightly
                   3560: on your system, but the effect is the same; when the text interpreter
1.29      crook    3561: detects an error, it discards any remaining text on a line, resets
1.134     anton    3562: certain internal state and prints an error message. For a detailed
                   3563: description of error messages see @ref{Error messages}.
1.23      crook    3564: 
1.29      crook    3565: The text interpreter waits for you to press carriage-return, and then
                   3566: processes your input line. Starting at the beginning of the line, it
                   3567: breaks the line into groups of characters separated by spaces. For each
                   3568: group of characters in turn, it makes two attempts to do something:
1.23      crook    3569: 
1.29      crook    3570: @itemize @bullet
                   3571: @item
1.44      crook    3572: @cindex name dictionary
1.29      crook    3573: It tries to treat it as a command. It does this by searching a @dfn{name
                   3574: dictionary}. If the group of characters matches an entry in the name
                   3575: dictionary, the name dictionary provides the text interpreter with
                   3576: information that allows the text interpreter perform some actions. In
                   3577: Forth jargon, we say that the group
                   3578: @cindex word
                   3579: @cindex definition
                   3580: @cindex execution token
                   3581: @cindex xt
                   3582: of characters names a @dfn{word}, that the dictionary search returns an
                   3583: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   3584: word, and that the text interpreter executes the xt. Often, the terms
                   3585: @dfn{word} and @dfn{definition} are used interchangeably.
                   3586: @item
                   3587: If the text interpreter fails to find a match in the name dictionary, it
                   3588: tries to treat the group of characters as a number in the current number
                   3589: base (when you start up Forth, the current number base is base 10). If
                   3590: the group of characters legitimately represents a number, the text
                   3591: interpreter pushes the number onto a stack (we'll learn more about that
                   3592: in the next section).
                   3593: @end itemize
1.23      crook    3594: 
1.29      crook    3595: If the text interpreter is unable to do either of these things with any
                   3596: group of characters, it discards the group of characters and the rest of
                   3597: the line, then prints an error message. If the text interpreter reaches
                   3598: the end of the line without error, it prints the status message ``@code{ ok}''
                   3599: followed by carriage-return.
1.21      crook    3600: 
1.29      crook    3601: This is the simplest command we can give to the text interpreter:
1.23      crook    3602: 
                   3603: @example
1.30      anton    3604: @key{RET}  ok
1.23      crook    3605: @end example
1.21      crook    3606: 
1.29      crook    3607: The text interpreter did everything we asked it to do (nothing) without
                   3608: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   3609: command:
1.21      crook    3610: 
1.23      crook    3611: @example
1.30      anton    3612: @kbd{12 dup fred dup@key{RET}}
1.134     anton    3613: *the terminal*:3: Undefined word
                   3614: 12 dup >>>fred<<< dup
                   3615: Backtrace:
                   3616: $2A95B42A20 throw 
                   3617: $2A95B57FB8 no.extensions 
1.23      crook    3618: @end example
1.21      crook    3619: 
1.29      crook    3620: When you press the carriage-return key, the text interpreter starts to
                   3621: work its way along the line:
1.21      crook    3622: 
1.29      crook    3623: @itemize @bullet
                   3624: @item
                   3625: When it gets to the space after the @code{2}, it takes the group of
                   3626: characters @code{12} and looks them up in the name
                   3627: dictionary@footnote{We can't tell if it found them or not, but assume
                   3628: for now that it did not}. There is no match for this group of characters
                   3629: in the name dictionary, so it tries to treat them as a number. It is
                   3630: able to do this successfully, so it puts the number, 12, ``on the stack''
                   3631: (whatever that means).
                   3632: @item
                   3633: The text interpreter resumes scanning the line and gets the next group
                   3634: of characters, @code{dup}. It looks it up in the name dictionary and
                   3635: (you'll have to take my word for this) finds it, and executes the word
                   3636: @code{dup} (whatever that means).
                   3637: @item
                   3638: Once again, the text interpreter resumes scanning the line and gets the
                   3639: group of characters @code{fred}. It looks them up in the name
                   3640: dictionary, but can't find them. It tries to treat them as a number, but
                   3641: they don't represent any legal number.
                   3642: @end itemize
1.21      crook    3643: 
1.29      crook    3644: At this point, the text interpreter gives up and prints an error
                   3645: message. The error message shows exactly how far the text interpreter
                   3646: got in processing the line. In particular, it shows that the text
                   3647: interpreter made no attempt to do anything with the final character
                   3648: group, @code{dup}, even though we have good reason to believe that the
                   3649: text interpreter would have no problem looking that word up and
                   3650: executing it a second time.
1.21      crook    3651: 
                   3652: 
1.29      crook    3653: @comment ----------------------------------------------
                   3654: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   3655: @section Stacks, postfix notation and parameter passing
                   3656: @cindex text interpreter
                   3657: @cindex outer interpreter
1.21      crook    3658: 
1.29      crook    3659: In procedural programming languages (like C and Pascal), the
                   3660: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   3661: functions or procedures are called with @dfn{explicit parameters}. For
                   3662: example, in C we might write:
1.21      crook    3663: 
1.23      crook    3664: @example
1.29      crook    3665: total = total + new_volume(length,height,depth);
1.23      crook    3666: @end example
1.21      crook    3667: 
1.23      crook    3668: @noindent
1.29      crook    3669: where new_volume is a function-call to another piece of code, and total,
                   3670: length, height and depth are all variables. length, height and depth are
                   3671: parameters to the function-call.
1.21      crook    3672: 
1.29      crook    3673: In Forth, the equivalent of the function or procedure is the
                   3674: @dfn{definition} and parameters are implicitly passed between
                   3675: definitions using a shared stack that is visible to the
                   3676: programmer. Although Forth does support variables, the existence of the
                   3677: stack means that they are used far less often than in most other
                   3678: programming languages. When the text interpreter encounters a number, it
                   3679: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    3680: actual number is implementation-dependent ...) and the particular stack
1.29      crook    3681: used for any operation is implied unambiguously by the operation being
                   3682: performed. The stack used for all integer operations is called the @dfn{data
                   3683: stack} and, since this is the stack used most commonly, references to
                   3684: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    3685: 
1.29      crook    3686: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    3687: 
1.23      crook    3688: @example
1.30      anton    3689: @kbd{1 2 3@key{RET}}  ok
1.23      crook    3690: @end example
1.21      crook    3691: 
1.29      crook    3692: Then this instructs the text interpreter to placed three numbers on the
                   3693: (data) stack. An analogy for the behaviour of the stack is to take a
                   3694: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   3695: the table. The 3 was the last card onto the pile (``last-in'') and if
                   3696: you take a card off the pile then, unless you're prepared to fiddle a
                   3697: bit, the card that you take off will be the 3 (``first-out''). The
                   3698: number that will be first-out of the stack is called the @dfn{top of
                   3699: stack}, which
                   3700: @cindex TOS definition
                   3701: is often abbreviated to @dfn{TOS}.
1.21      crook    3702: 
1.29      crook    3703: To understand how parameters are passed in Forth, consider the
                   3704: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   3705: be surprised to learn that this definition performs addition. More
                   3706: precisely, it adds two number together and produces a result. Where does
                   3707: it get the two numbers from? It takes the top two numbers off the
                   3708: stack. Where does it place the result? On the stack. You can act-out the
                   3709: behaviour of @code{+} with your playing cards like this:
1.21      crook    3710: 
                   3711: @itemize @bullet
                   3712: @item
1.29      crook    3713: Pick up two cards from the stack on the table
1.21      crook    3714: @item
1.29      crook    3715: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   3716: numbers''
1.21      crook    3717: @item
1.29      crook    3718: Decide that the answer is 5
1.21      crook    3719: @item
1.29      crook    3720: Shuffle the two cards back into the pack and find a 5
1.21      crook    3721: @item
1.29      crook    3722: Put a 5 on the remaining ace that's on the table.
1.21      crook    3723: @end itemize
                   3724: 
1.29      crook    3725: If you don't have a pack of cards handy but you do have Forth running,
                   3726: you can use the definition @code{.s} to show the current state of the stack,
                   3727: without affecting the stack. Type:
1.21      crook    3728: 
                   3729: @example
1.124     anton    3730: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30      anton    3731: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    3732: @end example
                   3733: 
1.124     anton    3734: The text interpreter looks up the word @code{clearstacks} and executes
                   3735: it; it tidies up the stacks and removes any entries that may have been
1.29      crook    3736: left on it by earlier examples. The text interpreter pushes each of the
                   3737: three numbers in turn onto the stack. Finally, the text interpreter
                   3738: looks up the word @code{.s} and executes it. The effect of executing
                   3739: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   3740: followed by a list of all the items on the stack; the item on the far
                   3741: right-hand side is the TOS.
1.21      crook    3742: 
1.29      crook    3743: You can now type:
1.21      crook    3744: 
1.29      crook    3745: @example
1.30      anton    3746: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    3747: @end example
1.21      crook    3748: 
1.29      crook    3749: @noindent
                   3750: which is correct; there are now 2 items on the stack and the result of
                   3751: the addition is 5.
1.23      crook    3752: 
1.29      crook    3753: If you're playing with cards, try doing a second addition: pick up the
                   3754: two cards, work out that their sum is 6, shuffle them into the pack,
                   3755: look for a 6 and place that on the table. You now have just one item on
                   3756: the stack. What happens if you try to do a third addition? Pick up the
                   3757: first card, pick up the second card -- ah! There is no second card. This
                   3758: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95      anton    3759: do the same thing with Forth it often reports an error (probably a Stack
1.29      crook    3760: Underflow or an Invalid Memory Address error).
1.23      crook    3761: 
1.29      crook    3762: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   3763: which simply accepts that there is a finite amount of storage space
                   3764: reserved for the stack. To stretch the playing card analogy, if you had
                   3765: enough packs of cards and you piled the cards up on the table, you would
                   3766: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   3767: allows you to set the maximum size of the stacks. In general, the only
                   3768: time that you will get a stack overflow is because a definition has a
                   3769: bug in it and is generating data on the stack uncontrollably.
1.23      crook    3770: 
1.29      crook    3771: There's one final use for the playing card analogy. If you model your
                   3772: stack using a pack of playing cards, the maximum number of items on
                   3773: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   3774: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   3775: possible numbers are positive integer numbers 1 through 13; you can't
                   3776: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   3777: think about some of the cards, you can accommodate different
                   3778: numbers. For example, you could think of the Jack as representing 0,
                   3779: the Queen as representing -1 and the King as representing -2. Your
1.45      crook    3780: @i{range} remains unchanged (you can still only represent a total of 13
1.29      crook    3781: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    3782: 
1.29      crook    3783: In that analogy, the limit was the amount of information that a single
                   3784: stack entry could hold, and Forth has a similar limit. In Forth, the
                   3785: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   3786: implementation dependent and affects the maximum value that a stack
                   3787: entry can hold. A Standard Forth provides a cell size of at least
                   3788: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    3789: 
1.29      crook    3790: Forth does not do any type checking for you, so you are free to
                   3791: manipulate and combine stack items in any way you wish. A convenient way
                   3792: of treating stack items is as 2's complement signed integers, and that
                   3793: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    3794: 
1.29      crook    3795: @example
1.30      anton    3796: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    3797: @end example
1.21      crook    3798: 
1.29      crook    3799: If you use numbers and definitions like @code{+} in order to turn Forth
                   3800: into a great big pocket calculator, you will realise that it's rather
                   3801: different from a normal calculator. Rather than typing 2 + 3 = you had
                   3802: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   3803: result). The terminology used to describe this difference is to say that
                   3804: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   3805: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   3806: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    3807: 
1.29      crook    3808: Whilst postfix notation might look confusing to begin with, it has
                   3809: several important advantages:
1.21      crook    3810: 
1.23      crook    3811: @itemize @bullet
                   3812: @item
1.29      crook    3813: it is unambiguous
1.23      crook    3814: @item
1.29      crook    3815: it is more concise
1.23      crook    3816: @item
1.29      crook    3817: it fits naturally with a stack-based system
1.23      crook    3818: @end itemize
1.21      crook    3819: 
1.29      crook    3820: To examine these claims in more detail, consider these sums:
1.21      crook    3821: 
1.29      crook    3822: @example
                   3823: 6 + 5 * 4 =
                   3824: 4 * 5 + 6 =
                   3825: @end example
1.21      crook    3826: 
1.29      crook    3827: If you're just learning maths or your maths is very rusty, you will
                   3828: probably come up with the answer 44 for the first and 26 for the
                   3829: second. If you are a bit of a whizz at maths you will remember the
                   3830: @i{convention} that multiplication takes precendence over addition, and
                   3831: you'd come up with the answer 26 both times. To explain the answer 26
                   3832: to someone who got the answer 44, you'd probably rewrite the first sum
                   3833: like this:
1.21      crook    3834: 
1.29      crook    3835: @example
                   3836: 6 + (5 * 4) =
                   3837: @end example
1.21      crook    3838: 
1.29      crook    3839: If what you really wanted was to perform the addition before the
                   3840: multiplication, you would have to use parentheses to force it.
1.21      crook    3841: 
1.29      crook    3842: If you did the first two sums on a pocket calculator you would probably
                   3843: get the right answers, unless you were very cautious and entered them using
                   3844: these keystroke sequences:
1.21      crook    3845: 
1.29      crook    3846: 6 + 5 = * 4 =
                   3847: 4 * 5 = + 6 =
1.21      crook    3848: 
1.29      crook    3849: Postfix notation is unambiguous because the order that the operators
                   3850: are applied is always explicit; that also means that parentheses are
                   3851: never required. The operators are @i{active} (the act of quoting the
                   3852: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    3853: 
1.29      crook    3854: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   3855: equivalent ways:
1.26      crook    3856: 
                   3857: @example
1.29      crook    3858: 6 5 4 * +      or:
                   3859: 5 4 * 6 +
1.26      crook    3860: @end example
1.23      crook    3861: 
1.29      crook    3862: An important thing that you should notice about this notation is that
                   3863: the @i{order} of the numbers does not change; if you want to subtract
                   3864: 2 from 10 you type @code{10 2 -}.
1.1       anton    3865: 
1.29      crook    3866: The reason that Forth uses postfix notation is very simple to explain: it
                   3867: makes the implementation extremely simple, and it follows naturally from
                   3868: using the stack as a mechanism for passing parameters. Another way of
                   3869: thinking about this is to realise that all Forth definitions are
                   3870: @i{active}; they execute as they are encountered by the text
                   3871: interpreter. The result of this is that the syntax of Forth is trivially
                   3872: simple.
1.1       anton    3873: 
                   3874: 
                   3875: 
1.29      crook    3876: @comment ----------------------------------------------
                   3877: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   3878: @section Your first Forth definition
                   3879: @cindex first definition
1.1       anton    3880: 
1.29      crook    3881: Until now, the examples we've seen have been trivial; we've just been
                   3882: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   3883: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   3884: again@footnote{That's not quite true. If you press the up-arrow key on
                   3885: your keyboard you should be able to scroll back to any earlier command,
                   3886: edit it and re-enter it.} In this section we'll see how to add new
                   3887: words to Forth's vocabulary.
1.1       anton    3888: 
1.29      crook    3889: The easiest way to create a new word is to use a @dfn{colon
                   3890: definition}. We'll define a few and try them out before worrying too
                   3891: much about how they work. Try typing in these examples; be careful to
                   3892: copy the spaces accurately:
1.1       anton    3893: 
1.29      crook    3894: @example
                   3895: : add-two 2 + . ;
                   3896: : greet ." Hello and welcome" ;
                   3897: : demo 5 add-two ;
                   3898: @end example
1.1       anton    3899: 
1.29      crook    3900: @noindent
                   3901: Now try them out:
1.1       anton    3902: 
1.29      crook    3903: @example
1.30      anton    3904: @kbd{greet@key{RET}} Hello and welcome  ok
                   3905: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   3906: @kbd{4 add-two@key{RET}} 6  ok
                   3907: @kbd{demo@key{RET}} 7  ok
                   3908: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    3909: @end example
1.1       anton    3910: 
1.29      crook    3911: The first new thing that we've introduced here is the pair of words
                   3912: @code{:} and @code{;}. These are used to start and terminate a new
                   3913: definition, respectively. The first word after the @code{:} is the name
                   3914: for the new definition.
1.1       anton    3915: 
1.29      crook    3916: As you can see from the examples, a definition is built up of words that
                   3917: have already been defined; Forth makes no distinction between
                   3918: definitions that existed when you started the system up, and those that
                   3919: you define yourself.
1.1       anton    3920: 
1.29      crook    3921: The examples also introduce the words @code{.} (dot), @code{."}
                   3922: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   3923: the stack and displays it. It's like @code{.s} except that it only
                   3924: displays the top item of the stack and it is destructive; after it has
                   3925: executed, the number is no longer on the stack. There is always one
                   3926: space printed after the number, and no spaces before it. Dot-quote
                   3927: defines a string (a sequence of characters) that will be printed when
                   3928: the word is executed. The string can contain any printable characters
                   3929: except @code{"}. A @code{"} has a special function; it is not a Forth
                   3930: word but it acts as a delimiter (the way that delimiters work is
                   3931: described in the next section). Finally, @code{dup} duplicates the value
                   3932: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    3933: 
1.29      crook    3934: We already know that the text interpreter searches through the
                   3935: dictionary to locate names. If you've followed the examples earlier, you
                   3936: will already have a definition called @code{add-two}. Lets try modifying
                   3937: it by typing in a new definition:
1.1       anton    3938: 
1.29      crook    3939: @example
1.30      anton    3940: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    3941: @end example
1.5       anton    3942: 
1.29      crook    3943: Forth recognised that we were defining a word that already exists, and
                   3944: printed a message to warn us of that fact. Let's try out the new
                   3945: definition:
1.5       anton    3946: 
1.29      crook    3947: @example
1.30      anton    3948: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    3949: @end example
1.1       anton    3950: 
1.29      crook    3951: @noindent
                   3952: All that we've actually done here, though, is to create a new
                   3953: definition, with a particular name. The fact that there was already a
                   3954: definition with the same name did not make any difference to the way
                   3955: that the new definition was created (except that Forth printed a warning
                   3956: message). The old definition of add-two still exists (try @code{demo}
                   3957: again to see that this is true). Any new definition will use the new
                   3958: definition of @code{add-two}, but old definitions continue to use the
                   3959: version that already existed at the time that they were @code{compiled}.
1.1       anton    3960: 
1.29      crook    3961: Before you go on to the next section, try defining and redefining some
                   3962: words of your own.
1.1       anton    3963: 
1.29      crook    3964: @comment ----------------------------------------------
                   3965: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   3966: @section How does that work?
                   3967: @cindex parsing words
1.1       anton    3968: 
1.30      anton    3969: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   3970: 
                   3971: @c Is it a good idea to talk about the interpretation semantics of a
                   3972: @c number? We don't have an xt to go along with it. - anton
                   3973: 
                   3974: @c Now that I have eliminated execution semantics, I wonder if it would not
                   3975: @c be better to keep them (or add run-time semantics), to make it easier to
                   3976: @c explain what compilation semantics usually does. - anton
                   3977: 
1.44      crook    3978: @c nac-> I removed the term ``default compilation sematics'' from the
                   3979: @c introductory chapter. Removing ``execution semantics'' was making
                   3980: @c everything simpler to explain, then I think the use of this term made
                   3981: @c everything more complex again. I replaced it with ``default
                   3982: @c semantics'' (which is used elsewhere in the manual) by which I mean
                   3983: @c ``a definition that has neither the immediate nor the compile-only
1.83      anton    3984: @c flag set''.
                   3985: 
                   3986: @c anton: I have eliminated default semantics (except in one place where it
                   3987: @c means "default interpretation and compilation semantics"), because it
                   3988: @c makes no sense in the presence of combined words.  I reverted to
                   3989: @c "execution semantics" where necessary.
                   3990: 
                   3991: @c nac-> I reworded big chunks of the ``how does that work''
1.44      crook    3992: @c section (and, unusually for me, I think I even made it shorter!).  See
                   3993: @c what you think -- I know I have not addressed your primary concern
                   3994: @c that it is too heavy-going for an introduction. From what I understood
                   3995: @c of your course notes it looks as though they might be a good framework. 
                   3996: @c Things that I've tried to capture here are some things that came as a
                   3997: @c great revelation here when I first understood them. Also, I like the
                   3998: @c fact that a very simple code example shows up almost all of the issues
                   3999: @c that you need to understand to see how Forth works. That's unique and
                   4000: @c worthwhile to emphasise.
                   4001: 
1.83      anton    4002: @c anton: I think it's a good idea to present the details, especially those
                   4003: @c that you found to be a revelation, and probably the tutorial tries to be
                   4004: @c too superficial and does not get some of the things across that make
                   4005: @c Forth special.  I do believe that most of the time these things should
                   4006: @c be discussed at the end of a section or in separate sections instead of
                   4007: @c in the middle of a section (e.g., the stuff you added in "User-defined
                   4008: @c defining words" leads in a completely different direction from the rest
                   4009: @c of the section).
                   4010: 
1.29      crook    4011: Now we're going to take another look at the definition of @code{add-two}
                   4012: from the previous section. From our knowledge of the way that the text
                   4013: interpreter works, we would have expected this result when we tried to
                   4014: define @code{add-two}:
1.21      crook    4015: 
1.29      crook    4016: @example
1.44      crook    4017: @kbd{: add-two 2 + . ;@key{RET}}
1.134     anton    4018: *the terminal*:4: Undefined word
                   4019: : >>>add-two<<< 2 + . ;
1.29      crook    4020: @end example
1.28      crook    4021: 
1.29      crook    4022: The reason that this didn't happen is bound up in the way that @code{:}
                   4023: works. The word @code{:} does two special things. The first special
                   4024: thing that it does prevents the text interpreter from ever seeing the
                   4025: characters @code{add-two}. The text interpreter uses a variable called
                   4026: @cindex modifying >IN
1.44      crook    4027: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29      crook    4028: input line. When it encounters the word @code{:} it behaves in exactly
                   4029: the same way as it does for any other word; it looks it up in the name
                   4030: dictionary, finds its xt and executes it. When @code{:} executes, it
                   4031: looks at the input buffer, finds the word @code{add-two} and advances the
                   4032: value of @code{>IN} to point past it. It then does some other stuff
                   4033: associated with creating the new definition (including creating an entry
                   4034: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   4035: completes, control returns to the text interpreter, which is oblivious
                   4036: to the fact that it has been tricked into ignoring part of the input
                   4037: line.
1.21      crook    4038: 
1.29      crook    4039: @cindex parsing words
                   4040: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   4041: prevent the text interpreter from acting on the whole of the input line
                   4042: -- are called @dfn{parsing words}.
1.21      crook    4043: 
1.29      crook    4044: @cindex @code{state} - effect on the text interpreter
                   4045: @cindex text interpreter - effect of state
                   4046: The second special thing that @code{:} does is change the value of a
                   4047: variable called @code{state}, which affects the way that the text
                   4048: interpreter behaves. When Gforth starts up, @code{state} has the value
                   4049: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   4050: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44      crook    4051: the text interpreter is said to be @dfn{compiling}.
                   4052: 
                   4053: In this example, the text interpreter is compiling when it processes the
                   4054: string ``@code{2 + . ;}''. It still breaks the string down into
                   4055: character sequences in the same way. However, instead of pushing the
                   4056: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
                   4057: into the definition of @code{add-two} that will make the number @code{2} get
                   4058: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
                   4059: the behaviours of @code{+} and @code{.} are also compiled into the
                   4060: definition.
                   4061: 
                   4062: One category of words don't get compiled. These so-called @dfn{immediate
                   4063: words} get executed (performed @i{now}) regardless of whether the text
                   4064: interpreter is interpreting or compiling. The word @code{;} is an
                   4065: immediate word. Rather than being compiled into the definition, it
                   4066: executes. Its effect is to terminate the current definition, which
                   4067: includes changing the value of @code{state} back to 0.
                   4068: 
                   4069: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
                   4070: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
                   4071: definition.
1.28      crook    4072: 
1.30      anton    4073: In Forth, every word or number can be described in terms of two
1.29      crook    4074: properties:
1.28      crook    4075: 
                   4076: @itemize @bullet
                   4077: @item
1.29      crook    4078: @cindex interpretation semantics
1.44      crook    4079: Its @dfn{interpretation semantics} describe how it will behave when the
                   4080: text interpreter encounters it in @dfn{interpret} state. The
                   4081: interpretation semantics of a word are represented by an @dfn{execution
                   4082: token}.
1.28      crook    4083: @item
1.29      crook    4084: @cindex compilation semantics
1.44      crook    4085: Its @dfn{compilation semantics} describe how it will behave when the
                   4086: text interpreter encounters it in @dfn{compile} state. The compilation
                   4087: semantics of a word are represented in an implementation-dependent way;
                   4088: Gforth uses a @dfn{compilation token}.
1.29      crook    4089: @end itemize
                   4090: 
                   4091: @noindent
                   4092: Numbers are always treated in a fixed way:
                   4093: 
                   4094: @itemize @bullet
1.28      crook    4095: @item
1.44      crook    4096: When the number is @dfn{interpreted}, its behaviour is to push the
                   4097: number onto the stack.
1.28      crook    4098: @item
1.30      anton    4099: When the number is @dfn{compiled}, a piece of code is appended to the
                   4100: current definition that pushes the number when it runs. (In other words,
                   4101: the compilation semantics of a number are to postpone its interpretation
                   4102: semantics until the run-time of the definition that it is being compiled
                   4103: into.)
1.29      crook    4104: @end itemize
                   4105: 
1.44      crook    4106: Words don't behave in such a regular way, but most have @i{default
                   4107: semantics} which means that they behave like this:
1.29      crook    4108: 
                   4109: @itemize @bullet
1.28      crook    4110: @item
1.30      anton    4111: The @dfn{interpretation semantics} of the word are to do something useful.
                   4112: @item
1.29      crook    4113: The @dfn{compilation semantics} of the word are to append its
1.30      anton    4114: @dfn{interpretation semantics} to the current definition (so that its
                   4115: run-time behaviour is to do something useful).
1.28      crook    4116: @end itemize
                   4117: 
1.30      anton    4118: @cindex immediate words
1.44      crook    4119: The actual behaviour of any particular word can be controlled by using
                   4120: the words @code{immediate} and @code{compile-only} when the word is
                   4121: defined. These words set flags in the name dictionary entry of the most
                   4122: recently defined word, and these flags are retrieved by the text
                   4123: interpreter when it finds the word in the name dictionary.
                   4124: 
                   4125: A word that is marked as @dfn{immediate} has compilation semantics that
                   4126: are identical to its interpretation semantics. In other words, it
                   4127: behaves like this:
1.29      crook    4128: 
                   4129: @itemize @bullet
                   4130: @item
1.30      anton    4131: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    4132: @item
1.30      anton    4133: The @dfn{compilation semantics} of the word are to do something useful
                   4134: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    4135: @end itemize
1.28      crook    4136: 
1.44      crook    4137: Marking a word as @dfn{compile-only} prohibits the text interpreter from
                   4138: performing the interpretation semantics of the word directly; an attempt
                   4139: to do so will generate an error. It is never necessary to use
                   4140: @code{compile-only} (and it is not even part of ANS Forth, though it is
                   4141: provided by many implementations) but it is good etiquette to apply it
                   4142: to a word that will not behave correctly (and might have unexpected
                   4143: side-effects) in interpret state. For example, it is only legal to use
                   4144: the conditional word @code{IF} within a definition. If you forget this
                   4145: and try to use it elsewhere, the fact that (in Gforth) it is marked as
                   4146: @code{compile-only} allows the text interpreter to generate a helpful
                   4147: error message rather than subjecting you to the consequences of your
                   4148: folly.
                   4149: 
1.29      crook    4150: This example shows the difference between an immediate and a
                   4151: non-immediate word:
1.28      crook    4152: 
1.29      crook    4153: @example
                   4154: : show-state state @@ . ;
                   4155: : show-state-now show-state ; immediate
                   4156: : word1 show-state ;
                   4157: : word2 show-state-now ;
1.28      crook    4158: @end example
1.23      crook    4159: 
1.29      crook    4160: The word @code{immediate} after the definition of @code{show-state-now}
                   4161: makes that word an immediate word. These definitions introduce a new
                   4162: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   4163: variable, and leaves it on the stack. Therefore, the behaviour of
                   4164: @code{show-state} is to print a number that represents the current value
                   4165: of @code{state}.
1.28      crook    4166: 
1.29      crook    4167: When you execute @code{word1}, it prints the number 0, indicating that
                   4168: the system is interpreting. When the text interpreter compiled the
                   4169: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    4170: compilation semantics are to append its interpretation semantics to the
1.29      crook    4171: current definition. When you execute @code{word1}, it performs the
1.30      anton    4172: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    4173: (and therefore @code{show-state}) are executed, the system is
                   4174: interpreting.
1.28      crook    4175: 
1.30      anton    4176: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    4177: you should have seen the number -1 printed, followed by ``@code{
                   4178: ok}''. When the text interpreter compiled the definition of
                   4179: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    4180: whose compilation semantics are therefore to perform its interpretation
1.29      crook    4181: semantics. It is executed straight away (even before the text
                   4182: interpreter has moved on to process another group of characters; the
                   4183: @code{;} in this example). The effect of executing it are to display the
                   4184: value of @code{state} @i{at the time that the definition of}
                   4185: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   4186: system is compiling at this time. If you execute @code{word2} it does
                   4187: nothing at all.
1.28      crook    4188: 
1.29      crook    4189: @cindex @code{."}, how it works
                   4190: Before leaving the subject of immediate words, consider the behaviour of
                   4191: @code{."} in the definition of @code{greet}, in the previous
                   4192: section. This word is both a parsing word and an immediate word. Notice
                   4193: that there is a space between @code{."} and the start of the text
                   4194: @code{Hello and welcome}, but that there is no space between the last
                   4195: letter of @code{welcome} and the @code{"} character. The reason for this
                   4196: is that @code{."} is a Forth word; it must have a space after it so that
                   4197: the text interpreter can identify it. The @code{"} is not a Forth word;
                   4198: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   4199: is displayed, there is neither a space before the @code{H} nor after the
                   4200: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   4201: that @code{greet} is defined. When it executes, its behaviour is to
                   4202: search forward in the input line looking for the delimiter. When it
                   4203: finds the delimiter, it updates @code{>IN} to point past the
                   4204: delimiter. It also compiles some magic code into the definition of
                   4205: @code{greet}; the xt of a run-time routine that prints a text string. It
                   4206: compiles the string @code{Hello and welcome} into memory so that it is
                   4207: available to be printed later. When the text interpreter gains control,
                   4208: the next word it finds in the input stream is @code{;} and so it
                   4209: terminates the definition of @code{greet}.
1.28      crook    4210: 
                   4211: 
                   4212: @comment ----------------------------------------------
1.29      crook    4213: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   4214: @section Forth is written in Forth
                   4215: @cindex structure of Forth programs
                   4216: 
                   4217: When you start up a Forth compiler, a large number of definitions
                   4218: already exist. In Forth, you develop a new application using bottom-up
                   4219: programming techniques to create new definitions that are defined in
                   4220: terms of existing definitions. As you create each definition you can
                   4221: test and debug it interactively.
                   4222: 
                   4223: If you have tried out the examples in this section, you will probably
                   4224: have typed them in by hand; when you leave Gforth, your definitions will
                   4225: be lost. You can avoid this by using a text editor to enter Forth source
                   4226: code into a file, and then loading code from the file using
1.49      anton    4227: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29      crook    4228: processed by the text interpreter, just as though you had typed it in by
                   4229: hand@footnote{Actually, there are some subtle differences -- see
                   4230: @ref{The Text Interpreter}.}.
                   4231: 
                   4232: Gforth also supports the traditional Forth alternative to using text
1.49      anton    4233: files for program entry (@pxref{Blocks}).
1.28      crook    4234: 
1.29      crook    4235: In common with many, if not most, Forth compilers, most of Gforth is
                   4236: actually written in Forth. All of the @file{.fs} files in the
                   4237: installation directory@footnote{For example,
1.30      anton    4238: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    4239: study to see examples of Forth programming.
1.28      crook    4240: 
1.29      crook    4241: Gforth maintains a history file that records every line that you type to
                   4242: the text interpreter. This file is preserved between sessions, and is
                   4243: used to provide a command-line recall facility. If you enter long
                   4244: definitions by hand, you can use a text editor to paste them out of the
                   4245: history file into a Forth source file for reuse at a later time
1.49      anton    4246: (for more information @pxref{Command-line editing}).
1.28      crook    4247: 
                   4248: 
                   4249: @comment ----------------------------------------------
1.29      crook    4250: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   4251: @section Review - elements of a Forth system
                   4252: @cindex elements of a Forth system
1.28      crook    4253: 
1.29      crook    4254: To summarise this chapter:
1.28      crook    4255: 
                   4256: @itemize @bullet
                   4257: @item
1.29      crook    4258: Forth programs use @dfn{factoring} to break a problem down into small
                   4259: fragments called @dfn{words} or @dfn{definitions}.
                   4260: @item
                   4261: Forth program development is an interactive process.
                   4262: @item
                   4263: The main command loop that accepts input, and controls both
                   4264: interpretation and compilation, is called the @dfn{text interpreter}
                   4265: (also known as the @dfn{outer interpreter}).
                   4266: @item
                   4267: Forth has a very simple syntax, consisting of words and numbers
                   4268: separated by spaces or carriage-return characters. Any additional syntax
                   4269: is imposed by @dfn{parsing words}.
                   4270: @item
                   4271: Forth uses a stack to pass parameters between words. As a result, it
                   4272: uses postfix notation.
                   4273: @item
                   4274: To use a word that has previously been defined, the text interpreter
                   4275: searches for the word in the @dfn{name dictionary}.
                   4276: @item
1.30      anton    4277: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    4278: @item
1.29      crook    4279: The text interpreter uses the value of @code{state} to select between
                   4280: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   4281: semantics} of a word that it encounters.
1.28      crook    4282: @item
1.30      anton    4283: The relationship between the @dfn{interpretation semantics} and
                   4284: @dfn{compilation semantics} for a word
1.29      crook    4285: depend upon the way in which the word was defined (for example, whether
                   4286: it is an @dfn{immediate} word).
1.28      crook    4287: @item
1.29      crook    4288: Forth definitions can be implemented in Forth (called @dfn{high-level
                   4289: definitions}) or in some other way (usually a lower-level language and
                   4290: as a result often called @dfn{low-level definitions}, @dfn{code
                   4291: definitions} or @dfn{primitives}).
1.28      crook    4292: @item
1.29      crook    4293: Many Forth systems are implemented mainly in Forth.
1.28      crook    4294: @end itemize
                   4295: 
                   4296: 
1.29      crook    4297: @comment ----------------------------------------------
1.48      anton    4298: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29      crook    4299: @section Where To Go Next
                   4300: @cindex where to go next
1.28      crook    4301: 
1.29      crook    4302: Amazing as it may seem, if you have read (and understood) this far, you
                   4303: know almost all the fundamentals about the inner workings of a Forth
                   4304: system. You certainly know enough to be able to read and understand the
                   4305: rest of this manual and the ANS Forth document, to learn more about the
                   4306: facilities that Forth in general and Gforth in particular provide. Even
                   4307: scarier, you know almost enough to implement your own Forth system.
1.30      anton    4308: However, that's not a good idea just yet... better to try writing some
1.29      crook    4309: programs in Gforth.
1.28      crook    4310: 
1.29      crook    4311: Forth has such a rich vocabulary that it can be hard to know where to
                   4312: start in learning it. This section suggests a few sets of words that are
                   4313: enough to write small but useful programs. Use the word index in this
                   4314: document to learn more about each word, then try it out and try to write
                   4315: small definitions using it. Start by experimenting with these words:
1.28      crook    4316: 
                   4317: @itemize @bullet
                   4318: @item
1.29      crook    4319: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   4320: @item
                   4321: Comparison: @code{MIN MAX =}
                   4322: @item
                   4323: Logic: @code{AND OR XOR NOT}
                   4324: @item
                   4325: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    4326: @item
1.29      crook    4327: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    4328: @item
1.29      crook    4329: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    4330: @item
1.29      crook    4331: Defining words: @code{: ; CREATE}
1.28      crook    4332: @item
1.29      crook    4333: Memory allocation words: @code{ALLOT ,}
1.28      crook    4334: @item
1.29      crook    4335: Tools: @code{SEE WORDS .S MARKER}
                   4336: @end itemize
                   4337: 
                   4338: When you have mastered those, go on to:
                   4339: 
                   4340: @itemize @bullet
1.28      crook    4341: @item
1.29      crook    4342: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    4343: @item
1.29      crook    4344: Memory access: @code{@@ !}
1.28      crook    4345: @end itemize
1.23      crook    4346: 
1.29      crook    4347: When you have mastered these, there's nothing for it but to read through
                   4348: the whole of this manual and find out what you've missed.
                   4349: 
                   4350: @comment ----------------------------------------------
1.48      anton    4351: @node Exercises,  , Where to go next, Introduction
1.29      crook    4352: @section Exercises
                   4353: @cindex exercises
                   4354: 
                   4355: TODO: provide a set of programming excercises linked into the stuff done
                   4356: already and into other sections of the manual. Provide solutions to all
                   4357: the exercises in a .fs file in the distribution.
                   4358: 
                   4359: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   4360: 
                   4361: @c excercises:
                   4362: @c 1. take inches and convert to feet and inches.
                   4363: @c 2. take temperature and convert from fahrenheight to celcius;
                   4364: @c    may need to care about symmetric vs floored??
                   4365: @c 3. take input line and do character substitution
                   4366: @c    to encipher or decipher
                   4367: @c 4. as above but work on a file for in and out
                   4368: @c 5. take input line and convert to pig-latin 
                   4369: @c
                   4370: @c thing of sets of things to exercise then come up with
                   4371: @c problems that need those things.
                   4372: 
                   4373: 
1.26      crook    4374: @c ******************************************************************
1.29      crook    4375: @node Words, Error messages, Introduction, Top
1.1       anton    4376: @chapter Forth Words
1.26      crook    4377: @cindex words
1.1       anton    4378: 
                   4379: @menu
                   4380: * Notation::                    
1.65      anton    4381: * Case insensitivity::          
                   4382: * Comments::                    
                   4383: * Boolean Flags::               
1.1       anton    4384: * Arithmetic::                  
                   4385: * Stack Manipulation::          
1.5       anton    4386: * Memory::                      
1.1       anton    4387: * Control Structures::          
                   4388: * Defining Words::              
1.65      anton    4389: * Interpretation and Compilation Semantics::  
1.47      crook    4390: * Tokens for Words::            
1.81      anton    4391: * Compiling words::             
1.65      anton    4392: * The Text Interpreter::        
1.111     anton    4393: * The Input Stream::            
1.65      anton    4394: * Word Lists::                  
                   4395: * Environmental Queries::       
1.12      anton    4396: * Files::                       
                   4397: * Blocks::                      
                   4398: * Other I/O::                   
1.121     anton    4399: * OS command line arguments::   
1.78      anton    4400: * Locals::                      
                   4401: * Structures::                  
                   4402: * Object-oriented Forth::       
1.12      anton    4403: * Programming Tools::           
1.150     anton    4404: * C Interface::                 
1.12      anton    4405: * Assembler and Code Words::    
                   4406: * Threading Words::             
1.65      anton    4407: * Passing Commands to the OS::  
                   4408: * Keeping track of Time::       
                   4409: * Miscellaneous Words::         
1.1       anton    4410: @end menu
                   4411: 
1.65      anton    4412: @node Notation, Case insensitivity, Words, Words
1.1       anton    4413: @section Notation
                   4414: @cindex notation of glossary entries
                   4415: @cindex format of glossary entries
                   4416: @cindex glossary notation format
                   4417: @cindex word glossary entry format
                   4418: 
                   4419: The Forth words are described in this section in the glossary notation
1.67      anton    4420: that has become a de-facto standard for Forth texts:
1.1       anton    4421: 
                   4422: @format
1.29      crook    4423: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    4424: @end format
1.29      crook    4425: @i{Description}
1.1       anton    4426: 
                   4427: @table @var
                   4428: @item word
1.28      crook    4429: The name of the word.
1.1       anton    4430: 
                   4431: @item Stack effect
                   4432: @cindex stack effect
1.29      crook    4433: The stack effect is written in the notation @code{@i{before} --
                   4434: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    4435: stack entries before and after the execution of the word. The rest of
                   4436: the stack is not touched by the word. The top of stack is rightmost,
                   4437: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   4438: uses a separate floating point stack, but a unified stack
1.29      crook    4439: notation. Also, return stack effects are not shown in @i{stack
                   4440: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    4441: the type and/or the function of the item. See below for a discussion of
                   4442: the types.
                   4443: 
                   4444: All words have two stack effects: A compile-time stack effect and a
                   4445: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    4446: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    4447: this standard behaviour, or the word does other unusual things at
                   4448: compile time, both stack effects are shown; otherwise only the run-time
                   4449: stack effect is shown.
                   4450: 
1.211     anton    4451: Also note that in code templates or examples there can be comments in
                   4452: parentheses that display the stack picture at this point; there is no
                   4453: @code{--} in these places, because there is no before-after situation.
                   4454: 
1.1       anton    4455: @cindex pronounciation of words
                   4456: @item pronunciation
                   4457: How the word is pronounced.
                   4458: 
                   4459: @cindex wordset
1.67      anton    4460: @cindex environment wordset
1.1       anton    4461: @item wordset
1.21      crook    4462: The ANS Forth standard is divided into several word sets. A standard
                   4463: system need not support all of them. Therefore, in theory, the fewer
                   4464: word sets your program uses the more portable it will be. However, we
                   4465: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    4466: all word sets. Words that are not defined in ANS Forth have
1.21      crook    4467: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    4468: describes words that will work in future releases of Gforth;
                   4469: @code{gforth-internal} words are more volatile. Environmental query
                   4470: strings are also displayed like words; you can recognize them by the
1.21      crook    4471: @code{environment} in the word set field.
1.1       anton    4472: 
                   4473: @item Description
                   4474: A description of the behaviour of the word.
                   4475: @end table
                   4476: 
                   4477: @cindex types of stack items
                   4478: @cindex stack item types
                   4479: The type of a stack item is specified by the character(s) the name
                   4480: starts with:
                   4481: 
                   4482: @table @code
                   4483: @item f
                   4484: @cindex @code{f}, stack item type
                   4485: Boolean flags, i.e. @code{false} or @code{true}.
                   4486: @item c
                   4487: @cindex @code{c}, stack item type
                   4488: Char
                   4489: @item w
                   4490: @cindex @code{w}, stack item type
                   4491: Cell, can contain an integer or an address
                   4492: @item n
                   4493: @cindex @code{n}, stack item type
                   4494: signed integer
                   4495: @item u
                   4496: @cindex @code{u}, stack item type
                   4497: unsigned integer
                   4498: @item d
                   4499: @cindex @code{d}, stack item type
                   4500: double sized signed integer
                   4501: @item ud
                   4502: @cindex @code{ud}, stack item type
                   4503: double sized unsigned integer
                   4504: @item r
                   4505: @cindex @code{r}, stack item type
                   4506: Float (on the FP stack)
1.21      crook    4507: @item a-
1.1       anton    4508: @cindex @code{a_}, stack item type
                   4509: Cell-aligned address
1.21      crook    4510: @item c-
1.1       anton    4511: @cindex @code{c_}, stack item type
                   4512: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    4513: @item f-
1.1       anton    4514: @cindex @code{f_}, stack item type
                   4515: Float-aligned address
1.21      crook    4516: @item df-
1.1       anton    4517: @cindex @code{df_}, stack item type
                   4518: Address aligned for IEEE double precision float
1.21      crook    4519: @item sf-
1.1       anton    4520: @cindex @code{sf_}, stack item type
                   4521: Address aligned for IEEE single precision float
                   4522: @item xt
                   4523: @cindex @code{xt}, stack item type
                   4524: Execution token, same size as Cell
                   4525: @item wid
                   4526: @cindex @code{wid}, stack item type
1.21      crook    4527: Word list ID, same size as Cell
1.68      anton    4528: @item ior, wior
                   4529: @cindex ior type description
                   4530: @cindex wior type description
                   4531: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
1.1       anton    4532: @item f83name
                   4533: @cindex @code{f83name}, stack item type
                   4534: Pointer to a name structure
                   4535: @item "
                   4536: @cindex @code{"}, stack item type
1.12      anton    4537: string in the input stream (not on the stack). The terminating character
                   4538: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    4539: quotes.
                   4540: @end table
                   4541: 
1.65      anton    4542: @comment ----------------------------------------------
                   4543: @node Case insensitivity, Comments, Notation, Words
                   4544: @section Case insensitivity
                   4545: @cindex case sensitivity
                   4546: @cindex upper and lower case
                   4547: 
                   4548: Gforth is case-insensitive; you can enter definitions and invoke
                   4549: Standard words using upper, lower or mixed case (however,
                   4550: @pxref{core-idef, Implementation-defined options, Implementation-defined
                   4551: options}).
                   4552: 
                   4553: ANS Forth only @i{requires} implementations to recognise Standard words
                   4554: when they are typed entirely in upper case. Therefore, a Standard
                   4555: program must use upper case for all Standard words. You can use whatever
                   4556: case you like for words that you define, but in a Standard program you
                   4557: have to use the words in the same case that you defined them.
                   4558: 
                   4559: Gforth supports case sensitivity through @code{table}s (case-sensitive
                   4560: wordlists, @pxref{Word Lists}).
                   4561: 
                   4562: Two people have asked how to convert Gforth to be case-sensitive; while
                   4563: we think this is a bad idea, you can change all wordlists into tables
                   4564: like this:
                   4565: 
                   4566: @example
                   4567: ' table-find forth-wordlist wordlist-map @ !
                   4568: @end example
                   4569: 
                   4570: Note that you now have to type the predefined words in the same case
                   4571: that we defined them, which are varying.  You may want to convert them
                   4572: to your favourite case before doing this operation (I won't explain how,
                   4573: because if you are even contemplating doing this, you'd better have
                   4574: enough knowledge of Forth systems to know this already).
                   4575: 
                   4576: @node Comments, Boolean Flags, Case insensitivity, Words
1.21      crook    4577: @section Comments
1.26      crook    4578: @cindex comments
1.21      crook    4579: 
1.29      crook    4580: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   4581: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    4582: 
1.44      crook    4583: 
1.23      crook    4584: doc-(
1.21      crook    4585: doc-\
1.23      crook    4586: doc-\G
1.21      crook    4587: 
1.44      crook    4588: 
1.21      crook    4589: @node Boolean Flags, Arithmetic, Comments, Words
                   4590: @section Boolean Flags
1.26      crook    4591: @cindex Boolean flags
1.21      crook    4592: 
                   4593: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   4594: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    4595: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    4596: a cell that has @i{any} bit set as @code{true}.
1.67      anton    4597: @c on and off to Memory? 
                   4598: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44      crook    4599: 
1.21      crook    4600: doc-true
                   4601: doc-false
1.29      crook    4602: doc-on
                   4603: doc-off
1.21      crook    4604: 
1.44      crook    4605: 
1.21      crook    4606: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    4607: @section Arithmetic
                   4608: @cindex arithmetic words
                   4609: 
                   4610: @cindex division with potentially negative operands
                   4611: Forth arithmetic is not checked, i.e., you will not hear about integer
                   4612: overflow on addition or multiplication, you may hear about division by
                   4613: zero if you are lucky. The operator is written after the operands, but
                   4614: the operands are still in the original order. I.e., the infix @code{2-1}
                   4615: corresponds to @code{2 1 -}. Forth offers a variety of division
                   4616: operators. If you perform division with potentially negative operands,
                   4617: you do not want to use @code{/} or @code{/mod} with its undefined
                   4618: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   4619: former, @pxref{Mixed precision}).
1.26      crook    4620: @comment TODO discuss the different division forms and the std approach
1.1       anton    4621: 
                   4622: @menu
                   4623: * Single precision::            
1.67      anton    4624: * Double precision::            Double-cell integer arithmetic
1.1       anton    4625: * Bitwise operations::          
1.67      anton    4626: * Numeric comparison::          
1.29      crook    4627: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    4628: * Floating Point::              
                   4629: @end menu
                   4630: 
1.67      anton    4631: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1       anton    4632: @subsection Single precision
                   4633: @cindex single precision arithmetic words
                   4634: 
1.67      anton    4635: @c !! cell undefined
                   4636: 
                   4637: By default, numbers in Forth are single-precision integers that are one
1.26      crook    4638: cell in size. They can be signed or unsigned, depending upon how you
1.49      anton    4639: treat them. For the rules used by the text interpreter for recognising
                   4640: single-precision integers see @ref{Number Conversion}.
1.21      crook    4641: 
1.67      anton    4642: These words are all defined for signed operands, but some of them also
                   4643: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
                   4644: @code{*}.
1.44      crook    4645: 
1.1       anton    4646: doc-+
1.21      crook    4647: doc-1+
1.128     anton    4648: doc-under+
1.1       anton    4649: doc--
1.21      crook    4650: doc-1-
1.1       anton    4651: doc-*
                   4652: doc-/
                   4653: doc-mod
                   4654: doc-/mod
                   4655: doc-negate
                   4656: doc-abs
                   4657: doc-min
                   4658: doc-max
1.27      crook    4659: doc-floored
1.1       anton    4660: 
1.44      crook    4661: 
1.67      anton    4662: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21      crook    4663: @subsection Double precision
                   4664: @cindex double precision arithmetic words
                   4665: 
1.49      anton    4666: For the rules used by the text interpreter for
                   4667: recognising double-precision integers, see @ref{Number Conversion}.
1.21      crook    4668: 
                   4669: A double precision number is represented by a cell pair, with the most
1.67      anton    4670: significant cell at the TOS. It is trivial to convert an unsigned single
                   4671: to a double: simply push a @code{0} onto the TOS. Since numbers are
                   4672: represented by Gforth using 2's complement arithmetic, converting a
                   4673: signed single to a (signed) double requires sign-extension across the
                   4674: most significant cell. This can be achieved using @code{s>d}. The moral
                   4675: of the story is that you cannot convert a number without knowing whether
                   4676: it represents an unsigned or a signed number.
1.21      crook    4677: 
1.67      anton    4678: These words are all defined for signed operands, but some of them also
                   4679: work for unsigned numbers: @code{d+}, @code{d-}.
1.44      crook    4680: 
1.21      crook    4681: doc-s>d
1.67      anton    4682: doc-d>s
1.21      crook    4683: doc-d+
                   4684: doc-d-
                   4685: doc-dnegate
                   4686: doc-dabs
                   4687: doc-dmin
                   4688: doc-dmax
                   4689: 
1.44      crook    4690: 
1.67      anton    4691: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
                   4692: @subsection Bitwise operations
                   4693: @cindex bitwise operation words
                   4694: 
                   4695: 
                   4696: doc-and
                   4697: doc-or
                   4698: doc-xor
                   4699: doc-invert
                   4700: doc-lshift
                   4701: doc-rshift
                   4702: doc-2*
                   4703: doc-d2*
                   4704: doc-2/
                   4705: doc-d2/
                   4706: 
                   4707: 
                   4708: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21      crook    4709: @subsection Numeric comparison
                   4710: @cindex numeric comparison words
                   4711: 
1.67      anton    4712: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
                   4713: d0= d0<>}) work for for both signed and unsigned numbers.
1.44      crook    4714: 
1.28      crook    4715: doc-<
                   4716: doc-<=
                   4717: doc-<>
                   4718: doc-=
                   4719: doc->
                   4720: doc->=
                   4721: 
1.21      crook    4722: doc-0<
1.23      crook    4723: doc-0<=
1.21      crook    4724: doc-0<>
                   4725: doc-0=
1.23      crook    4726: doc-0>
                   4727: doc-0>=
1.28      crook    4728: 
                   4729: doc-u<
                   4730: doc-u<=
1.44      crook    4731: @c u<> and u= exist but are the same as <> and =
1.31      anton    4732: @c doc-u<>
                   4733: @c doc-u=
1.28      crook    4734: doc-u>
                   4735: doc-u>=
                   4736: 
                   4737: doc-within
                   4738: 
                   4739: doc-d<
                   4740: doc-d<=
                   4741: doc-d<>
                   4742: doc-d=
                   4743: doc-d>
                   4744: doc-d>=
1.23      crook    4745: 
1.21      crook    4746: doc-d0<
1.23      crook    4747: doc-d0<=
                   4748: doc-d0<>
1.21      crook    4749: doc-d0=
1.23      crook    4750: doc-d0>
                   4751: doc-d0>=
                   4752: 
1.21      crook    4753: doc-du<
1.28      crook    4754: doc-du<=
1.44      crook    4755: @c du<> and du= exist but are the same as d<> and d=
1.31      anton    4756: @c doc-du<>
                   4757: @c doc-du=
1.28      crook    4758: doc-du>
                   4759: doc-du>=
1.1       anton    4760: 
1.44      crook    4761: 
1.21      crook    4762: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    4763: @subsection Mixed precision
                   4764: @cindex mixed precision arithmetic words
                   4765: 
1.44      crook    4766: 
1.1       anton    4767: doc-m+
                   4768: doc-*/
                   4769: doc-*/mod
                   4770: doc-m*
                   4771: doc-um*
                   4772: doc-m*/
                   4773: doc-um/mod
                   4774: doc-fm/mod
                   4775: doc-sm/rem
                   4776: 
1.44      crook    4777: 
1.21      crook    4778: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    4779: @subsection Floating Point
                   4780: @cindex floating point arithmetic words
                   4781: 
1.49      anton    4782: For the rules used by the text interpreter for
                   4783: recognising floating-point numbers see @ref{Number Conversion}.
1.1       anton    4784: 
1.67      anton    4785: Gforth has a separate floating point stack, but the documentation uses
                   4786: the unified notation.@footnote{It's easy to generate the separate
                   4787: notation from that by just separating the floating-point numbers out:
                   4788: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
                   4789: r3 )}.}
1.1       anton    4790: 
                   4791: @cindex floating-point arithmetic, pitfalls
                   4792: Floating point numbers have a number of unpleasant surprises for the
1.190     anton    4793: unwary (e.g., floating point addition is not associative) and even a
                   4794: few for the wary. You should not use them unless you know what you are
                   4795: doing or you don't care that the results you get are totally bogus. If
                   4796: you want to learn about the problems of floating point numbers (and
                   4797: how to avoid them), you might start with @cite{David Goldberg,
                   4798: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
                   4799: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
                   4800: Computing Surveys 23(1):5@minus{}48, March 1991}.
1.1       anton    4801: 
1.44      crook    4802: 
1.21      crook    4803: doc-d>f
                   4804: doc-f>d
1.1       anton    4805: doc-f+
                   4806: doc-f-
                   4807: doc-f*
                   4808: doc-f/
                   4809: doc-fnegate
                   4810: doc-fabs
                   4811: doc-fmax
                   4812: doc-fmin
                   4813: doc-floor
                   4814: doc-fround
                   4815: doc-f**
                   4816: doc-fsqrt
                   4817: doc-fexp
                   4818: doc-fexpm1
                   4819: doc-fln
                   4820: doc-flnp1
                   4821: doc-flog
                   4822: doc-falog
1.32      anton    4823: doc-f2*
                   4824: doc-f2/
                   4825: doc-1/f
                   4826: doc-precision
                   4827: doc-set-precision
                   4828: 
                   4829: @cindex angles in trigonometric operations
                   4830: @cindex trigonometric operations
                   4831: Angles in floating point operations are given in radians (a full circle
                   4832: has 2 pi radians).
                   4833: 
1.1       anton    4834: doc-fsin
                   4835: doc-fcos
                   4836: doc-fsincos
                   4837: doc-ftan
                   4838: doc-fasin
                   4839: doc-facos
                   4840: doc-fatan
                   4841: doc-fatan2
                   4842: doc-fsinh
                   4843: doc-fcosh
                   4844: doc-ftanh
                   4845: doc-fasinh
                   4846: doc-facosh
                   4847: doc-fatanh
1.21      crook    4848: doc-pi
1.28      crook    4849: 
1.32      anton    4850: @cindex equality of floats
                   4851: @cindex floating-point comparisons
1.31      anton    4852: One particular problem with floating-point arithmetic is that comparison
                   4853: for equality often fails when you would expect it to succeed.  For this
                   4854: reason approximate equality is often preferred (but you still have to
1.67      anton    4855: know what you are doing).  Also note that IEEE NaNs may compare
1.68      anton    4856: differently from what you might expect.  The comparison words are:
1.31      anton    4857: 
                   4858: doc-f~rel
                   4859: doc-f~abs
1.68      anton    4860: doc-f~
1.31      anton    4861: doc-f=
                   4862: doc-f<>
                   4863: 
                   4864: doc-f<
                   4865: doc-f<=
                   4866: doc-f>
                   4867: doc-f>=
                   4868: 
1.21      crook    4869: doc-f0<
1.28      crook    4870: doc-f0<=
                   4871: doc-f0<>
1.21      crook    4872: doc-f0=
1.28      crook    4873: doc-f0>
                   4874: doc-f0>=
                   4875: 
1.1       anton    4876: 
                   4877: @node Stack Manipulation, Memory, Arithmetic, Words
                   4878: @section Stack Manipulation
                   4879: @cindex stack manipulation words
                   4880: 
                   4881: @cindex floating-point stack in the standard
1.21      crook    4882: Gforth maintains a number of separate stacks:
                   4883: 
1.29      crook    4884: @cindex data stack
                   4885: @cindex parameter stack
1.21      crook    4886: @itemize @bullet
                   4887: @item
1.29      crook    4888: A data stack (also known as the @dfn{parameter stack}) -- for
                   4889: characters, cells, addresses, and double cells.
1.21      crook    4890: 
1.29      crook    4891: @cindex floating-point stack
1.21      crook    4892: @item
1.44      crook    4893: A floating point stack -- for holding floating point (FP) numbers.
1.21      crook    4894: 
1.29      crook    4895: @cindex return stack
1.21      crook    4896: @item
1.44      crook    4897: A return stack -- for holding the return addresses of colon
1.32      anton    4898: definitions and other (non-FP) data.
1.21      crook    4899: 
1.29      crook    4900: @cindex locals stack
1.21      crook    4901: @item
1.44      crook    4902: A locals stack -- for holding local variables.
1.21      crook    4903: @end itemize
                   4904: 
1.1       anton    4905: @menu
                   4906: * Data stack::                  
                   4907: * Floating point stack::        
                   4908: * Return stack::                
                   4909: * Locals stack::                
                   4910: * Stack pointer manipulation::  
                   4911: @end menu
                   4912: 
                   4913: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   4914: @subsection Data stack
                   4915: @cindex data stack manipulation words
                   4916: @cindex stack manipulations words, data stack
                   4917: 
1.44      crook    4918: 
1.1       anton    4919: doc-drop
                   4920: doc-nip
                   4921: doc-dup
                   4922: doc-over
                   4923: doc-tuck
                   4924: doc-swap
1.21      crook    4925: doc-pick
1.1       anton    4926: doc-rot
                   4927: doc--rot
                   4928: doc-?dup
                   4929: doc-roll
                   4930: doc-2drop
                   4931: doc-2nip
                   4932: doc-2dup
                   4933: doc-2over
                   4934: doc-2tuck
                   4935: doc-2swap
                   4936: doc-2rot
                   4937: 
1.44      crook    4938: 
1.1       anton    4939: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   4940: @subsection Floating point stack
                   4941: @cindex floating-point stack manipulation words
                   4942: @cindex stack manipulation words, floating-point stack
                   4943: 
1.32      anton    4944: Whilst every sane Forth has a separate floating-point stack, it is not
                   4945: strictly required; an ANS Forth system could theoretically keep
                   4946: floating-point numbers on the data stack. As an additional difficulty,
                   4947: you don't know how many cells a floating-point number takes. It is
                   4948: reportedly possible to write words in a way that they work also for a
                   4949: unified stack model, but we do not recommend trying it. Instead, just
                   4950: say that your program has an environmental dependency on a separate
                   4951: floating-point stack.
                   4952: 
                   4953: doc-floating-stack
                   4954: 
1.1       anton    4955: doc-fdrop
                   4956: doc-fnip
                   4957: doc-fdup
                   4958: doc-fover
                   4959: doc-ftuck
                   4960: doc-fswap
1.21      crook    4961: doc-fpick
1.1       anton    4962: doc-frot
                   4963: 
1.44      crook    4964: 
1.1       anton    4965: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   4966: @subsection Return stack
                   4967: @cindex return stack manipulation words
                   4968: @cindex stack manipulation words, return stack
                   4969: 
1.32      anton    4970: @cindex return stack and locals
                   4971: @cindex locals and return stack
                   4972: A Forth system is allowed to keep local variables on the
                   4973: return stack. This is reasonable, as local variables usually eliminate
                   4974: the need to use the return stack explicitly. So, if you want to produce
                   4975: a standard compliant program and you are using local variables in a
                   4976: word, forget about return stack manipulations in that word (refer to the
                   4977: standard document for the exact rules).
                   4978: 
1.1       anton    4979: doc->r
                   4980: doc-r>
                   4981: doc-r@
                   4982: doc-rdrop
                   4983: doc-2>r
                   4984: doc-2r>
                   4985: doc-2r@
                   4986: doc-2rdrop
                   4987: 
1.44      crook    4988: 
1.1       anton    4989: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   4990: @subsection Locals stack
                   4991: 
1.78      anton    4992: Gforth uses an extra locals stack.  It is described, along with the
                   4993: reasons for its existence, in @ref{Locals implementation}.
1.21      crook    4994: 
1.1       anton    4995: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   4996: @subsection Stack pointer manipulation
                   4997: @cindex stack pointer manipulation words
                   4998: 
1.44      crook    4999: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21      crook    5000: doc-sp0
1.1       anton    5001: doc-sp@
                   5002: doc-sp!
1.21      crook    5003: doc-fp0
1.1       anton    5004: doc-fp@
                   5005: doc-fp!
1.21      crook    5006: doc-rp0
1.1       anton    5007: doc-rp@
                   5008: doc-rp!
1.21      crook    5009: doc-lp0
1.1       anton    5010: doc-lp@
                   5011: doc-lp!
                   5012: 
1.44      crook    5013: 
1.1       anton    5014: @node Memory, Control Structures, Stack Manipulation, Words
                   5015: @section Memory
1.26      crook    5016: @cindex memory words
1.1       anton    5017: 
1.32      anton    5018: @menu
                   5019: * Memory model::                
                   5020: * Dictionary allocation::       
                   5021: * Heap Allocation::             
                   5022: * Memory Access::               
                   5023: * Address arithmetic::          
                   5024: * Memory Blocks::               
                   5025: @end menu
                   5026: 
1.67      anton    5027: In addition to the standard Forth memory allocation words, there is also
                   5028: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   5029: garbage collector}.
                   5030: 
1.32      anton    5031: @node Memory model, Dictionary allocation, Memory, Memory
                   5032: @subsection ANS Forth and Gforth memory models
                   5033: 
                   5034: @c The ANS Forth description is a mess (e.g., is the heap part of
                   5035: @c the dictionary?), so let's not stick to closely with it.
                   5036: 
1.67      anton    5037: ANS Forth considers a Forth system as consisting of several address
                   5038: spaces, of which only @dfn{data space} is managed and accessible with
                   5039: the memory words.  Memory not necessarily in data space includes the
                   5040: stacks, the code (called code space) and the headers (called name
                   5041: space). In Gforth everything is in data space, but the code for the
                   5042: primitives is usually read-only.
1.32      anton    5043: 
                   5044: Data space is divided into a number of areas: The (data space portion of
                   5045: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
                   5046: refer to the search data structure embodied in word lists and headers,
                   5047: because it is used for looking up names, just as you would in a
                   5048: conventional dictionary.}, the heap, and a number of system-allocated
                   5049: buffers.
                   5050: 
1.68      anton    5051: @cindex address arithmetic restrictions, ANS vs. Gforth
                   5052: @cindex contiguous regions, ANS vs. Gforth
1.32      anton    5053: In ANS Forth data space is also divided into contiguous regions.  You
                   5054: can only use address arithmetic within a contiguous region, not between
                   5055: them.  Usually each allocation gives you one contiguous region, but the
1.33      anton    5056: dictionary allocation words have additional rules (@pxref{Dictionary
1.32      anton    5057: allocation}).
                   5058: 
                   5059: Gforth provides one big address space, and address arithmetic can be
                   5060: performed between any addresses. However, in the dictionary headers or
                   5061: code are interleaved with data, so almost the only contiguous data space
                   5062: regions there are those described by ANS Forth as contiguous; but you
                   5063: can be sure that the dictionary is allocated towards increasing
                   5064: addresses even between contiguous regions.  The memory order of
                   5065: allocations in the heap is platform-dependent (and possibly different
                   5066: from one run to the next).
                   5067: 
1.27      crook    5068: 
1.32      anton    5069: @node Dictionary allocation, Heap Allocation, Memory model, Memory
                   5070: @subsection Dictionary allocation
1.27      crook    5071: @cindex reserving data space
                   5072: @cindex data space - reserving some
                   5073: 
1.32      anton    5074: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
                   5075: you want to deallocate X, you also deallocate everything
                   5076: allocated after X.
                   5077: 
1.68      anton    5078: @cindex contiguous regions in dictionary allocation
1.32      anton    5079: The allocations using the words below are contiguous and grow the region
                   5080: towards increasing addresses.  Other words that allocate dictionary
                   5081: memory of any kind (i.e., defining words including @code{:noname}) end
                   5082: the contiguous region and start a new one.
                   5083: 
                   5084: In ANS Forth only @code{create}d words are guaranteed to produce an
                   5085: address that is the start of the following contiguous region.  In
                   5086: particular, the cell allocated by @code{variable} is not guaranteed to
                   5087: be contiguous with following @code{allot}ed memory.
                   5088: 
                   5089: You can deallocate memory by using @code{allot} with a negative argument
                   5090: (with some restrictions, see @code{allot}). For larger deallocations use
                   5091: @code{marker}.
1.27      crook    5092: 
1.29      crook    5093: 
1.27      crook    5094: doc-here
                   5095: doc-unused
                   5096: doc-allot
                   5097: doc-c,
1.29      crook    5098: doc-f,
1.27      crook    5099: doc-,
                   5100: doc-2,
                   5101: 
1.32      anton    5102: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
                   5103: course you should allocate memory in an aligned way, too. I.e., before
                   5104: allocating allocating a cell, @code{here} must be cell-aligned, etc.
                   5105: The words below align @code{here} if it is not already.  Basically it is
                   5106: only already aligned for a type, if the last allocation was a multiple
                   5107: of the size of this type and if @code{here} was aligned for this type
                   5108: before.
                   5109: 
                   5110: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
                   5111: ANS Forth (@code{maxalign}ed in Gforth).
                   5112: 
                   5113: doc-align
                   5114: doc-falign
                   5115: doc-sfalign
                   5116: doc-dfalign
                   5117: doc-maxalign
                   5118: doc-cfalign
                   5119: 
                   5120: 
                   5121: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
                   5122: @subsection Heap allocation
                   5123: @cindex heap allocation
                   5124: @cindex dynamic allocation of memory
                   5125: @cindex memory-allocation word set
                   5126: 
1.68      anton    5127: @cindex contiguous regions and heap allocation
1.32      anton    5128: Heap allocation supports deallocation of allocated memory in any
                   5129: order. Dictionary allocation is not affected by it (i.e., it does not
                   5130: end a contiguous region). In Gforth, these words are implemented using
                   5131: the standard C library calls malloc(), free() and resize().
                   5132: 
1.68      anton    5133: The memory region produced by one invocation of @code{allocate} or
                   5134: @code{resize} is internally contiguous.  There is no contiguity between
                   5135: such a region and any other region (including others allocated from the
                   5136: heap).
                   5137: 
1.32      anton    5138: doc-allocate
                   5139: doc-free
                   5140: doc-resize
                   5141: 
1.27      crook    5142: 
1.32      anton    5143: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1       anton    5144: @subsection Memory Access
                   5145: @cindex memory access words
                   5146: 
                   5147: doc-@
                   5148: doc-!
                   5149: doc-+!
                   5150: doc-c@
                   5151: doc-c!
                   5152: doc-2@
                   5153: doc-2!
                   5154: doc-f@
                   5155: doc-f!
                   5156: doc-sf@
                   5157: doc-sf!
                   5158: doc-df@
                   5159: doc-df!
1.144     anton    5160: doc-sw@
                   5161: doc-uw@
                   5162: doc-w!
                   5163: doc-sl@
                   5164: doc-ul@
                   5165: doc-l!
1.68      anton    5166: 
1.32      anton    5167: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   5168: @subsection Address arithmetic
1.1       anton    5169: @cindex address arithmetic words
                   5170: 
1.67      anton    5171: Address arithmetic is the foundation on which you can build data
                   5172: structures like arrays, records (@pxref{Structures}) and objects
                   5173: (@pxref{Object-oriented Forth}).
1.32      anton    5174: 
1.68      anton    5175: @cindex address unit
                   5176: @cindex au (address unit)
1.1       anton    5177: ANS Forth does not specify the sizes of the data types. Instead, it
                   5178: offers a number of words for computing sizes and doing address
1.29      crook    5179: arithmetic. Address arithmetic is performed in terms of address units
                   5180: (aus); on most systems the address unit is one byte. Note that a
                   5181: character may have more than one au, so @code{chars} is no noop (on
1.68      anton    5182: platforms where it is a noop, it compiles to nothing).
1.1       anton    5183: 
1.67      anton    5184: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
                   5185: you have the address of a cell, perform @code{1 cells +}, and you will
                   5186: have the address of the next cell.
                   5187: 
1.68      anton    5188: @cindex contiguous regions and address arithmetic
1.67      anton    5189: In ANS Forth you can perform address arithmetic only within a contiguous
                   5190: region, i.e., if you have an address into one region, you can only add
                   5191: and subtract such that the result is still within the region; you can
                   5192: only subtract or compare addresses from within the same contiguous
                   5193: region.  Reasons: several contiguous regions can be arranged in memory
                   5194: in any way; on segmented systems addresses may have unusual
                   5195: representations, such that address arithmetic only works within a
                   5196: region.  Gforth provides a few more guarantees (linear address space,
                   5197: dictionary grows upwards), but in general I have found it easy to stay
                   5198: within contiguous regions (exception: computing and comparing to the
                   5199: address just beyond the end of an array).
                   5200: 
1.1       anton    5201: @cindex alignment of addresses for types
                   5202: ANS Forth also defines words for aligning addresses for specific
                   5203: types. Many computers require that accesses to specific data types
                   5204: must only occur at specific addresses; e.g., that cells may only be
                   5205: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   5206: accesses, it can usually perform aligned accesses faster. 
                   5207: 
                   5208: For the performance-conscious: alignment operations are usually only
                   5209: necessary during the definition of a data structure, not during the
                   5210: (more frequent) accesses to it.
                   5211: 
                   5212: ANS Forth defines no words for character-aligning addresses. This is not
                   5213: an oversight, but reflects the fact that addresses that are not
                   5214: char-aligned have no use in the standard and therefore will not be
                   5215: created.
                   5216: 
                   5217: @cindex @code{CREATE} and alignment
1.29      crook    5218: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    5219: are cell-aligned; in addition, Gforth guarantees that these addresses
                   5220: are aligned for all purposes.
                   5221: 
1.26      crook    5222: Note that the ANS Forth word @code{char} has nothing to do with address
                   5223: arithmetic.
1.1       anton    5224: 
1.44      crook    5225: 
1.1       anton    5226: doc-chars
                   5227: doc-char+
                   5228: doc-cells
                   5229: doc-cell+
                   5230: doc-cell
                   5231: doc-aligned
                   5232: doc-floats
                   5233: doc-float+
                   5234: doc-float
                   5235: doc-faligned
                   5236: doc-sfloats
                   5237: doc-sfloat+
                   5238: doc-sfaligned
                   5239: doc-dfloats
                   5240: doc-dfloat+
                   5241: doc-dfaligned
                   5242: doc-maxaligned
                   5243: doc-cfaligned
                   5244: doc-address-unit-bits
1.145     anton    5245: doc-/w
                   5246: doc-/l
1.44      crook    5247: 
1.32      anton    5248: @node Memory Blocks,  , Address arithmetic, Memory
1.1       anton    5249: @subsection Memory Blocks
                   5250: @cindex memory block words
1.27      crook    5251: @cindex character strings - moving and copying
                   5252: 
1.49      anton    5253: Memory blocks often represent character strings; For ways of storing
                   5254: character strings in memory see @ref{String Formats}.  For other
                   5255: string-processing words see @ref{Displaying characters and strings}.
1.1       anton    5256: 
1.67      anton    5257: A few of these words work on address unit blocks.  In that case, you
                   5258: usually have to insert @code{CHARS} before the word when working on
                   5259: character strings.  Most words work on character blocks, and expect a
                   5260: char-aligned address.
                   5261: 
                   5262: When copying characters between overlapping memory regions, use
                   5263: @code{chars move} or choose carefully between @code{cmove} and
                   5264: @code{cmove>}.
1.44      crook    5265: 
1.1       anton    5266: doc-move
                   5267: doc-erase
                   5268: doc-cmove
                   5269: doc-cmove>
                   5270: doc-fill
                   5271: doc-blank
1.21      crook    5272: doc-compare
1.111     anton    5273: doc-str=
                   5274: doc-str<
                   5275: doc-string-prefix?
1.21      crook    5276: doc-search
1.27      crook    5277: doc--trailing
                   5278: doc-/string
1.82      anton    5279: doc-bounds
1.141     anton    5280: doc-pad
1.111     anton    5281: 
1.27      crook    5282: @comment TODO examples
                   5283: 
1.1       anton    5284: 
1.26      crook    5285: @node Control Structures, Defining Words, Memory, Words
1.1       anton    5286: @section Control Structures
                   5287: @cindex control structures
                   5288: 
1.33      anton    5289: Control structures in Forth cannot be used interpretively, only in a
                   5290: colon definition@footnote{To be precise, they have no interpretation
                   5291: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
                   5292: not like this limitation, but have not seen a satisfying way around it
                   5293: yet, although many schemes have been proposed.
1.1       anton    5294: 
                   5295: @menu
1.33      anton    5296: * Selection::                   IF ... ELSE ... ENDIF
                   5297: * Simple Loops::                BEGIN ...
1.29      crook    5298: * Counted Loops::               DO
1.67      anton    5299: * Arbitrary control structures::  
                   5300: * Calls and returns::           
1.1       anton    5301: * Exception Handling::          
                   5302: @end menu
                   5303: 
                   5304: @node Selection, Simple Loops, Control Structures, Control Structures
                   5305: @subsection Selection
                   5306: @cindex selection control structures
                   5307: @cindex control structures for selection
                   5308: 
                   5309: @cindex @code{IF} control structure
                   5310: @example
1.29      crook    5311: @i{flag}
1.1       anton    5312: IF
1.29      crook    5313:   @i{code}
1.1       anton    5314: ENDIF
                   5315: @end example
1.21      crook    5316: @noindent
1.33      anton    5317: 
1.44      crook    5318: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
                   5319: with any bit set represents truth) @i{code} is executed.
1.33      anton    5320: 
1.1       anton    5321: @example
1.29      crook    5322: @i{flag}
1.1       anton    5323: IF
1.29      crook    5324:   @i{code1}
1.1       anton    5325: ELSE
1.29      crook    5326:   @i{code2}
1.1       anton    5327: ENDIF
                   5328: @end example
                   5329: 
1.44      crook    5330: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
                   5331: executed.
1.33      anton    5332: 
1.1       anton    5333: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   5334: standard, and @code{ENDIF} is not, although it is quite popular. We
                   5335: recommend using @code{ENDIF}, because it is less confusing for people
                   5336: who also know other languages (and is not prone to reinforcing negative
                   5337: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   5338: system that only supplies @code{THEN} is simple:
                   5339: @example
1.82      anton    5340: : ENDIF   POSTPONE then ; immediate
1.1       anton    5341: @end example
                   5342: 
                   5343: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   5344: (adv.)}  has the following meanings:
                   5345: @quotation
                   5346: ... 2b: following next after in order ... 3d: as a necessary consequence
                   5347: (if you were there, then you saw them).
                   5348: @end quotation
                   5349: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   5350: and many other programming languages has the meaning 3d.]
                   5351: 
1.21      crook    5352: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    5353: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    5354: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    5355: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   5356: @file{compat/control.fs}.
                   5357: 
                   5358: @cindex @code{CASE} control structure
                   5359: @example
1.213     anton    5360: @i{x}
1.1       anton    5361: CASE
1.213     anton    5362:   @i{x1} OF @i{code1} ENDOF
                   5363:   @i{x2} OF @i{code2} ENDOF
1.1       anton    5364:   @dots{}
1.213     anton    5365:   ( x ) @i{default-code} ( x )
1.131     anton    5366: ENDCASE ( )
1.1       anton    5367: @end example
                   5368: 
1.213     anton    5369: Executes the first @i{codei}, where the @i{xi} is equal to @i{x}.  If no
                   5370: @i{xi} matches, the optional @i{default-code} is executed. The optional
1.211     anton    5371: default case can be added by simply writing the code after the last
1.213     anton    5372: @code{ENDOF}. It may use @i{x}, which is on top of the stack, but must
                   5373: not consume it.  The value @i{x} is consumed by this construction
1.211     anton    5374: (either by an @code{OF} that matches, or by the @code{ENDCASE}, if no OF
                   5375: matches).  Example:
                   5376: 
                   5377: @example
1.213     anton    5378: : num-name ( n -- c-addr u )
1.211     anton    5379:  case
1.213     anton    5380:    0 of s" zero " endof
                   5381:    1 of s" one "  endof
                   5382:    2 of s" two "  endof
                   5383:    \ default case:
                   5384:    s" other number" 
                   5385:    rot \ get n on top so ENDCASE can drop it
1.211     anton    5386:  endcase ;
                   5387: @end example
1.1       anton    5388: 
1.232     anton    5389: You can also use (the non-standard) @code{?of} to use @code{case} as a
                   5390: general selection structure for more than two alternatives.
                   5391: @code{?Of} takes a flag.  Example:
                   5392: 
                   5393: @example
                   5394: : sgn ( n1 -- n2 )
                   5395:     \ sign function
                   5396:     case
                   5397:        dup 0< ?of drop -1 endof
                   5398:        dup 0> ?of drop 1 endof
                   5399:        dup \ n1=0 -> n2=0; dup an item, to be consumed by ENDCASE
                   5400:     endcase ;
                   5401: @end example
                   5402: 
1.69      anton    5403: @progstyle
1.131     anton    5404: To keep the code understandable, you should ensure that you change the
                   5405: stack in the same way (wrt. number and types of stack items consumed
1.232     anton    5406: and pushed) on all paths through a selection structure.
1.69      anton    5407: 
1.1       anton    5408: @node Simple Loops, Counted Loops, Selection, Control Structures
                   5409: @subsection Simple Loops
                   5410: @cindex simple loops
                   5411: @cindex loops without count 
                   5412: 
                   5413: @cindex @code{WHILE} loop
                   5414: @example
                   5415: BEGIN
1.29      crook    5416:   @i{code1}
                   5417:   @i{flag}
1.1       anton    5418: WHILE
1.29      crook    5419:   @i{code2}
1.1       anton    5420: REPEAT
                   5421: @end example
                   5422: 
1.29      crook    5423: @i{code1} is executed and @i{flag} is computed. If it is true,
                   5424: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    5425: false, execution continues after the @code{REPEAT}.
                   5426: 
                   5427: @cindex @code{UNTIL} loop
                   5428: @example
                   5429: BEGIN
1.29      crook    5430:   @i{code}
                   5431:   @i{flag}
1.1       anton    5432: UNTIL
                   5433: @end example
                   5434: 
1.29      crook    5435: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    5436: 
1.69      anton    5437: @progstyle
                   5438: To keep the code understandable, a complete iteration of the loop should
                   5439: not change the number and types of the items on the stacks.
                   5440: 
1.1       anton    5441: @cindex endless loop
                   5442: @cindex loops, endless
                   5443: @example
                   5444: BEGIN
1.29      crook    5445:   @i{code}
1.1       anton    5446: AGAIN
                   5447: @end example
                   5448: 
                   5449: This is an endless loop.
                   5450: 
                   5451: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   5452: @subsection Counted Loops
                   5453: @cindex counted loops
                   5454: @cindex loops, counted
                   5455: @cindex @code{DO} loops
                   5456: 
                   5457: The basic counted loop is:
                   5458: @example
1.29      crook    5459: @i{limit} @i{start}
1.1       anton    5460: ?DO
1.29      crook    5461:   @i{body}
1.1       anton    5462: LOOP
                   5463: @end example
                   5464: 
1.29      crook    5465: This performs one iteration for every integer, starting from @i{start}
                   5466: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    5467: accessed with @code{i}. For example, the loop:
1.1       anton    5468: @example
                   5469: 10 0 ?DO
                   5470:   i .
                   5471: LOOP
                   5472: @end example
1.21      crook    5473: @noindent
                   5474: prints @code{0 1 2 3 4 5 6 7 8 9}
                   5475: 
1.1       anton    5476: The index of the innermost loop can be accessed with @code{i}, the index
                   5477: of the next loop with @code{j}, and the index of the third loop with
                   5478: @code{k}.
                   5479: 
1.44      crook    5480: 
1.1       anton    5481: doc-i
                   5482: doc-j
                   5483: doc-k
                   5484: 
1.44      crook    5485: 
1.1       anton    5486: The loop control data are kept on the return stack, so there are some
1.21      crook    5487: restrictions on mixing return stack accesses and counted loop words. In
                   5488: particuler, if you put values on the return stack outside the loop, you
                   5489: cannot read them inside the loop@footnote{well, not in a way that is
                   5490: portable.}. If you put values on the return stack within a loop, you
                   5491: have to remove them before the end of the loop and before accessing the
                   5492: index of the loop.
1.1       anton    5493: 
                   5494: There are several variations on the counted loop:
                   5495: 
1.21      crook    5496: @itemize @bullet
                   5497: @item
                   5498: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   5499: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   5500: 
                   5501: @example
                   5502: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   5503: @end example
                   5504: prints @code{0 1 2 3}
                   5505: 
1.1       anton    5506: 
1.21      crook    5507: @item
                   5508: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   5509: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   5510: return stack so @code{EXIT} can get to its return address. For example:
                   5511: 
                   5512: @example
                   5513: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   5514: @end example
                   5515: prints @code{0 1 2 3}
                   5516: 
                   5517: 
                   5518: @item
1.29      crook    5519: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    5520: (and @code{LOOP} iterates until they become equal by wrap-around
                   5521: arithmetic). This behaviour is usually not what you want. Therefore,
                   5522: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    5523: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   5524: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    5525: unsigned loop parameters.
                   5526: 
1.21      crook    5527: @item
                   5528: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   5529: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   5530: if you know that the loop is entered in any case. Such knowledge tends
                   5531: to become invalid during maintenance of a program, and then the
                   5532: @code{DO} will make trouble.
                   5533: 
                   5534: @item
1.29      crook    5535: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   5536: index by @i{n} instead of by 1. The loop is terminated when the border
                   5537: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    5538: 
1.21      crook    5539: @example
                   5540: 4 0 +DO  i .  2 +LOOP
                   5541: @end example
                   5542: @noindent
                   5543: prints @code{0 2}
                   5544: 
                   5545: @example
                   5546: 4 1 +DO  i .  2 +LOOP
                   5547: @end example
                   5548: @noindent
                   5549: prints @code{1 3}
1.1       anton    5550: 
1.68      anton    5551: @item
1.1       anton    5552: @cindex negative increment for counted loops
                   5553: @cindex counted loops with negative increment
1.29      crook    5554: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    5555: 
1.21      crook    5556: @example
                   5557: -1 0 ?DO  i .  -1 +LOOP
                   5558: @end example
                   5559: @noindent
                   5560: prints @code{0 -1}
1.1       anton    5561: 
1.21      crook    5562: @example
                   5563: 0 0 ?DO  i .  -1 +LOOP
                   5564: @end example
                   5565: prints nothing.
1.1       anton    5566: 
1.29      crook    5567: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   5568: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   5569: index by @i{u} each iteration. The loop is terminated when the border
                   5570: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    5571: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   5572: 
1.21      crook    5573: @example
                   5574: -2 0 -DO  i .  1 -LOOP
                   5575: @end example
                   5576: @noindent
                   5577: prints @code{0 -1}
1.1       anton    5578: 
1.21      crook    5579: @example
                   5580: -1 0 -DO  i .  1 -LOOP
                   5581: @end example
                   5582: @noindent
                   5583: prints @code{0}
                   5584: 
                   5585: @example
                   5586: 0 0 -DO  i .  1 -LOOP
                   5587: @end example
                   5588: @noindent
                   5589: prints nothing.
1.1       anton    5590: 
1.21      crook    5591: @end itemize
1.1       anton    5592: 
                   5593: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    5594: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   5595: for these words that uses only standard words is provided in
                   5596: @file{compat/loops.fs}.
1.1       anton    5597: 
                   5598: 
                   5599: @cindex @code{FOR} loops
1.26      crook    5600: Another counted loop is:
1.1       anton    5601: @example
1.29      crook    5602: @i{n}
1.1       anton    5603: FOR
1.29      crook    5604:   @i{body}
1.1       anton    5605: NEXT
                   5606: @end example
                   5607: This is the preferred loop of native code compiler writers who are too
1.26      crook    5608: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    5609: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   5610: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    5611: Forth systems may behave differently, even if they support @code{FOR}
                   5612: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    5613: 
                   5614: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   5615: @subsection Arbitrary control structures
                   5616: @cindex control structures, user-defined
                   5617: 
                   5618: @cindex control-flow stack
                   5619: ANS Forth permits and supports using control structures in a non-nested
                   5620: way. Information about incomplete control structures is stored on the
                   5621: control-flow stack. This stack may be implemented on the Forth data
                   5622: stack, and this is what we have done in Gforth.
                   5623: 
                   5624: @cindex @code{orig}, control-flow stack item
                   5625: @cindex @code{dest}, control-flow stack item
                   5626: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   5627: entry represents a backward branch target. A few words are the basis for
                   5628: building any control structure possible (except control structures that
                   5629: need storage, like calls, coroutines, and backtracking).
                   5630: 
1.44      crook    5631: 
1.1       anton    5632: doc-if
                   5633: doc-ahead
                   5634: doc-then
                   5635: doc-begin
                   5636: doc-until
                   5637: doc-again
                   5638: doc-cs-pick
                   5639: doc-cs-roll
                   5640: 
1.44      crook    5641: 
1.21      crook    5642: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   5643: manipulate the control-flow stack in a portable way. Without them, you
                   5644: would need to know how many stack items are occupied by a control-flow
                   5645: entry (many systems use one cell. In Gforth they currently take three,
                   5646: but this may change in the future).
                   5647: 
1.1       anton    5648: Some standard control structure words are built from these words:
                   5649: 
1.44      crook    5650: 
1.1       anton    5651: doc-else
                   5652: doc-while
                   5653: doc-repeat
                   5654: 
1.44      crook    5655: 
                   5656: @noindent
1.1       anton    5657: Gforth adds some more control-structure words:
                   5658: 
1.44      crook    5659: 
1.1       anton    5660: doc-endif
                   5661: doc-?dup-if
                   5662: doc-?dup-0=-if
                   5663: 
1.44      crook    5664: 
                   5665: @noindent
1.1       anton    5666: Counted loop words constitute a separate group of words:
                   5667: 
1.44      crook    5668: 
1.1       anton    5669: doc-?do
                   5670: doc-+do
                   5671: doc-u+do
                   5672: doc--do
                   5673: doc-u-do
                   5674: doc-do
                   5675: doc-for
                   5676: doc-loop
                   5677: doc-+loop
                   5678: doc--loop
                   5679: doc-next
                   5680: doc-leave
                   5681: doc-?leave
                   5682: doc-unloop
                   5683: doc-done
                   5684: 
1.44      crook    5685: 
1.21      crook    5686: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   5687: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    5688: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   5689: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   5690: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   5691: resolved (by using one of the loop-ending words or @code{DONE}).
                   5692: 
1.44      crook    5693: @noindent
1.26      crook    5694: Another group of control structure words are:
1.1       anton    5695: 
1.44      crook    5696: 
1.1       anton    5697: doc-case
                   5698: doc-endcase
                   5699: doc-of
1.232     anton    5700: doc-?ofx
1.1       anton    5701: doc-endof
                   5702: 
1.44      crook    5703: 
1.21      crook    5704: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   5705: @code{CS-ROLL}.
1.1       anton    5706: 
                   5707: @subsubsection Programming Style
1.47      crook    5708: @cindex control structures programming style
                   5709: @cindex programming style, arbitrary control structures
1.1       anton    5710: 
                   5711: In order to ensure readability we recommend that you do not create
                   5712: arbitrary control structures directly, but define new control structure
                   5713: words for the control structure you want and use these words in your
1.26      crook    5714: program. For example, instead of writing:
1.1       anton    5715: 
                   5716: @example
1.26      crook    5717: BEGIN
1.1       anton    5718:   ...
1.26      crook    5719: IF [ 1 CS-ROLL ]
1.1       anton    5720:   ...
1.26      crook    5721: AGAIN THEN
1.1       anton    5722: @end example
                   5723: 
1.21      crook    5724: @noindent
1.1       anton    5725: we recommend defining control structure words, e.g.,
                   5726: 
                   5727: @example
1.26      crook    5728: : WHILE ( DEST -- ORIG DEST )
                   5729:  POSTPONE IF
                   5730:  1 CS-ROLL ; immediate
                   5731: 
                   5732: : REPEAT ( orig dest -- )
                   5733:  POSTPONE AGAIN
                   5734:  POSTPONE THEN ; immediate
1.1       anton    5735: @end example
                   5736: 
1.21      crook    5737: @noindent
1.1       anton    5738: and then using these to create the control structure:
                   5739: 
                   5740: @example
1.26      crook    5741: BEGIN
1.1       anton    5742:   ...
1.26      crook    5743: WHILE
1.1       anton    5744:   ...
1.26      crook    5745: REPEAT
1.1       anton    5746: @end example
                   5747: 
                   5748: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   5749: @code{WHILE} are predefined, so in this example it would not be
                   5750: necessary to define them.
                   5751: 
                   5752: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   5753: @subsection Calls and returns
                   5754: @cindex calling a definition
                   5755: @cindex returning from a definition
                   5756: 
1.3       anton    5757: @cindex recursive definitions
                   5758: A definition can be called simply be writing the name of the definition
1.26      crook    5759: to be called. Normally a definition is invisible during its own
1.3       anton    5760: definition. If you want to write a directly recursive definition, you
1.26      crook    5761: can use @code{recursive} to make the current definition visible, or
                   5762: @code{recurse} to call the current definition directly.
1.3       anton    5763: 
1.44      crook    5764: 
1.3       anton    5765: doc-recursive
                   5766: doc-recurse
                   5767: 
1.44      crook    5768: 
1.21      crook    5769: @comment TODO add example of the two recursion methods
1.12      anton    5770: @quotation
                   5771: @progstyle
                   5772: I prefer using @code{recursive} to @code{recurse}, because calling the
                   5773: definition by name is more descriptive (if the name is well-chosen) than
                   5774: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   5775: implementation, it is much better to read (and think) ``now sort the
                   5776: partitions'' than to read ``now do a recursive call''.
                   5777: @end quotation
1.3       anton    5778: 
1.29      crook    5779: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    5780: 
                   5781: @example
1.28      crook    5782: Defer foo
1.3       anton    5783: 
                   5784: : bar ( ... -- ... )
                   5785:  ... foo ... ;
                   5786: 
                   5787: :noname ( ... -- ... )
                   5788:  ... bar ... ;
                   5789: IS foo
                   5790: @end example
                   5791: 
1.170     pazsan   5792: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33      anton    5793: 
1.26      crook    5794: The current definition returns control to the calling definition when
1.33      anton    5795: the end of the definition is reached or @code{EXIT} is encountered.
1.1       anton    5796: 
                   5797: doc-exit
                   5798: doc-;s
                   5799: 
1.44      crook    5800: 
1.1       anton    5801: @node Exception Handling,  , Calls and returns, Control Structures
                   5802: @subsection Exception Handling
1.26      crook    5803: @cindex exceptions
1.1       anton    5804: 
1.68      anton    5805: @c quit is a very bad idea for error handling, 
                   5806: @c because it does not translate into a THROW
                   5807: @c it also does not belong into this chapter
                   5808: 
                   5809: If a word detects an error condition that it cannot handle, it can
                   5810: @code{throw} an exception.  In the simplest case, this will terminate
                   5811: your program, and report an appropriate error.
1.21      crook    5812: 
1.68      anton    5813: doc-throw
1.1       anton    5814: 
1.69      anton    5815: @code{Throw} consumes a cell-sized error number on the stack. There are
                   5816: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
                   5817: Gforth (and most other systems) you can use the iors produced by various
                   5818: words as error numbers (e.g., a typical use of @code{allocate} is
                   5819: @code{allocate throw}).  Gforth also provides the word @code{exception}
                   5820: to define your own error numbers (with decent error reporting); an ANS
                   5821: Forth version of this word (but without the error messages) is available
                   5822: in @code{compat/except.fs}.  And finally, you can use your own error
1.68      anton    5823: numbers (anything outside the range -4095..0), but won't get nice error
                   5824: messages, only numbers.  For example, try:
                   5825: 
                   5826: @example
1.69      anton    5827: -10 throw                    \ ANS defined
                   5828: -267 throw                   \ system defined
                   5829: s" my error" exception throw \ user defined
                   5830: 7 throw                      \ arbitrary number
1.68      anton    5831: @end example
                   5832: 
                   5833: doc---exception-exception
1.1       anton    5834: 
1.69      anton    5835: A common idiom to @code{THROW} a specific error if a flag is true is
                   5836: this:
                   5837: 
                   5838: @example
                   5839: @code{( flag ) 0<> @i{errno} and throw}
                   5840: @end example
                   5841: 
                   5842: Your program can provide exception handlers to catch exceptions.  An
                   5843: exception handler can be used to correct the problem, or to clean up
                   5844: some data structures and just throw the exception to the next exception
                   5845: handler.  Note that @code{throw} jumps to the dynamically innermost
                   5846: exception handler.  The system's exception handler is outermost, and just
                   5847: prints an error and restarts command-line interpretation (or, in batch
                   5848: mode (i.e., while processing the shell command line), leaves Gforth).
1.1       anton    5849: 
1.68      anton    5850: The ANS Forth way to catch exceptions is @code{catch}:
1.1       anton    5851: 
1.68      anton    5852: doc-catch
1.160     anton    5853: doc-nothrow
1.68      anton    5854: 
                   5855: The most common use of exception handlers is to clean up the state when
                   5856: an error happens.  E.g.,
1.1       anton    5857: 
1.26      crook    5858: @example
1.68      anton    5859: base @ >r hex \ actually the hex should be inside foo, or we h
                   5860: ['] foo catch ( nerror|0 )
                   5861: r> base !
1.69      anton    5862: ( nerror|0 ) throw \ pass it on
1.26      crook    5863: @end example
1.1       anton    5864: 
1.69      anton    5865: A use of @code{catch} for handling the error @code{myerror} might look
                   5866: like this:
1.44      crook    5867: 
1.68      anton    5868: @example
1.69      anton    5869: ['] foo catch
                   5870: CASE
1.160     anton    5871:   myerror OF ... ( do something about it ) nothrow ENDOF
1.69      anton    5872:   dup throw \ default: pass other errors on, do nothing on non-errors
                   5873: ENDCASE
1.68      anton    5874: @end example
1.44      crook    5875: 
1.68      anton    5876: Having to wrap the code into a separate word is often cumbersome,
                   5877: therefore Gforth provides an alternative syntax:
1.1       anton    5878: 
                   5879: @example
1.69      anton    5880: TRY
1.68      anton    5881:   @i{code1}
1.172     anton    5882:   IFERROR
                   5883:     @i{code2}
                   5884:   THEN
                   5885:   @i{code3}
1.69      anton    5886: ENDTRY
1.1       anton    5887: @end example
                   5888: 
1.172     anton    5889: This performs @i{code1}.  If @i{code1} completes normally, execution
1.201     anton    5890: continues with @i{code3}.  If there is an exception in @i{code1} or
                   5891: before @code{endtry}, the stacks are reset to the depth during
1.172     anton    5892: @code{try}, the throw value is pushed on the data stack, and execution
1.239     anton    5893: continues at @i{code2}, and finally falls through to @i{code3}.
1.26      crook    5894: 
1.68      anton    5895: doc-try
                   5896: doc-endtry
1.172     anton    5897: doc-iferror
                   5898: 
                   5899: If you don't need @i{code2}, you can write @code{restore} instead of
                   5900: @code{iferror then}:
                   5901: 
                   5902: @example
                   5903: TRY
                   5904:   @i{code1}
                   5905: RESTORE
                   5906:   @i{code3}
                   5907: ENDTRY
                   5908: @end example
1.26      crook    5909: 
1.172     anton    5910: @cindex unwind-protect
1.69      anton    5911: The cleanup example from above in this syntax:
1.26      crook    5912: 
1.68      anton    5913: @example
1.174     anton    5914: base @@ @{ oldbase @}
1.172     anton    5915: TRY
1.68      anton    5916:   hex foo \ now the hex is placed correctly
1.69      anton    5917:   0       \ value for throw
1.172     anton    5918: RESTORE
                   5919:   oldbase base !
                   5920: ENDTRY
                   5921: throw
1.1       anton    5922: @end example
                   5923: 
1.172     anton    5924: An additional advantage of this variant is that an exception between
                   5925: @code{restore} and @code{endtry} (e.g., from the user pressing
                   5926: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
                   5927: so the base will be restored under all circumstances.
                   5928: 
                   5929: However, you have to ensure that this code does not cause an exception
                   5930: itself, otherwise the @code{iferror}/@code{restore} code will loop.
                   5931: Moreover, you should also make sure that the stack contents needed by
                   5932: the @code{iferror}/@code{restore} code exist everywhere between
                   5933: @code{try} and @code{endtry}; in our example this is achived by
                   5934: putting the data in a local before the @code{try} (you cannot use the
                   5935: return stack because the exception frame (@i{sys1}) is in the way
                   5936: there).
                   5937: 
                   5938: This kind of usage corresponds to Lisp's @code{unwind-protect}.
                   5939: 
                   5940: @cindex @code{recover} (old Gforth versions)
                   5941: If you do not want this exception-restarting behaviour, you achieve
                   5942: this as follows:
                   5943: 
                   5944: @example
                   5945: TRY
                   5946:   @i{code1}
                   5947: ENDTRY-IFERROR
                   5948:   @i{code2}
                   5949: THEN
                   5950: @end example
                   5951: 
                   5952: If there is an exception in @i{code1}, then @i{code2} is executed,
                   5953: otherwise execution continues behind the @code{then} (or in a possible
                   5954: @code{else} branch).  This corresponds to the construct
                   5955: 
                   5956: @example
                   5957: TRY
                   5958:   @i{code1}
                   5959: RECOVER
                   5960:   @i{code2}
                   5961: ENDTRY
                   5962: @end example
                   5963: 
                   5964: in Gforth before version 0.7.  So you can directly replace
                   5965: @code{recover}-using code; however, we recommend that you check if it
                   5966: would not be better to use one of the other @code{try} variants while
                   5967: you are at it.
                   5968: 
1.173     anton    5969: To ease the transition, Gforth provides two compatibility files:
                   5970: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
                   5971: ... then} syntax (but not @code{iferror} or @code{restore}) for old
                   5972: systems; @file{recover-endtry.fs} provides the @code{try ... recover
                   5973: ... endtry} syntax on new systems, so you can use that file as a
                   5974: stopgap to run old programs.  Both files work on any system (they just
                   5975: do nothing if the system already has the syntax it implements), so you
                   5976: can unconditionally @code{require} one of these files, even if you use
                   5977: a mix old and new systems.
                   5978: 
1.172     anton    5979: doc-restore
                   5980: doc-endtry-iferror
                   5981: 
                   5982: Here's the error handling example:
1.1       anton    5983: 
1.68      anton    5984: @example
1.69      anton    5985: TRY
1.68      anton    5986:   foo
1.172     anton    5987: ENDTRY-IFERROR
1.69      anton    5988:   CASE
1.160     anton    5989:     myerror OF ... ( do something about it ) nothrow ENDOF
1.69      anton    5990:     throw \ pass other errors on
                   5991:   ENDCASE
1.172     anton    5992: THEN
1.68      anton    5993: @end example
1.1       anton    5994: 
1.69      anton    5995: @progstyle
                   5996: As usual, you should ensure that the stack depth is statically known at
                   5997: the end: either after the @code{throw} for passing on errors, or after
                   5998: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
                   5999: selection construct for handling the error).
                   6000: 
1.68      anton    6001: There are two alternatives to @code{throw}: @code{Abort"} is conditional
                   6002: and you can provide an error message.  @code{Abort} just produces an
                   6003: ``Aborted'' error.
1.1       anton    6004: 
1.68      anton    6005: The problem with these words is that exception handlers cannot
                   6006: differentiate between different @code{abort"}s; they just look like
                   6007: @code{-2 throw} to them (the error message cannot be accessed by
                   6008: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
                   6009: exception handlers.
1.44      crook    6010: 
1.68      anton    6011: doc-abort"
1.26      crook    6012: doc-abort
1.29      crook    6013: 
                   6014: 
1.44      crook    6015: 
1.29      crook    6016: @c -------------------------------------------------------------
1.47      crook    6017: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29      crook    6018: @section Defining Words
                   6019: @cindex defining words
                   6020: 
1.47      crook    6021: Defining words are used to extend Forth by creating new entries in the dictionary.
                   6022: 
1.29      crook    6023: @menu
1.67      anton    6024: * CREATE::                      
1.44      crook    6025: * Variables::                   Variables and user variables
1.67      anton    6026: * Constants::                   
1.44      crook    6027: * Values::                      Initialised variables
1.67      anton    6028: * Colon Definitions::           
1.44      crook    6029: * Anonymous Definitions::       Definitions without names
1.236     anton    6030: * Quotations::                  
1.69      anton    6031: * Supplying names::             Passing definition names as strings
1.67      anton    6032: * User-defined Defining Words::  
1.170     pazsan   6033: * Deferred Words::              Allow forward references
1.67      anton    6034: * Aliases::                     
1.29      crook    6035: @end menu
                   6036: 
1.44      crook    6037: @node CREATE, Variables, Defining Words, Defining Words
                   6038: @subsection @code{CREATE}
1.29      crook    6039: @cindex simple defining words
                   6040: @cindex defining words, simple
                   6041: 
                   6042: Defining words are used to create new entries in the dictionary. The
                   6043: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   6044: this:
                   6045: 
                   6046: @example
                   6047: CREATE new-word1
                   6048: @end example
                   6049: 
1.69      anton    6050: @code{CREATE} is a parsing word, i.e., it takes an argument from the
                   6051: input stream (@code{new-word1} in our example).  It generates a
                   6052: dictionary entry for @code{new-word1}. When @code{new-word1} is
                   6053: executed, all that it does is leave an address on the stack. The address
                   6054: represents the value of the data space pointer (@code{HERE}) at the time
                   6055: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
                   6056: associating a name with the address of a region of memory.
1.29      crook    6057: 
1.34      anton    6058: doc-create
                   6059: 
1.69      anton    6060: Note that in ANS Forth guarantees only for @code{create} that its body
                   6061: is in dictionary data space (i.e., where @code{here}, @code{allot}
                   6062: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
                   6063: @code{create}d words can be modified with @code{does>}
                   6064: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
                   6065: can only be applied to @code{create}d words.
                   6066: 
1.29      crook    6067: By extending this example to reserve some memory in data space, we end
1.69      anton    6068: up with something like a @i{variable}. Here are two different ways to do
                   6069: it:
1.29      crook    6070: 
                   6071: @example
                   6072: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   6073: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   6074: @end example
                   6075: 
                   6076: The variable can be examined and modified using @code{@@} (``fetch'') and
                   6077: @code{!} (``store'') like this:
                   6078: 
                   6079: @example
                   6080: new-word2 @@ .      \ get address, fetch from it and display
                   6081: 1234 new-word2 !   \ new value, get address, store to it
                   6082: @end example
                   6083: 
1.44      crook    6084: @cindex arrays
                   6085: A similar mechanism can be used to create arrays. For example, an
                   6086: 80-character text input buffer:
1.29      crook    6087: 
                   6088: @example
1.44      crook    6089: CREATE text-buf 80 chars allot
                   6090: 
1.168     anton    6091: text-buf 0 chars + c@@ \ the 1st character (offset 0)
                   6092: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44      crook    6093: @end example
1.29      crook    6094: 
1.44      crook    6095: You can build arbitrarily complex data structures by allocating
1.49      anton    6096: appropriate areas of memory. For further discussions of this, and to
1.66      anton    6097: learn about some Gforth tools that make it easier,
1.49      anton    6098: @xref{Structures}.
1.44      crook    6099: 
                   6100: 
                   6101: @node Variables, Constants, CREATE, Defining Words
                   6102: @subsection Variables
                   6103: @cindex variables
                   6104: 
                   6105: The previous section showed how a sequence of commands could be used to
                   6106: generate a variable.  As a final refinement, the whole code sequence can
                   6107: be wrapped up in a defining word (pre-empting the subject of the next
                   6108: section), making it easier to create new variables:
                   6109: 
                   6110: @example
                   6111: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
                   6112: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
                   6113: 
                   6114: myvariableX foo \ variable foo starts off with an unknown value
                   6115: myvariable0 joe \ whilst joe is initialised to 0
1.29      crook    6116: 
                   6117: 45 3 * foo !   \ set foo to 135
                   6118: 1234 joe !     \ set joe to 1234
                   6119: 3 joe +!       \ increment joe by 3.. to 1237
                   6120: @end example
                   6121: 
                   6122: Not surprisingly, there is no need to define @code{myvariable}, since
1.44      crook    6123: Forth already has a definition @code{Variable}. ANS Forth does not
1.69      anton    6124: guarantee that a @code{Variable} is initialised when it is created
                   6125: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
                   6126: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
                   6127: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47      crook    6128: @code{fvariable} for double and floating-point variables, respectively
1.69      anton    6129: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47      crook    6130: store a boolean, you can use @code{on} and @code{off} to toggle its
                   6131: state.
1.29      crook    6132: 
1.34      anton    6133: doc-variable
                   6134: doc-2variable
                   6135: doc-fvariable
                   6136: 
1.29      crook    6137: @cindex user variables
                   6138: @cindex user space
                   6139: The defining word @code{User} behaves in the same way as @code{Variable}.
                   6140: The difference is that it reserves space in @i{user (data) space} rather
                   6141: than normal data space. In a Forth system that has a multi-tasker, each
                   6142: task has its own set of user variables.
                   6143: 
1.34      anton    6144: doc-user
1.67      anton    6145: @c doc-udp
                   6146: @c doc-uallot
1.34      anton    6147: 
1.29      crook    6148: @comment TODO is that stuff about user variables strictly correct? Is it
                   6149: @comment just terminal tasks that have user variables?
                   6150: @comment should document tasker.fs (with some examples) elsewhere
                   6151: @comment in this manual, then expand on user space and user variables.
                   6152: 
1.44      crook    6153: @node Constants, Values, Variables, Defining Words
                   6154: @subsection Constants
                   6155: @cindex constants
                   6156: 
                   6157: @code{Constant} allows you to declare a fixed value and refer to it by
                   6158: name. For example:
1.29      crook    6159: 
                   6160: @example
                   6161: 12 Constant INCHES-PER-FOOT
                   6162: 3E+08 fconstant SPEED-O-LIGHT
                   6163: @end example
                   6164: 
                   6165: A @code{Variable} can be both read and written, so its run-time
                   6166: behaviour is to supply an address through which its current value can be
                   6167: manipulated. In contrast, the value of a @code{Constant} cannot be
                   6168: changed once it has been declared@footnote{Well, often it can be -- but
                   6169: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   6170: on).} so it's not necessary to supply the address -- it is more
                   6171: efficient to return the value of the constant directly. That's exactly
                   6172: what happens; the run-time effect of a constant is to put its value on
1.49      anton    6173: the top of the stack (You can find one
                   6174: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29      crook    6175: 
1.69      anton    6176: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29      crook    6177: double and floating-point constants, respectively.
                   6178: 
1.34      anton    6179: doc-constant
                   6180: doc-2constant
                   6181: doc-fconstant
                   6182: 
                   6183: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44      crook    6184: @c nac-> How could that not be true in an ANS Forth? You can't define a
                   6185: @c constant, use it and then delete the definition of the constant..
1.69      anton    6186: 
                   6187: @c anton->An ANS Forth system can compile a constant to a literal; On
                   6188: @c decompilation you would see only the number, just as if it had been used
                   6189: @c in the first place.  The word will stay, of course, but it will only be
                   6190: @c used by the text interpreter (no run-time duties, except when it is 
                   6191: @c POSTPONEd or somesuch).
                   6192: 
                   6193: @c nac:
1.44      crook    6194: @c I agree that it's rather deep, but IMO it is an important difference
                   6195: @c relative to other programming languages.. often it's annoying: it
                   6196: @c certainly changes my programming style relative to C.
                   6197: 
1.69      anton    6198: @c anton: In what way?
                   6199: 
1.29      crook    6200: Constants in Forth behave differently from their equivalents in other
                   6201: programming languages. In other languages, a constant (such as an EQU in
                   6202: assembler or a #define in C) only exists at compile-time; in the
                   6203: executable program the constant has been translated into an absolute
                   6204: number and, unless you are using a symbolic debugger, it's impossible to
                   6205: know what abstract thing that number represents. In Forth a constant has
1.44      crook    6206: an entry in the header space and remains there after the code that uses
                   6207: it has been defined. In fact, it must remain in the dictionary since it
                   6208: has run-time duties to perform. For example:
1.29      crook    6209: 
                   6210: @example
                   6211: 12 Constant INCHES-PER-FOOT
                   6212: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   6213: @end example
                   6214: 
                   6215: @cindex in-lining of constants
                   6216: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   6217: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   6218: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   6219: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   6220: attempt to optimise constants by in-lining them where they are used. You
                   6221: can force Gforth to in-line a constant like this:
                   6222: 
                   6223: @example
                   6224: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   6225: @end example
                   6226: 
                   6227: If you use @code{see} to decompile @i{this} version of
                   6228: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49      anton    6229: longer present. To understand how this works, read
                   6230: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29      crook    6231: 
                   6232: In-lining constants in this way might improve execution time
                   6233: fractionally, and can ensure that a constant is now only referenced at
                   6234: compile-time. However, the definition of the constant still remains in
                   6235: the dictionary. Some Forth compilers provide a mechanism for controlling
                   6236: a second dictionary for holding transient words such that this second
                   6237: dictionary can be deleted later in order to recover memory
                   6238: space. However, there is no standard way of doing this.
                   6239: 
                   6240: 
1.44      crook    6241: @node Values, Colon Definitions, Constants, Defining Words
                   6242: @subsection Values
                   6243: @cindex values
1.34      anton    6244: 
1.69      anton    6245: A @code{Value} behaves like a @code{Constant}, but it can be changed.
                   6246: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
                   6247: (not in ANS Forth) you can access (and change) a @code{value} also with
                   6248: @code{>body}.
                   6249: 
                   6250: Here are some
                   6251: examples:
1.29      crook    6252: 
                   6253: @example
1.69      anton    6254: 12 Value APPLES     \ Define APPLES with an initial value of 12
                   6255: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
                   6256: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
                   6257: APPLES              \ puts 35 on the top of the stack.
1.29      crook    6258: @end example
                   6259: 
1.44      crook    6260: doc-value
                   6261: doc-to
1.29      crook    6262: 
1.35      anton    6263: 
1.69      anton    6264: 
1.44      crook    6265: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
                   6266: @subsection Colon Definitions
                   6267: @cindex colon definitions
1.35      anton    6268: 
                   6269: @example
1.44      crook    6270: : name ( ... -- ... )
                   6271:     word1 word2 word3 ;
1.29      crook    6272: @end example
                   6273: 
1.44      crook    6274: @noindent
                   6275: Creates a word called @code{name} that, upon execution, executes
                   6276: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29      crook    6277: 
1.49      anton    6278: The explanation above is somewhat superficial. For simple examples of
                   6279: colon definitions see @ref{Your first definition}.  For an in-depth
1.66      anton    6280: discussion of some of the issues involved, @xref{Interpretation and
1.49      anton    6281: Compilation Semantics}.
1.29      crook    6282: 
1.44      crook    6283: doc-:
                   6284: doc-;
1.1       anton    6285: 
1.34      anton    6286: 
1.236     anton    6287: @node Anonymous Definitions, Quotations, Colon Definitions, Defining Words
1.44      crook    6288: @subsection Anonymous Definitions
                   6289: @cindex colon definitions
                   6290: @cindex defining words without name
1.34      anton    6291: 
1.44      crook    6292: Sometimes you want to define an @dfn{anonymous word}; a word without a
                   6293: name. You can do this with:
1.1       anton    6294: 
1.44      crook    6295: doc-:noname
1.1       anton    6296: 
1.44      crook    6297: This leaves the execution token for the word on the stack after the
                   6298: closing @code{;}. Here's an example in which a deferred word is
                   6299: initialised with an @code{xt} from an anonymous colon definition:
1.1       anton    6300: 
1.29      crook    6301: @example
1.44      crook    6302: Defer deferred
                   6303: :noname ( ... -- ... )
                   6304:   ... ;
                   6305: IS deferred
1.29      crook    6306: @end example
1.26      crook    6307: 
1.44      crook    6308: @noindent
                   6309: Gforth provides an alternative way of doing this, using two separate
                   6310: words:
1.27      crook    6311: 
1.44      crook    6312: doc-noname
                   6313: @cindex execution token of last defined word
1.116     anton    6314: doc-latestxt
1.1       anton    6315: 
1.44      crook    6316: @noindent
                   6317: The previous example can be rewritten using @code{noname} and
1.116     anton    6318: @code{latestxt}:
1.1       anton    6319: 
1.26      crook    6320: @example
1.44      crook    6321: Defer deferred
                   6322: noname : ( ... -- ... )
                   6323:   ... ;
1.116     anton    6324: latestxt IS deferred
1.26      crook    6325: @end example
1.1       anton    6326: 
1.29      crook    6327: @noindent
1.44      crook    6328: @code{noname} works with any defining word, not just @code{:}.
                   6329: 
1.116     anton    6330: @code{latestxt} also works when the last word was not defined as
1.71      anton    6331: @code{noname}.  It does not work for combined words, though.  It also has
                   6332: the useful property that is is valid as soon as the header for a
                   6333: definition has been built. Thus:
1.44      crook    6334: 
                   6335: @example
1.116     anton    6336: latestxt . : foo [ latestxt . ] ; ' foo .
1.44      crook    6337: @end example
1.1       anton    6338: 
1.44      crook    6339: @noindent
                   6340: prints 3 numbers; the last two are the same.
1.26      crook    6341: 
1.236     anton    6342: 
                   6343: @node Quotations, Supplying names, Anonymous Definitions, Defining Words
                   6344: @subsection Quotations
                   6345: @cindex quotations
                   6346: @cindex nested colon definitions
                   6347: @cindex colon definitions, nesting
                   6348: 
                   6349: A quotation is an anonymous colon definition inside another colon
                   6350: definition.  Quotations are useful when dealing with words that
                   6351: consume an execution token, like @code{catch} or
                   6352: @code{outfile-execute}.  E.g. consider the following example of using
                   6353: @code{outfile-execute} (@pxref{Redirection}):
                   6354: 
                   6355: @example
                   6356: : some-warning ( n -- )
                   6357:     cr ." warning# " . ;
                   6358: 
                   6359: : print-some-warning ( n -- )
                   6360:     ['] some-warning stderr outfile-execute ;
                   6361: @end example
                   6362: 
                   6363: Here we defined @code{some-warning} as a helper word whose xt we could
                   6364: pass to outfile-execute.  Instead, we can use a quotation to define
                   6365: such a word anonymously inside @code{print-some-warning}:
                   6366: 
                   6367: @example
                   6368: : print-some-warning ( n -- )
                   6369:   [: cr ." warning# " . ;] stderr outfile-execute ;
                   6370: @end example
                   6371: 
                   6372: The quotation is bouded by @code{[:} and @code{;]}.  It produces an
                   6373: execution token at run-time.
                   6374: 
                   6375: doc-[:
                   6376: doc-;]
                   6377: 
                   6378: 
                   6379: @node Supplying names, User-defined Defining Words, Quotations, Defining Words
1.69      anton    6380: @subsection Supplying the name of a defined word
                   6381: @cindex names for defined words
                   6382: @cindex defining words, name given in a string
                   6383: 
                   6384: By default, a defining word takes the name for the defined word from the
                   6385: input stream. Sometimes you want to supply the name from a string. You
                   6386: can do this with:
                   6387: 
                   6388: doc-nextname
                   6389: 
                   6390: For example:
                   6391: 
                   6392: @example
                   6393: s" foo" nextname create
                   6394: @end example
                   6395: 
                   6396: @noindent
                   6397: is equivalent to:
                   6398: 
                   6399: @example
                   6400: create foo
                   6401: @end example
                   6402: 
                   6403: @noindent
                   6404: @code{nextname} works with any defining word.
                   6405: 
1.1       anton    6406: 
1.170     pazsan   6407: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26      crook    6408: @subsection User-defined Defining Words
                   6409: @cindex user-defined defining words
                   6410: @cindex defining words, user-defined
1.1       anton    6411: 
1.29      crook    6412: You can create a new defining word by wrapping defining-time code around
                   6413: an existing defining word and putting the sequence in a colon
1.69      anton    6414: definition. 
                   6415: 
                   6416: @c anton: This example is very complex and leads in a quite different
                   6417: @c direction from the CREATE-DOES> stuff that follows.  It should probably
                   6418: @c be done elsewhere, or as a subsubsection of this subsection (or as a
                   6419: @c subsection of Defining Words)
                   6420: 
                   6421: For example, suppose that you have a word @code{stats} that
1.29      crook    6422: gathers statistics about colon definitions given the @i{xt} of the
                   6423: definition, and you want every colon definition in your application to
                   6424: make a call to @code{stats}. You can define and use a new version of
                   6425: @code{:} like this:
                   6426: 
                   6427: @example
                   6428: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   6429:   ... ;  \ other code
                   6430: 
1.116     anton    6431: : my: : latestxt postpone literal ['] stats compile, ;
1.29      crook    6432: 
                   6433: my: foo + - ;
                   6434: @end example
                   6435: 
                   6436: When @code{foo} is defined using @code{my:} these steps occur:
                   6437: 
                   6438: @itemize @bullet
                   6439: @item
                   6440: @code{my:} is executed.
                   6441: @item
                   6442: The @code{:} within the definition (the one between @code{my:} and
1.116     anton    6443: @code{latestxt}) is executed, and does just what it always does; it parses
1.29      crook    6444: the input stream for a name, builds a dictionary header for the name
                   6445: @code{foo} and switches @code{state} from interpret to compile.
                   6446: @item
1.116     anton    6447: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29      crook    6448: being defined -- @code{foo} -- onto the stack.
                   6449: @item
                   6450: The code that was produced by @code{postpone literal} is executed; this
                   6451: causes the value on the stack to be compiled as a literal in the code
                   6452: area of @code{foo}.
                   6453: @item
                   6454: The code @code{['] stats} compiles a literal into the definition of
                   6455: @code{my:}. When @code{compile,} is executed, that literal -- the
                   6456: execution token for @code{stats} -- is layed down in the code area of
                   6457: @code{foo} , following the literal@footnote{Strictly speaking, the
                   6458: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   6459: in the code area is implementation-dependent. A threaded implementation
                   6460: might spit out the execution token directly whilst another
                   6461: implementation might spit out a native code sequence.}.
                   6462: @item
                   6463: At this point, the execution of @code{my:} is complete, and control
                   6464: returns to the text interpreter. The text interpreter is in compile
                   6465: state, so subsequent text @code{+ -} is compiled into the definition of
                   6466: @code{foo} and the @code{;} terminates the definition as always.
                   6467: @end itemize
                   6468: 
                   6469: You can use @code{see} to decompile a word that was defined using
                   6470: @code{my:} and see how it is different from a normal @code{:}
                   6471: definition. For example:
                   6472: 
                   6473: @example
                   6474: : bar + - ;  \ like foo but using : rather than my:
                   6475: see bar
                   6476: : bar
                   6477:   + - ;
                   6478: see foo
                   6479: : foo
                   6480:   107645672 stats + - ;
                   6481: 
1.140     anton    6482: \ use ' foo . to show that 107645672 is the xt for foo
1.29      crook    6483: @end example
                   6484: 
                   6485: You can use techniques like this to make new defining words in terms of
                   6486: @i{any} existing defining word.
1.1       anton    6487: 
                   6488: 
1.29      crook    6489: @cindex defining defining words
1.26      crook    6490: @cindex @code{CREATE} ... @code{DOES>}
                   6491: If you want the words defined with your defining words to behave
                   6492: differently from words defined with standard defining words, you can
                   6493: write your defining word like this:
1.1       anton    6494: 
                   6495: @example
1.26      crook    6496: : def-word ( "name" -- )
1.29      crook    6497:     CREATE @i{code1}
1.26      crook    6498: DOES> ( ... -- ... )
1.29      crook    6499:     @i{code2} ;
1.26      crook    6500: 
                   6501: def-word name
1.1       anton    6502: @end example
                   6503: 
1.29      crook    6504: @cindex child words
                   6505: This fragment defines a @dfn{defining word} @code{def-word} and then
                   6506: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   6507: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   6508: is not executed at this time. The word @code{name} is sometimes called a
                   6509: @dfn{child} of @code{def-word}.
                   6510: 
                   6511: When you execute @code{name}, the address of the body of @code{name} is
                   6512: put on the data stack and @i{code2} is executed (the address of the body
                   6513: of @code{name} is the address @code{HERE} returns immediately after the
1.69      anton    6514: @code{CREATE}, i.e., the address a @code{create}d word returns by
                   6515: default).
                   6516: 
                   6517: @c anton:
                   6518: @c www.dictionary.com says:
                   6519: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
                   6520: @c several generations of absence, usually caused by the chance
                   6521: @c recombination of genes.  2.An individual or a part that exhibits
                   6522: @c atavism. Also called throwback.  3.The return of a trait or recurrence
                   6523: @c of previous behavior after a period of absence.
                   6524: @c
                   6525: @c Doesn't seem to fit.
1.29      crook    6526: 
1.69      anton    6527: @c @cindex atavism in child words
1.33      anton    6528: You can use @code{def-word} to define a set of child words that behave
1.69      anton    6529: similarly; they all have a common run-time behaviour determined by
                   6530: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
                   6531: body of the child word. The structure of the data is common to all
                   6532: children of @code{def-word}, but the data values are specific -- and
                   6533: private -- to each child word. When a child word is executed, the
                   6534: address of its private data area is passed as a parameter on TOS to be
                   6535: used and manipulated@footnote{It is legitimate both to read and write to
                   6536: this data area.} by @i{code2}.
1.29      crook    6537: 
                   6538: The two fragments of code that make up the defining words act (are
                   6539: executed) at two completely separate times:
1.1       anton    6540: 
1.29      crook    6541: @itemize @bullet
                   6542: @item
                   6543: At @i{define time}, the defining word executes @i{code1} to generate a
                   6544: child word
                   6545: @item
                   6546: At @i{child execution time}, when a child word is invoked, @i{code2}
                   6547: is executed, using parameters (data) that are private and specific to
                   6548: the child word.
                   6549: @end itemize
                   6550: 
1.44      crook    6551: Another way of understanding the behaviour of @code{def-word} and
                   6552: @code{name} is to say that, if you make the following definitions:
1.33      anton    6553: @example
                   6554: : def-word1 ( "name" -- )
                   6555:     CREATE @i{code1} ;
                   6556: 
                   6557: : action1 ( ... -- ... )
                   6558:     @i{code2} ;
                   6559: 
                   6560: def-word1 name1
                   6561: @end example
                   6562: 
1.44      crook    6563: @noindent
                   6564: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    6565: 
1.29      crook    6566: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    6567: 
1.1       anton    6568: @example
1.29      crook    6569: : CONSTANT ( w "name" -- )
                   6570:     CREATE ,
1.26      crook    6571: DOES> ( -- w )
                   6572:     @@ ;
1.1       anton    6573: @end example
                   6574: 
1.29      crook    6575: @comment There is a beautiful description of how this works and what
                   6576: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   6577: @comment commentary on the Counting Fruits problem.
                   6578: 
                   6579: When you create a constant with @code{5 CONSTANT five}, a set of
                   6580: define-time actions take place; first a new word @code{five} is created,
                   6581: then the value 5 is laid down in the body of @code{five} with
1.44      crook    6582: @code{,}. When @code{five} is executed, the address of the body is put on
1.29      crook    6583: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   6584: no code of its own; it simply contains a data field and a pointer to the
                   6585: code that follows @code{DOES>} in its defining word. That makes words
                   6586: created in this way very compact.
                   6587: 
                   6588: The final example in this section is intended to remind you that space
                   6589: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   6590: both read and written by a Standard program@footnote{Exercise: use this
                   6591: example as a starting point for your own implementation of @code{Value}
                   6592: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   6593: @code{[']}.}:
                   6594: 
                   6595: @example
                   6596: : foo ( "name" -- )
                   6597:     CREATE -1 ,
                   6598: DOES> ( -- )
1.33      anton    6599:     @@ . ;
1.29      crook    6600: 
                   6601: foo first-word
                   6602: foo second-word
                   6603: 
                   6604: 123 ' first-word >BODY !
                   6605: @end example
                   6606: 
                   6607: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   6608: have executed it to get the address of its data field. However, since it
                   6609: was defined to have @code{DOES>} actions, its execution semantics are to
                   6610: perform those @code{DOES>} actions. To get the address of its data field
                   6611: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   6612: translate the xt into the address of the data field.  When you execute
                   6613: @code{first-word}, it will display @code{123}. When you execute
                   6614: @code{second-word} it will display @code{-1}.
1.26      crook    6615: 
                   6616: @cindex stack effect of @code{DOES>}-parts
                   6617: @cindex @code{DOES>}-parts, stack effect
1.29      crook    6618: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    6619: the stack effect of the defined words, not the stack effect of the
                   6620: following code (the following code expects the address of the body on
                   6621: the top of stack, which is not reflected in the stack comment). This is
                   6622: the convention that I use and recommend (it clashes a bit with using
                   6623: locals declarations for stack effect specification, though).
1.1       anton    6624: 
1.53      anton    6625: @menu
                   6626: * CREATE..DOES> applications::  
                   6627: * CREATE..DOES> details::       
1.63      anton    6628: * Advanced does> usage example::  
1.155     anton    6629: * Const-does>::                 
1.53      anton    6630: @end menu
                   6631: 
                   6632: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26      crook    6633: @subsubsection Applications of @code{CREATE..DOES>}
                   6634: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    6635: 
1.26      crook    6636: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    6637: 
1.26      crook    6638: @cindex factoring similar colon definitions
                   6639: When you see a sequence of code occurring several times, and you can
                   6640: identify a meaning, you will factor it out as a colon definition. When
                   6641: you see similar colon definitions, you can factor them using
                   6642: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   6643: that look very similar:
1.1       anton    6644: @example
1.26      crook    6645: : ori, ( reg-target reg-source n -- )
                   6646:     0 asm-reg-reg-imm ;
                   6647: : andi, ( reg-target reg-source n -- )
                   6648:     1 asm-reg-reg-imm ;
1.1       anton    6649: @end example
                   6650: 
1.26      crook    6651: @noindent
                   6652: This could be factored with:
                   6653: @example
                   6654: : reg-reg-imm ( op-code -- )
                   6655:     CREATE ,
                   6656: DOES> ( reg-target reg-source n -- )
                   6657:     @@ asm-reg-reg-imm ;
                   6658: 
                   6659: 0 reg-reg-imm ori,
                   6660: 1 reg-reg-imm andi,
                   6661: @end example
1.1       anton    6662: 
1.26      crook    6663: @cindex currying
                   6664: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   6665: supply a part of the parameters for a word (known as @dfn{currying} in
                   6666: the functional language community). E.g., @code{+} needs two
                   6667: parameters. Creating versions of @code{+} with one parameter fixed can
                   6668: be done like this:
1.82      anton    6669: 
1.1       anton    6670: @example
1.82      anton    6671: : curry+ ( n1 "name" -- )
1.26      crook    6672:     CREATE ,
                   6673: DOES> ( n2 -- n1+n2 )
                   6674:     @@ + ;
                   6675: 
                   6676:  3 curry+ 3+
                   6677: -2 curry+ 2-
1.1       anton    6678: @end example
                   6679: 
1.91      anton    6680: 
1.63      anton    6681: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26      crook    6682: @subsubsection The gory details of @code{CREATE..DOES>}
                   6683: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    6684: 
1.26      crook    6685: doc-does>
1.1       anton    6686: 
1.26      crook    6687: @cindex @code{DOES>} in a separate definition
                   6688: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   6689: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    6690: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    6691: @example
                   6692: : does1 
                   6693: DOES> ( ... -- ... )
1.44      crook    6694:     ... ;
                   6695: 
                   6696: : does2
                   6697: DOES> ( ... -- ... )
                   6698:     ... ;
                   6699: 
                   6700: : def-word ( ... -- ... )
                   6701:     create ...
                   6702:     IF
                   6703:        does1
                   6704:     ELSE
                   6705:        does2
                   6706:     ENDIF ;
                   6707: @end example
                   6708: 
                   6709: In this example, the selection of whether to use @code{does1} or
1.69      anton    6710: @code{does2} is made at definition-time; at the time that the child word is
1.44      crook    6711: @code{CREATE}d.
                   6712: 
                   6713: @cindex @code{DOES>} in interpretation state
                   6714: In a standard program you can apply a @code{DOES>}-part only if the last
                   6715: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   6716: will override the behaviour of the last word defined in any case. In a
                   6717: standard program, you can use @code{DOES>} only in a colon
                   6718: definition. In Gforth, you can also use it in interpretation state, in a
                   6719: kind of one-shot mode; for example:
                   6720: @example
                   6721: CREATE name ( ... -- ... )
                   6722:   @i{initialization}
                   6723: DOES>
                   6724:   @i{code} ;
                   6725: @end example
                   6726: 
                   6727: @noindent
                   6728: is equivalent to the standard:
                   6729: @example
                   6730: :noname
                   6731: DOES>
                   6732:     @i{code} ;
                   6733: CREATE name EXECUTE ( ... -- ... )
                   6734:     @i{initialization}
                   6735: @end example
                   6736: 
1.53      anton    6737: doc->body
                   6738: 
1.152     pazsan   6739: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63      anton    6740: @subsubsection Advanced does> usage example
                   6741: 
                   6742: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
                   6743: for disassembling instructions, that follow a very repetetive scheme:
                   6744: 
                   6745: @example
                   6746: :noname @var{disasm-operands} s" @var{inst-name}" type ;
                   6747: @var{entry-num} cells @var{table} + !
                   6748: @end example
                   6749: 
                   6750: Of course, this inspires the idea to factor out the commonalities to
                   6751: allow a definition like
                   6752: 
                   6753: @example
                   6754: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
                   6755: @end example
                   6756: 
                   6757: The parameters @var{disasm-operands} and @var{table} are usually
1.69      anton    6758: correlated.  Moreover, before I wrote the disassembler, there already
                   6759: existed code that defines instructions like this:
1.63      anton    6760: 
                   6761: @example
                   6762: @var{entry-num} @var{inst-format} @var{inst-name}
                   6763: @end example
                   6764: 
                   6765: This code comes from the assembler and resides in
                   6766: @file{arch/mips/insts.fs}.
                   6767: 
                   6768: So I had to define the @var{inst-format} words that performed the scheme
                   6769: above when executed.  At first I chose to use run-time code-generation:
                   6770: 
                   6771: @example
                   6772: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
                   6773:   :noname Postpone @var{disasm-operands}
                   6774:   name Postpone sliteral Postpone type Postpone ;
                   6775:   swap cells @var{table} + ! ;
                   6776: @end example
                   6777: 
                   6778: Note that this supplies the other two parameters of the scheme above.
1.44      crook    6779: 
1.63      anton    6780: An alternative would have been to write this using
                   6781: @code{create}/@code{does>}:
                   6782: 
                   6783: @example
                   6784: : @var{inst-format} ( entry-num "name" -- )
                   6785:   here name string, ( entry-num c-addr ) \ parse and save "name"
                   6786:   noname create , ( entry-num )
1.116     anton    6787:   latestxt swap cells @var{table} + !
1.63      anton    6788: does> ( addr w -- )
                   6789:   \ disassemble instruction w at addr
                   6790:   @@ >r 
                   6791:   @var{disasm-operands}
                   6792:   r> count type ;
                   6793: @end example
                   6794: 
                   6795: Somehow the first solution is simpler, mainly because it's simpler to
                   6796: shift a string from definition-time to use-time with @code{sliteral}
                   6797: than with @code{string,} and friends.
                   6798: 
                   6799: I wrote a lot of words following this scheme and soon thought about
                   6800: factoring out the commonalities among them.  Note that this uses a
                   6801: two-level defining word, i.e., a word that defines ordinary defining
                   6802: words.
                   6803: 
                   6804: This time a solution involving @code{postpone} and friends seemed more
                   6805: difficult (try it as an exercise), so I decided to use a
                   6806: @code{create}/@code{does>} word; since I was already at it, I also used
                   6807: @code{create}/@code{does>} for the lower level (try using
                   6808: @code{postpone} etc. as an exercise), resulting in the following
                   6809: definition:
                   6810: 
                   6811: @example
                   6812: : define-format ( disasm-xt table-xt -- )
                   6813:     \ define an instruction format that uses disasm-xt for
                   6814:     \ disassembling and enters the defined instructions into table
                   6815:     \ table-xt
                   6816:     create 2,
                   6817: does> ( u "inst" -- )
                   6818:     \ defines an anonymous word for disassembling instruction inst,
                   6819:     \ and enters it as u-th entry into table-xt
                   6820:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
                   6821:     noname create 2,      \ define anonymous word
1.116     anton    6822:     execute latestxt swap ! \ enter xt of defined word into table-xt
1.63      anton    6823: does> ( addr w -- )
                   6824:     \ disassemble instruction w at addr
                   6825:     2@@ >r ( addr w disasm-xt R: c-addr )
                   6826:     execute ( R: c-addr ) \ disassemble operands
                   6827:     r> count type ; \ print name 
                   6828: @end example
                   6829: 
                   6830: Note that the tables here (in contrast to above) do the @code{cells +}
                   6831: by themselves (that's why you have to pass an xt).  This word is used in
                   6832: the following way:
                   6833: 
                   6834: @example
                   6835: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
                   6836: @end example
                   6837: 
1.71      anton    6838: As shown above, the defined instruction format is then used like this:
                   6839: 
                   6840: @example
                   6841: @var{entry-num} @var{inst-format} @var{inst-name}
                   6842: @end example
                   6843: 
1.63      anton    6844: In terms of currying, this kind of two-level defining word provides the
                   6845: parameters in three stages: first @var{disasm-operands} and @var{table},
                   6846: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
                   6847: the instruction to be disassembled.  
                   6848: 
                   6849: Of course this did not quite fit all the instruction format names used
                   6850: in @file{insts.fs}, so I had to define a few wrappers that conditioned
                   6851: the parameters into the right form.
                   6852: 
                   6853: If you have trouble following this section, don't worry.  First, this is
                   6854: involved and takes time (and probably some playing around) to
                   6855: understand; second, this is the first two-level
                   6856: @code{create}/@code{does>} word I have written in seventeen years of
                   6857: Forth; and if I did not have @file{insts.fs} to start with, I may well
                   6858: have elected to use just a one-level defining word (with some repeating
                   6859: of parameters when using the defining word). So it is not necessary to
                   6860: understand this, but it may improve your understanding of Forth.
1.44      crook    6861: 
                   6862: 
1.152     pazsan   6863: @node Const-does>,  , Advanced does> usage example, User-defined Defining Words
1.91      anton    6864: @subsubsection @code{Const-does>}
                   6865: 
                   6866: A frequent use of @code{create}...@code{does>} is for transferring some
                   6867: values from definition-time to run-time.  Gforth supports this use with
                   6868: 
                   6869: doc-const-does>
                   6870: 
                   6871: A typical use of this word is:
                   6872: 
                   6873: @example
                   6874: : curry+ ( n1 "name" -- )
                   6875: 1 0 CONST-DOES> ( n2 -- n1+n2 )
                   6876:     + ;
                   6877: 
                   6878: 3 curry+ 3+
                   6879: @end example
                   6880: 
                   6881: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
                   6882: definition to run-time.
                   6883: 
                   6884: The advantages of using @code{const-does>} are:
                   6885: 
                   6886: @itemize
                   6887: 
                   6888: @item
                   6889: You don't have to deal with storing and retrieving the values, i.e.,
                   6890: your program becomes more writable and readable.
                   6891: 
                   6892: @item
                   6893: When using @code{does>}, you have to introduce a @code{@@} that cannot
                   6894: be optimized away (because you could change the data using
                   6895: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
                   6896: 
                   6897: @end itemize
                   6898: 
                   6899: An ANS Forth implementation of @code{const-does>} is available in
                   6900: @file{compat/const-does.fs}.
                   6901: 
                   6902: 
1.170     pazsan   6903: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
                   6904: @subsection Deferred Words
1.44      crook    6905: @cindex deferred words
                   6906: 
                   6907: The defining word @code{Defer} allows you to define a word by name
                   6908: without defining its behaviour; the definition of its behaviour is
                   6909: deferred. Here are two situation where this can be useful:
                   6910: 
                   6911: @itemize @bullet
                   6912: @item
                   6913: Where you want to allow the behaviour of a word to be altered later, and
                   6914: for all precompiled references to the word to change when its behaviour
                   6915: is changed.
                   6916: @item
                   6917: For mutual recursion; @xref{Calls and returns}.
                   6918: @end itemize
                   6919: 
                   6920: In the following example, @code{foo} always invokes the version of
                   6921: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
                   6922: always invokes the version that prints ``@code{Hello}''. There is no way
                   6923: of getting @code{foo} to use the later version without re-ordering the
                   6924: source code and recompiling it.
                   6925: 
                   6926: @example
                   6927: : greet ." Good morning" ;
                   6928: : foo ... greet ... ;
                   6929: : greet ." Hello" ;
                   6930: : bar ... greet ... ;
                   6931: @end example
                   6932: 
                   6933: This problem can be solved by defining @code{greet} as a @code{Defer}red
                   6934: word. The behaviour of a @code{Defer}red word can be defined and
                   6935: redefined at any time by using @code{IS} to associate the xt of a
                   6936: previously-defined word with it. The previous example becomes:
                   6937: 
                   6938: @example
1.69      anton    6939: Defer greet ( -- )
1.44      crook    6940: : foo ... greet ... ;
                   6941: : bar ... greet ... ;
1.69      anton    6942: : greet1 ( -- ) ." Good morning" ;
                   6943: : greet2 ( -- ) ." Hello" ;
1.132     anton    6944: ' greet2 IS greet  \ make greet behave like greet2
1.44      crook    6945: @end example
                   6946: 
1.69      anton    6947: @progstyle
                   6948: You should write a stack comment for every deferred word, and put only
                   6949: XTs into deferred words that conform to this stack effect.  Otherwise
                   6950: it's too difficult to use the deferred word.
                   6951: 
1.44      crook    6952: A deferred word can be used to improve the statistics-gathering example
                   6953: from @ref{User-defined Defining Words}; rather than edit the
                   6954: application's source code to change every @code{:} to a @code{my:}, do
                   6955: this:
                   6956: 
                   6957: @example
                   6958: : real: : ;     \ retain access to the original
                   6959: defer :         \ redefine as a deferred word
1.132     anton    6960: ' my: IS :      \ use special version of :
1.44      crook    6961: \
                   6962: \ load application here
                   6963: \
1.132     anton    6964: ' real: IS :    \ go back to the original
1.44      crook    6965: @end example
                   6966: 
                   6967: 
1.132     anton    6968: One thing to note is that @code{IS} has special compilation semantics,
                   6969: such that it parses the name at compile time (like @code{TO}):
1.44      crook    6970: 
                   6971: @example
                   6972: : set-greet ( xt -- )
1.132     anton    6973:   IS greet ;
1.44      crook    6974: 
                   6975: ' greet1 set-greet
                   6976: @end example
                   6977: 
1.132     anton    6978: In situations where @code{IS} does not fit, use @code{defer!} instead.
                   6979: 
1.69      anton    6980: A deferred word can only inherit execution semantics from the xt
                   6981: (because that is all that an xt can represent -- for more discussion of
                   6982: this @pxref{Tokens for Words}); by default it will have default
                   6983: interpretation and compilation semantics deriving from this execution
                   6984: semantics.  However, you can change the interpretation and compilation
                   6985: semantics of the deferred word in the usual ways:
1.44      crook    6986: 
                   6987: @example
1.132     anton    6988: : bar .... ; immediate
1.44      crook    6989: Defer fred immediate
                   6990: Defer jim
                   6991: 
1.132     anton    6992: ' bar IS jim  \ jim has default semantics
                   6993: ' bar IS fred \ fred is immediate
1.44      crook    6994: @end example
                   6995: 
                   6996: doc-defer
1.132     anton    6997: doc-defer!
1.44      crook    6998: doc-is
1.132     anton    6999: doc-defer@
                   7000: doc-action-of
1.44      crook    7001: @comment TODO document these: what's defers [is]
                   7002: doc-defers
                   7003: 
                   7004: @c Use @code{words-deferred} to see a list of deferred words.
                   7005: 
1.132     anton    7006: Definitions of these words (except @code{defers}) in ANS Forth are
                   7007: provided in @file{compat/defer.fs}.
1.44      crook    7008: 
                   7009: 
1.170     pazsan   7010: @node Aliases,  , Deferred Words, Defining Words
1.44      crook    7011: @subsection Aliases
                   7012: @cindex aliases
1.1       anton    7013: 
1.44      crook    7014: The defining word @code{Alias} allows you to define a word by name that
                   7015: has the same behaviour as some other word. Here are two situation where
                   7016: this can be useful:
1.1       anton    7017: 
1.44      crook    7018: @itemize @bullet
                   7019: @item
                   7020: When you want access to a word's definition from a different word list
                   7021: (for an example of this, see the definition of the @code{Root} word list
                   7022: in the Gforth source).
                   7023: @item
                   7024: When you want to create a synonym; a definition that can be known by
                   7025: either of two names (for example, @code{THEN} and @code{ENDIF} are
                   7026: aliases).
                   7027: @end itemize
1.1       anton    7028: 
1.69      anton    7029: Like deferred words, an alias has default compilation and interpretation
                   7030: semantics at the beginning (not the modifications of the other word),
                   7031: but you can change them in the usual ways (@code{immediate},
                   7032: @code{compile-only}). For example:
1.1       anton    7033: 
                   7034: @example
1.44      crook    7035: : foo ... ; immediate
                   7036: 
                   7037: ' foo Alias bar \ bar is not an immediate word
                   7038: ' foo Alias fooby immediate \ fooby is an immediate word
1.1       anton    7039: @end example
                   7040: 
1.44      crook    7041: Words that are aliases have the same xt, different headers in the
                   7042: dictionary, and consequently different name tokens (@pxref{Tokens for
                   7043: Words}) and possibly different immediate flags.  An alias can only have
                   7044: default or immediate compilation semantics; you can define aliases for
                   7045: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1       anton    7046: 
1.44      crook    7047: doc-alias
1.1       anton    7048: 
                   7049: 
1.47      crook    7050: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
                   7051: @section Interpretation and Compilation Semantics
1.26      crook    7052: @cindex semantics, interpretation and compilation
1.1       anton    7053: 
1.71      anton    7054: @c !! state and ' are used without explanation
                   7055: @c example for immediate/compile-only? or is the tutorial enough
                   7056: 
1.26      crook    7057: @cindex interpretation semantics
1.71      anton    7058: The @dfn{interpretation semantics} of a (named) word are what the text
1.26      crook    7059: interpreter does when it encounters the word in interpret state. It also
                   7060: appears in some other contexts, e.g., the execution token returned by
1.71      anton    7061: @code{' @i{word}} identifies the interpretation semantics of @i{word}
                   7062: (in other words, @code{' @i{word} execute} is equivalent to
1.29      crook    7063: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    7064: 
1.26      crook    7065: @cindex compilation semantics
1.71      anton    7066: The @dfn{compilation semantics} of a (named) word are what the text
                   7067: interpreter does when it encounters the word in compile state. It also
                   7068: appears in other contexts, e.g, @code{POSTPONE @i{word}}
                   7069: compiles@footnote{In standard terminology, ``appends to the current
                   7070: definition''.} the compilation semantics of @i{word}.
1.1       anton    7071: 
1.26      crook    7072: @cindex execution semantics
                   7073: The standard also talks about @dfn{execution semantics}. They are used
                   7074: only for defining the interpretation and compilation semantics of many
                   7075: words. By default, the interpretation semantics of a word are to
                   7076: @code{execute} its execution semantics, and the compilation semantics of
                   7077: a word are to @code{compile,} its execution semantics.@footnote{In
                   7078: standard terminology: The default interpretation semantics are its
                   7079: execution semantics; the default compilation semantics are to append its
                   7080: execution semantics to the execution semantics of the current
                   7081: definition.}
                   7082: 
1.71      anton    7083: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
                   7084: the text interpreter, ticked, or @code{postpone}d, so they have no
                   7085: interpretation or compilation semantics.  Their behaviour is represented
                   7086: by their XT (@pxref{Tokens for Words}), and we call it execution
                   7087: semantics, too.
                   7088: 
1.26      crook    7089: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   7090: 
                   7091: @cindex immediate words
                   7092: @cindex compile-only words
                   7093: You can change the semantics of the most-recently defined word:
                   7094: 
1.44      crook    7095: 
1.26      crook    7096: doc-immediate
                   7097: doc-compile-only
                   7098: doc-restrict
                   7099: 
1.82      anton    7100: By convention, words with non-default compilation semantics (e.g.,
                   7101: immediate words) often have names surrounded with brackets (e.g.,
                   7102: @code{[']}, @pxref{Execution token}).
1.44      crook    7103: 
1.26      crook    7104: Note that ticking (@code{'}) a compile-only word gives an error
                   7105: (``Interpreting a compile-only word'').
1.1       anton    7106: 
1.47      crook    7107: @menu
1.67      anton    7108: * Combined words::              
1.47      crook    7109: @end menu
1.44      crook    7110: 
1.71      anton    7111: 
1.48      anton    7112: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44      crook    7113: @subsection Combined Words
                   7114: @cindex combined words
                   7115: 
                   7116: Gforth allows you to define @dfn{combined words} -- words that have an
                   7117: arbitrary combination of interpretation and compilation semantics.
                   7118: 
1.26      crook    7119: doc-interpret/compile:
1.1       anton    7120: 
1.26      crook    7121: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   7122: recommend that you do not define such words, as cute as they may be:
                   7123: they make it hard to get at both parts of the word in some contexts.
                   7124: E.g., assume you want to get an execution token for the compilation
                   7125: part. Instead, define two words, one that embodies the interpretation
                   7126: part, and one that embodies the compilation part.  Once you have done
                   7127: that, you can define a combined word with @code{interpret/compile:} for
                   7128: the convenience of your users.
1.1       anton    7129: 
1.26      crook    7130: You might try to use this feature to provide an optimizing
                   7131: implementation of the default compilation semantics of a word. For
                   7132: example, by defining:
1.1       anton    7133: @example
1.26      crook    7134: :noname
                   7135:    foo bar ;
                   7136: :noname
                   7137:    POSTPONE foo POSTPONE bar ;
1.29      crook    7138: interpret/compile: opti-foobar
1.1       anton    7139: @end example
1.26      crook    7140: 
1.23      crook    7141: @noindent
1.26      crook    7142: as an optimizing version of:
                   7143: 
1.1       anton    7144: @example
1.26      crook    7145: : foobar
                   7146:     foo bar ;
1.1       anton    7147: @end example
                   7148: 
1.26      crook    7149: Unfortunately, this does not work correctly with @code{[compile]},
                   7150: because @code{[compile]} assumes that the compilation semantics of all
                   7151: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    7152: opti-foobar} would compile compilation semantics, whereas
                   7153: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    7154: 
1.26      crook    7155: @cindex state-smart words (are a bad idea)
1.82      anton    7156: @anchor{state-smartness}
1.29      crook    7157: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    7158: by @code{interpret/compile:} (words are state-smart if they check
                   7159: @code{STATE} during execution). E.g., they would try to code
                   7160: @code{foobar} like this:
1.1       anton    7161: 
1.26      crook    7162: @example
                   7163: : foobar
                   7164:   STATE @@
                   7165:   IF ( compilation state )
                   7166:     POSTPONE foo POSTPONE bar
                   7167:   ELSE
                   7168:     foo bar
                   7169:   ENDIF ; immediate
                   7170: @end example
1.1       anton    7171: 
1.26      crook    7172: Although this works if @code{foobar} is only processed by the text
                   7173: interpreter, it does not work in other contexts (like @code{'} or
                   7174: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   7175: for a state-smart word, not for the interpretation semantics of the
                   7176: original @code{foobar}; when you execute this execution token (directly
                   7177: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   7178: state, the result will not be what you expected (i.e., it will not
                   7179: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   7180: write them@footnote{For a more detailed discussion of this topic, see
1.66      anton    7181: M. Anton Ertl,
                   7182: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
                   7183: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1       anton    7184: 
1.26      crook    7185: @cindex defining words with arbitrary semantics combinations
                   7186: It is also possible to write defining words that define words with
                   7187: arbitrary combinations of interpretation and compilation semantics. In
                   7188: general, they look like this:
1.1       anton    7189: 
1.26      crook    7190: @example
                   7191: : def-word
                   7192:     create-interpret/compile
1.29      crook    7193:     @i{code1}
1.26      crook    7194: interpretation>
1.29      crook    7195:     @i{code2}
1.26      crook    7196: <interpretation
                   7197: compilation>
1.29      crook    7198:     @i{code3}
1.26      crook    7199: <compilation ;
                   7200: @end example
1.1       anton    7201: 
1.29      crook    7202: For a @i{word} defined with @code{def-word}, the interpretation
                   7203: semantics are to push the address of the body of @i{word} and perform
                   7204: @i{code2}, and the compilation semantics are to push the address of
                   7205: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    7206: can also be defined like this (except that the defined constants don't
                   7207: behave correctly when @code{[compile]}d):
1.1       anton    7208: 
1.26      crook    7209: @example
                   7210: : constant ( n "name" -- )
                   7211:     create-interpret/compile
                   7212:     ,
                   7213: interpretation> ( -- n )
                   7214:     @@
                   7215: <interpretation
                   7216: compilation> ( compilation. -- ; run-time. -- n )
                   7217:     @@ postpone literal
                   7218: <compilation ;
                   7219: @end example
1.1       anton    7220: 
1.44      crook    7221: 
1.26      crook    7222: doc-create-interpret/compile
                   7223: doc-interpretation>
                   7224: doc-<interpretation
                   7225: doc-compilation>
                   7226: doc-<compilation
1.1       anton    7227: 
1.44      crook    7228: 
1.29      crook    7229: Words defined with @code{interpret/compile:} and
1.26      crook    7230: @code{create-interpret/compile} have an extended header structure that
                   7231: differs from other words; however, unless you try to access them with
                   7232: plain address arithmetic, you should not notice this. Words for
                   7233: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    7234: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   7235: with @code{create-interpret/compile}.
1.1       anton    7236: 
1.44      crook    7237: 
1.47      crook    7238: @c -------------------------------------------------------------
1.81      anton    7239: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47      crook    7240: @section Tokens for Words
                   7241: @cindex tokens for words
                   7242: 
                   7243: This section describes the creation and use of tokens that represent
                   7244: words.
                   7245: 
1.71      anton    7246: @menu
                   7247: * Execution token::             represents execution/interpretation semantics
                   7248: * Compilation token::           represents compilation semantics
                   7249: * Name token::                  represents named words
                   7250: @end menu
1.47      crook    7251: 
1.71      anton    7252: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
                   7253: @subsection Execution token
1.47      crook    7254: 
                   7255: @cindex xt
                   7256: @cindex execution token
1.71      anton    7257: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
                   7258: You can use @code{execute} to invoke this behaviour.
1.47      crook    7259: 
1.71      anton    7260: @cindex tick (')
                   7261: You can use @code{'} to get an execution token that represents the
                   7262: interpretation semantics of a named word:
1.47      crook    7263: 
                   7264: @example
1.97      anton    7265: 5 ' .   ( n xt ) 
                   7266: execute ( )      \ execute the xt (i.e., ".")
1.71      anton    7267: @end example
1.47      crook    7268: 
1.71      anton    7269: doc-'
                   7270: 
                   7271: @code{'} parses at run-time; there is also a word @code{[']} that parses
                   7272: when it is compiled, and compiles the resulting XT:
                   7273: 
                   7274: @example
                   7275: : foo ['] . execute ;
                   7276: 5 foo
                   7277: : bar ' execute ; \ by contrast,
                   7278: 5 bar .           \ ' parses "." when bar executes
                   7279: @end example
                   7280: 
                   7281: doc-[']
                   7282: 
                   7283: If you want the execution token of @i{word}, write @code{['] @i{word}}
                   7284: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
                   7285: @code{'} and @code{[']} behave somewhat unusually by complaining about
                   7286: compile-only words (because these words have no interpretation
                   7287: semantics).  You might get what you want by using @code{COMP' @i{word}
                   7288: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
                   7289: token}).
                   7290: 
1.116     anton    7291: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71      anton    7292: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
                   7293: for the only behaviour the word has (the execution semantics).  For
1.116     anton    7294: named words, @code{latestxt} produces an XT for the same behaviour it
1.71      anton    7295: would produce if the word was defined anonymously.
                   7296: 
                   7297: @example
                   7298: :noname ." hello" ;
                   7299: execute
1.47      crook    7300: @end example
                   7301: 
1.71      anton    7302: An XT occupies one cell and can be manipulated like any other cell.
                   7303: 
1.47      crook    7304: @cindex code field address
                   7305: @cindex CFA
1.71      anton    7306: In ANS Forth the XT is just an abstract data type (i.e., defined by the
                   7307: operations that produce or consume it).  For old hands: In Gforth, the
                   7308: XT is implemented as a code field address (CFA).
                   7309: 
                   7310: doc-execute
                   7311: doc-perform
                   7312: 
                   7313: @node Compilation token, Name token, Execution token, Tokens for Words
                   7314: @subsection Compilation token
1.47      crook    7315: 
                   7316: @cindex compilation token
1.71      anton    7317: @cindex CT (compilation token)
                   7318: Gforth represents the compilation semantics of a named word by a
1.47      crook    7319: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   7320: @i{xt} is an execution token. The compilation semantics represented by
                   7321: the compilation token can be performed with @code{execute}, which
                   7322: consumes the whole compilation token, with an additional stack effect
                   7323: determined by the represented compilation semantics.
                   7324: 
                   7325: At present, the @i{w} part of a compilation token is an execution token,
                   7326: and the @i{xt} part represents either @code{execute} or
                   7327: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   7328: word. If the word has default compilation semantics, the @i{xt} will
                   7329: represent @code{compile,}. Otherwise (e.g., for immediate words), the
                   7330: @i{xt} will represent @code{execute}.}. However, don't rely on that
                   7331: knowledge, unless necessary; future versions of Gforth may introduce
                   7332: unusual compilation tokens (e.g., a compilation token that represents
                   7333: the compilation semantics of a literal).
                   7334: 
1.71      anton    7335: You can perform the compilation semantics represented by the compilation
                   7336: token with @code{execute}.  You can compile the compilation semantics
                   7337: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
                   7338: equivalent to @code{postpone @i{word}}.
                   7339: 
                   7340: doc-[comp']
                   7341: doc-comp'
                   7342: doc-postpone,
                   7343: 
                   7344: @node Name token,  , Compilation token, Tokens for Words
                   7345: @subsection Name token
1.47      crook    7346: 
                   7347: @cindex name token
1.116     anton    7348: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
                   7349: token is an abstract data type that occurs as argument or result of the
                   7350: words below.
                   7351: 
                   7352: @c !! put this elswhere?
1.47      crook    7353: @cindex name field address
                   7354: @cindex NFA
1.116     anton    7355: The closest thing to the nt in older Forth systems is the name field
                   7356: address (NFA), but there are significant differences: in older Forth
                   7357: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
                   7358: LFA, NFA, CFA, PFA) and there were words for getting from one to the
                   7359: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
                   7360: is a link field in the structure identified by the name token, but
                   7361: searching usually uses a hash table external to these structures; the
                   7362: name in Gforth has a cell-wide count-and-flags field, and the nt is not
                   7363: implemented as the address of that count field.
1.47      crook    7364: 
                   7365: doc-find-name
1.116     anton    7366: doc-latest
                   7367: doc->name
1.47      crook    7368: doc-name>int
                   7369: doc-name?int
                   7370: doc-name>comp
                   7371: doc-name>string
1.109     anton    7372: doc-id.
                   7373: doc-.name
                   7374: doc-.id
1.47      crook    7375: 
1.81      anton    7376: @c ----------------------------------------------------------
                   7377: @node Compiling words, The Text Interpreter, Tokens for Words, Words
                   7378: @section Compiling words
                   7379: @cindex compiling words
                   7380: @cindex macros
                   7381: 
                   7382: In contrast to most other languages, Forth has no strict boundary
1.82      anton    7383: between compilation and run-time.  E.g., you can run arbitrary code
                   7384: between defining words (or for computing data used by defining words
                   7385: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
                   7386: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
                   7387: running arbitrary code while compiling a colon definition (exception:
                   7388: you must not allot dictionary space).
                   7389: 
                   7390: @menu
                   7391: * Literals::                    Compiling data values
                   7392: * Macros::                      Compiling words
                   7393: @end menu
                   7394: 
                   7395: @node Literals, Macros, Compiling words, Compiling words
                   7396: @subsection Literals
                   7397: @cindex Literals
                   7398: 
                   7399: The simplest and most frequent example is to compute a literal during
                   7400: compilation.  E.g., the following definition prints an array of strings,
                   7401: one string per line:
                   7402: 
                   7403: @example
                   7404: : .strings ( addr u -- ) \ gforth
                   7405:     2* cells bounds U+DO
                   7406:        cr i 2@@ type
                   7407:     2 cells +LOOP ;  
                   7408: @end example
1.81      anton    7409: 
1.82      anton    7410: With a simple-minded compiler like Gforth's, this computes @code{2
                   7411: cells} on every loop iteration.  You can compute this value once and for
                   7412: all at compile time and compile it into the definition like this:
                   7413: 
                   7414: @example
                   7415: : .strings ( addr u -- ) \ gforth
                   7416:     2* cells bounds U+DO
                   7417:        cr i 2@@ type
                   7418:     [ 2 cells ] literal +LOOP ;  
                   7419: @end example
                   7420: 
                   7421: @code{[} switches the text interpreter to interpret state (you will get
                   7422: an @code{ok} prompt if you type this example interactively and insert a
                   7423: newline between @code{[} and @code{]}), so it performs the
                   7424: interpretation semantics of @code{2 cells}; this computes a number.
                   7425: @code{]} switches the text interpreter back into compile state.  It then
                   7426: performs @code{Literal}'s compilation semantics, which are to compile
                   7427: this number into the current word.  You can decompile the word with
                   7428: @code{see .strings} to see the effect on the compiled code.
1.81      anton    7429: 
1.82      anton    7430: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
                   7431: *} in this way.
1.81      anton    7432: 
1.82      anton    7433: doc-[
                   7434: doc-]
1.81      anton    7435: doc-literal
                   7436: doc-]L
1.82      anton    7437: 
                   7438: There are also words for compiling other data types than single cells as
                   7439: literals:
                   7440: 
1.81      anton    7441: doc-2literal
                   7442: doc-fliteral
1.82      anton    7443: doc-sliteral
                   7444: 
                   7445: @cindex colon-sys, passing data across @code{:}
                   7446: @cindex @code{:}, passing data across
                   7447: You might be tempted to pass data from outside a colon definition to the
                   7448: inside on the data stack.  This does not work, because @code{:} puhes a
                   7449: colon-sys, making stuff below unaccessible.  E.g., this does not work:
                   7450: 
                   7451: @example
                   7452: 5 : foo literal ; \ error: "unstructured"
                   7453: @end example
                   7454: 
                   7455: Instead, you have to pass the value in some other way, e.g., through a
                   7456: variable:
                   7457: 
                   7458: @example
                   7459: variable temp
                   7460: 5 temp !
                   7461: : foo [ temp @@ ] literal ;
                   7462: @end example
                   7463: 
                   7464: 
                   7465: @node Macros,  , Literals, Compiling words
                   7466: @subsection Macros
                   7467: @cindex Macros
                   7468: @cindex compiling compilation semantics
                   7469: 
                   7470: @code{Literal} and friends compile data values into the current
                   7471: definition.  You can also write words that compile other words into the
                   7472: current definition.  E.g.,
                   7473: 
                   7474: @example
                   7475: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
                   7476:   POSTPONE + ;
                   7477: 
                   7478: : foo ( n1 n2 -- n )
                   7479:   [ compile-+ ] ;
                   7480: 1 2 foo .
                   7481: @end example
                   7482: 
                   7483: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
                   7484: What happens in this example?  @code{Postpone} compiles the compilation
                   7485: semantics of @code{+} into @code{compile-+}; later the text interpreter
                   7486: executes @code{compile-+} and thus the compilation semantics of +, which
                   7487: compile (the execution semantics of) @code{+} into
                   7488: @code{foo}.@footnote{A recent RFI answer requires that compiling words
                   7489: should only be executed in compile state, so this example is not
                   7490: guaranteed to work on all standard systems, but on any decent system it
                   7491: will work.}
                   7492: 
                   7493: doc-postpone
                   7494: 
                   7495: Compiling words like @code{compile-+} are usually immediate (or similar)
                   7496: so you do not have to switch to interpret state to execute them;
1.206     anton    7497: modifying the last example accordingly produces:
1.82      anton    7498: 
                   7499: @example
                   7500: : [compile-+] ( compilation: --; interpretation: -- )
                   7501:   \ compiled code: ( n1 n2 -- n )
                   7502:   POSTPONE + ; immediate
                   7503: 
                   7504: : foo ( n1 n2 -- n )
                   7505:   [compile-+] ;
                   7506: 1 2 foo .
                   7507: @end example
                   7508: 
1.206     anton    7509: You will occassionally find the need to POSTPONE several words;
                   7510: putting POSTPONE before each such word is cumbersome, so Gforth
                   7511: provides a more convenient syntax: @code{]] ... [[}.  This
                   7512: allows us to write @code{[compile-+]} as:
                   7513: 
                   7514: @example
                   7515: : [compile-+] ( compilation: --; interpretation: -- )
                   7516:   ]] + [[ ; immediate
                   7517: @end example
                   7518: 
                   7519: doc-]]
                   7520: doc-[[
                   7521: 
                   7522: The unusual direction of the brackets indicates their function:
                   7523: @code{]]} switches from compilation to postponing (i.e., compilation
                   7524: of compilation), just like @code{]} switches from immediate execution
                   7525: (interpretation) to compilation.  Conversely, @code{[[} switches from
                   7526: postponing to compilation, ananlogous to @code{[} which switches from
                   7527: compilation to immediate execution.
                   7528: 
                   7529: The real advantage of @code{]] }...@code{ [[} becomes apparent when
                   7530: there are many words to POSTPONE.  E.g., the word
                   7531: @code{compile-map-array} (@pxref{Advanced macros Tutorial}) can be
                   7532: written much shorter as follows:
                   7533: 
                   7534: @example
                   7535: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
                   7536: \ at run-time, execute xt ( ... x -- ... ) for each element of the
                   7537: \ array beginning at addr and containing u elements
                   7538:   @{ xt @}
                   7539:   ]] cells over + swap ?do
                   7540:     i @@ [[ xt compile, 
                   7541:   1 cells ]]L +loop [[ ;
                   7542: @end example
                   7543: 
                   7544: This example also uses @code{]]L} as a shortcut for @code{]] literal}.
                   7545: There are also other shortcuts
                   7546: 
                   7547: doc-]]L
                   7548: doc-]]2L
                   7549: doc-]]FL
                   7550: doc-]]SL
                   7551: 
                   7552: Note that parsing words don't parse at postpone time; if you want to
                   7553: provide the parsed string right away, you have to switch back to
                   7554: compilation:
                   7555: 
                   7556: @example
                   7557: ]] ... [[ s" some string" ]]2L ... [[
                   7558: ]] ... [[ ['] + ]]L ... [[
                   7559: @end example
                   7560: 
                   7561: Definitions of @code{]]} and friends in ANS Forth are provided in
                   7562: @file{compat/macros.fs}.
                   7563: 
1.82      anton    7564: Immediate compiling words are similar to macros in other languages (in
                   7565: particular, Lisp).  The important differences to macros in, e.g., C are:
                   7566: 
                   7567: @itemize @bullet
                   7568: 
                   7569: @item
                   7570: You use the same language for defining and processing macros, not a
                   7571: separate preprocessing language and processor.
                   7572: 
                   7573: @item
                   7574: Consequently, the full power of Forth is available in macro definitions.
                   7575: E.g., you can perform arbitrarily complex computations, or generate
                   7576: different code conditionally or in a loop (e.g., @pxref{Advanced macros
                   7577: Tutorial}).  This power is very useful when writing a parser generators
                   7578: or other code-generating software.
                   7579: 
                   7580: @item
                   7581: Macros defined using @code{postpone} etc. deal with the language at a
                   7582: higher level than strings; name binding happens at macro definition
                   7583: time, so you can avoid the pitfalls of name collisions that can happen
                   7584: in C macros.  Of course, Forth is a liberal language and also allows to
                   7585: shoot yourself in the foot with text-interpreted macros like
                   7586: 
                   7587: @example
                   7588: : [compile-+] s" +" evaluate ; immediate
                   7589: @end example
                   7590: 
                   7591: Apart from binding the name at macro use time, using @code{evaluate}
                   7592: also makes your definition @code{state}-smart (@pxref{state-smartness}).
                   7593: @end itemize
                   7594: 
                   7595: You may want the macro to compile a number into a word.  The word to do
                   7596: it is @code{literal}, but you have to @code{postpone} it, so its
                   7597: compilation semantics take effect when the macro is executed, not when
                   7598: it is compiled:
                   7599: 
                   7600: @example
                   7601: : [compile-5] ( -- ) \ compiled code: ( -- n )
                   7602:   5 POSTPONE literal ; immediate
                   7603: 
                   7604: : foo [compile-5] ;
                   7605: foo .
                   7606: @end example
                   7607: 
                   7608: You may want to pass parameters to a macro, that the macro should
                   7609: compile into the current definition.  If the parameter is a number, then
                   7610: you can use @code{postpone literal} (similar for other values).
                   7611: 
                   7612: If you want to pass a word that is to be compiled, the usual way is to
                   7613: pass an execution token and @code{compile,} it:
                   7614: 
                   7615: @example
                   7616: : twice1 ( xt -- ) \ compiled code: ... -- ...
                   7617:   dup compile, compile, ;
                   7618: 
                   7619: : 2+ ( n1 -- n2 )
                   7620:   [ ' 1+ twice1 ] ;
                   7621: @end example
                   7622: 
                   7623: doc-compile,
                   7624: 
                   7625: An alternative available in Gforth, that allows you to pass compile-only
                   7626: words as parameters is to use the compilation token (@pxref{Compilation
                   7627: token}).  The same example in this technique:
                   7628: 
                   7629: @example
                   7630: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
                   7631:   2dup 2>r execute 2r> execute ;
                   7632: 
                   7633: : 2+ ( n1 -- n2 )
                   7634:   [ comp' 1+ twice ] ;
                   7635: @end example
                   7636: 
                   7637: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
                   7638: works even if the executed compilation semantics has an effect on the
                   7639: data stack.
                   7640: 
                   7641: You can also define complete definitions with these words; this provides
                   7642: an alternative to using @code{does>} (@pxref{User-defined Defining
                   7643: Words}).  E.g., instead of
                   7644: 
                   7645: @example
                   7646: : curry+ ( n1 "name" -- )
                   7647:     CREATE ,
                   7648: DOES> ( n2 -- n1+n2 )
                   7649:     @@ + ;
                   7650: @end example
                   7651: 
                   7652: you could define
                   7653: 
                   7654: @example
                   7655: : curry+ ( n1 "name" -- )
                   7656:   \ name execution: ( n2 -- n1+n2 )
                   7657:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81      anton    7658: 
1.82      anton    7659: -3 curry+ 3-
                   7660: see 3-
                   7661: @end example
1.81      anton    7662: 
1.82      anton    7663: The sequence @code{>r : r>} is necessary, because @code{:} puts a
                   7664: colon-sys on the data stack that makes everything below it unaccessible.
1.81      anton    7665: 
1.82      anton    7666: This way of writing defining words is sometimes more, sometimes less
                   7667: convenient than using @code{does>} (@pxref{Advanced does> usage
                   7668: example}).  One advantage of this method is that it can be optimized
                   7669: better, because the compiler knows that the value compiled with
                   7670: @code{literal} is fixed, whereas the data associated with a
                   7671: @code{create}d word can be changed.
1.47      crook    7672: 
1.206     anton    7673: @c doc-[compile] !! not properly documented
                   7674: 
1.26      crook    7675: @c ----------------------------------------------------------
1.111     anton    7676: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26      crook    7677: @section  The Text Interpreter
                   7678: @cindex interpreter - outer
                   7679: @cindex text interpreter
                   7680: @cindex outer interpreter
1.1       anton    7681: 
1.34      anton    7682: @c Should we really describe all these ugly details?  IMO the text
                   7683: @c interpreter should be much cleaner, but that may not be possible within
                   7684: @c ANS Forth. - anton
1.44      crook    7685: @c nac-> I wanted to explain how it works to show how you can exploit
                   7686: @c it in your own programs. When I was writing a cross-compiler, figuring out
                   7687: @c some of these gory details was very helpful to me. None of the textbooks
                   7688: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
                   7689: @c seems to positively avoid going into too much detail for some of
                   7690: @c the internals.
1.34      anton    7691: 
1.71      anton    7692: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
                   7693: @c it is; for the ugly details, I would prefer another place.  I wonder
                   7694: @c whether we should have a chapter before "Words" that describes some
                   7695: @c basic concepts referred to in words, and a chapter after "Words" that
                   7696: @c describes implementation details.
                   7697: 
1.29      crook    7698: The text interpreter@footnote{This is an expanded version of the
                   7699: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34      anton    7700: that processes input from the current input device. It is also called
                   7701: the outer interpreter, in contrast to the inner interpreter
                   7702: (@pxref{Engine}) which executes the compiled Forth code on interpretive
                   7703: implementations.
1.27      crook    7704: 
1.29      crook    7705: @cindex interpret state
                   7706: @cindex compile state
                   7707: The text interpreter operates in one of two states: @dfn{interpret
                   7708: state} and @dfn{compile state}. The current state is defined by the
1.71      anton    7709: aptly-named variable @code{state}.
1.29      crook    7710: 
                   7711: This section starts by describing how the text interpreter behaves when
                   7712: it is in interpret state, processing input from the user input device --
                   7713: the keyboard. This is the mode that a Forth system is in after it starts
                   7714: up.
                   7715: 
                   7716: @cindex input buffer
                   7717: @cindex terminal input buffer
                   7718: The text interpreter works from an area of memory called the @dfn{input
                   7719: buffer}@footnote{When the text interpreter is processing input from the
                   7720: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   7721: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   7722: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    7723: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    7724: leading spaces (called @dfn{delimiters}) then parses a string (a
                   7725: sequence of non-space characters) until it reaches either a space
                   7726: character or the end of the buffer. Having parsed a string, it makes two
                   7727: attempts to process it:
1.27      crook    7728: 
1.29      crook    7729: @cindex dictionary
1.27      crook    7730: @itemize @bullet
                   7731: @item
1.29      crook    7732: It looks for the string in a @dfn{dictionary} of definitions. If the
                   7733: string is found, the string names a @dfn{definition} (also known as a
                   7734: @dfn{word}) and the dictionary search returns information that allows
                   7735: the text interpreter to perform the word's @dfn{interpretation
                   7736: semantics}. In most cases, this simply means that the word will be
                   7737: executed.
1.27      crook    7738: @item
                   7739: If the string is not found in the dictionary, the text interpreter
1.29      crook    7740: attempts to treat it as a number, using the rules described in
                   7741: @ref{Number Conversion}. If the string represents a legal number in the
                   7742: current radix, the number is pushed onto a parameter stack (the data
                   7743: stack for integers, the floating-point stack for floating-point
                   7744: numbers).
                   7745: @end itemize
                   7746: 
                   7747: If both attempts fail, or if the word is found in the dictionary but has
                   7748: no interpretation semantics@footnote{This happens if the word was
                   7749: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   7750: remainder of the input buffer, issues an error message and waits for
                   7751: more input. If one of the attempts succeeds, the text interpreter
                   7752: repeats the parsing process until the whole of the input buffer has been
                   7753: processed, at which point it prints the status message ``@code{ ok}''
                   7754: and waits for more input.
                   7755: 
1.71      anton    7756: @c anton: this should be in the input stream subsection (or below it)
                   7757: 
1.29      crook    7758: @cindex parse area
                   7759: The text interpreter keeps track of its position in the input buffer by
                   7760: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   7761: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   7762: of the input buffer. The region from offset @code{>IN @@} to the end of
                   7763: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   7764: the text interpreter processes the contents of the input buffer by
                   7765: parsing strings from the parse area until the parse area is empty.}.
                   7766: This example shows how @code{>IN} changes as the text interpreter parses
                   7767: the input buffer:
                   7768: 
                   7769: @example
                   7770: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   7771:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   7772: 
                   7773: 1 2 3 remaining + remaining . 
                   7774: 
                   7775: : foo 1 2 3 remaining SWAP remaining ;
                   7776: @end example
                   7777: 
                   7778: @noindent
                   7779: The result is:
                   7780: 
                   7781: @example
                   7782: ->+ remaining .<-
                   7783: ->.<-5  ok
                   7784: 
                   7785: ->SWAP remaining ;-<
                   7786: ->;<-  ok
                   7787: @end example
                   7788: 
                   7789: @cindex parsing words
                   7790: The value of @code{>IN} can also be modified by a word in the input
                   7791: buffer that is executed by the text interpreter.  This means that a word
                   7792: can ``trick'' the text interpreter into either skipping a section of the
                   7793: input buffer@footnote{This is how parsing words work.} or into parsing a
                   7794: section twice. For example:
1.27      crook    7795: 
1.29      crook    7796: @example
1.71      anton    7797: : lat ." <<foo>>" ;
                   7798: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29      crook    7799: @end example
                   7800: 
                   7801: @noindent
                   7802: When @code{flat} is executed, this output is produced@footnote{Exercise
                   7803: for the reader: what would happen if the @code{3} were replaced with
                   7804: @code{4}?}:
                   7805: 
                   7806: @example
1.71      anton    7807: <<bar>><<foo>>
1.29      crook    7808: @end example
                   7809: 
1.71      anton    7810: This technique can be used to work around some of the interoperability
                   7811: problems of parsing words.  Of course, it's better to avoid parsing
                   7812: words where possible.
                   7813: 
1.29      crook    7814: @noindent
                   7815: Two important notes about the behaviour of the text interpreter:
1.27      crook    7816: 
                   7817: @itemize @bullet
                   7818: @item
                   7819: It processes each input string to completion before parsing additional
1.29      crook    7820: characters from the input buffer.
                   7821: @item
                   7822: It treats the input buffer as a read-only region (and so must your code).
                   7823: @end itemize
                   7824: 
                   7825: @noindent
                   7826: When the text interpreter is in compile state, its behaviour changes in
                   7827: these ways:
                   7828: 
                   7829: @itemize @bullet
                   7830: @item
                   7831: If a parsed string is found in the dictionary, the text interpreter will
                   7832: perform the word's @dfn{compilation semantics}. In most cases, this
                   7833: simply means that the execution semantics of the word will be appended
                   7834: to the current definition.
1.27      crook    7835: @item
1.29      crook    7836: When a number is encountered, it is compiled into the current definition
                   7837: (as a literal) rather than being pushed onto a parameter stack.
                   7838: @item
                   7839: If an error occurs, @code{state} is modified to put the text interpreter
                   7840: back into interpret state.
                   7841: @item
                   7842: Each time a line is entered from the keyboard, Gforth prints
                   7843: ``@code{ compiled}'' rather than `` @code{ok}''.
                   7844: @end itemize
                   7845: 
                   7846: @cindex text interpreter - input sources
                   7847: When the text interpreter is using an input device other than the
                   7848: keyboard, its behaviour changes in these ways:
                   7849: 
                   7850: @itemize @bullet
                   7851: @item
                   7852: When the parse area is empty, the text interpreter attempts to refill
                   7853: the input buffer from the input source. When the input source is
1.71      anton    7854: exhausted, the input source is set back to the previous input source.
1.29      crook    7855: @item
                   7856: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   7857: time the parse area is emptied.
                   7858: @item
                   7859: If an error occurs, the input source is set back to the user input
                   7860: device.
1.27      crook    7861: @end itemize
1.21      crook    7862: 
1.49      anton    7863: You can read about this in more detail in @ref{Input Sources}.
1.44      crook    7864: 
1.26      crook    7865: doc->in
1.27      crook    7866: doc-source
                   7867: 
1.26      crook    7868: doc-tib
                   7869: doc-#tib
1.1       anton    7870: 
1.44      crook    7871: 
1.26      crook    7872: @menu
1.67      anton    7873: * Input Sources::               
                   7874: * Number Conversion::           
                   7875: * Interpret/Compile states::    
                   7876: * Interpreter Directives::      
1.26      crook    7877: @end menu
1.1       anton    7878: 
1.29      crook    7879: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   7880: @subsection Input Sources
                   7881: @cindex input sources
                   7882: @cindex text interpreter - input sources
                   7883: 
1.44      crook    7884: By default, the text interpreter processes input from the user input
1.29      crook    7885: device (the keyboard) when Forth starts up. The text interpreter can
                   7886: process input from any of these sources:
                   7887: 
                   7888: @itemize @bullet
                   7889: @item
                   7890: The user input device -- the keyboard.
                   7891: @item
                   7892: A file, using the words described in @ref{Forth source files}.
                   7893: @item
                   7894: A block, using the words described in @ref{Blocks}.
                   7895: @item
                   7896: A text string, using @code{evaluate}.
                   7897: @end itemize
                   7898: 
                   7899: A program can identify the current input device from the values of
                   7900: @code{source-id} and @code{blk}.
                   7901: 
1.44      crook    7902: 
1.29      crook    7903: doc-source-id
                   7904: doc-blk
                   7905: 
                   7906: doc-save-input
                   7907: doc-restore-input
                   7908: 
                   7909: doc-evaluate
1.111     anton    7910: doc-query
1.1       anton    7911: 
1.29      crook    7912: 
1.44      crook    7913: 
1.29      crook    7914: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    7915: @subsection Number Conversion
                   7916: @cindex number conversion
                   7917: @cindex double-cell numbers, input format
                   7918: @cindex input format for double-cell numbers
                   7919: @cindex single-cell numbers, input format
                   7920: @cindex input format for single-cell numbers
                   7921: @cindex floating-point numbers, input format
                   7922: @cindex input format for floating-point numbers
1.1       anton    7923: 
1.29      crook    7924: This section describes the rules that the text interpreter uses when it
                   7925: tries to convert a string into a number.
1.1       anton    7926: 
1.26      crook    7927: Let <digit> represent any character that is a legal digit in the current
1.29      crook    7928: number base@footnote{For example, 0-9 when the number base is decimal or
                   7929: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    7930: 
1.26      crook    7931: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    7932: 
1.29      crook    7933: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   7934: in the braces (@i{a} or @i{b} or neither).
1.1       anton    7935: 
1.26      crook    7936: Let * represent any number of instances of the previous character
                   7937: (including none).
1.1       anton    7938: 
1.26      crook    7939: Let any other character represent itself.
1.1       anton    7940: 
1.29      crook    7941: @noindent
1.26      crook    7942: Now, the conversion rules are:
1.21      crook    7943: 
1.26      crook    7944: @itemize @bullet
                   7945: @item
                   7946: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    7947: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    7948: @item
                   7949: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    7950: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    7951: arithmetic. Examples are -45 -5681 -0
                   7952: @item
                   7953: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    7954: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   7955: (all three of these represent the same number).
1.26      crook    7956: @item
                   7957: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    7958: double-precision (double-cell-sized) negative integer, and is
1.26      crook    7959: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    7960: -34.65 (all three of these represent the same number).
1.26      crook    7961: @item
1.29      crook    7962: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   7963: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35      anton    7964: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    7965: number) +12.E-4
1.26      crook    7966: @end itemize
1.1       anton    7967: 
1.174     anton    7968: By default, the number base used for integer number conversion is
                   7969: given by the contents of the variable @code{base}.  Note that a lot of
1.35      anton    7970: confusion can result from unexpected values of @code{base}.  If you
1.174     anton    7971: change @code{base} anywhere, make sure to save the old value and
                   7972: restore it afterwards; better yet, use @code{base-execute}, which does
                   7973: this for you.  In general I recommend keeping @code{base} decimal, and
1.35      anton    7974: using the prefixes described below for the popular non-decimal bases.
1.1       anton    7975: 
1.29      crook    7976: doc-dpl
1.174     anton    7977: doc-base-execute
1.26      crook    7978: doc-base
                   7979: doc-hex
                   7980: doc-decimal
1.1       anton    7981: 
1.26      crook    7982: @cindex '-prefix for character strings
                   7983: @cindex &-prefix for decimal numbers
1.133     anton    7984: @cindex #-prefix for decimal numbers
1.26      crook    7985: @cindex %-prefix for binary numbers
                   7986: @cindex $-prefix for hexadecimal numbers
1.133     anton    7987: @cindex 0x-prefix for hexadecimal numbers
1.35      anton    7988: Gforth allows you to override the value of @code{base} by using a
1.29      crook    7989: prefix@footnote{Some Forth implementations provide a similar scheme by
                   7990: implementing @code{$} etc. as parsing words that process the subsequent
                   7991: number in the input stream and push it onto the stack. For example, see
                   7992: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   7993: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   7994: is required between the prefix and the number.} before the first digit
1.133     anton    7995: of an (integer) number. The following prefixes are supported:
1.1       anton    7996: 
1.26      crook    7997: @itemize @bullet
                   7998: @item
1.35      anton    7999: @code{&} -- decimal
1.26      crook    8000: @item
1.133     anton    8001: @code{#} -- decimal
                   8002: @item
1.35      anton    8003: @code{%} -- binary
1.26      crook    8004: @item
1.35      anton    8005: @code{$} -- hexadecimal
1.26      crook    8006: @item
1.133     anton    8007: @code{0x} -- hexadecimal, if base<33.
                   8008: @item
                   8009: @code{'} -- numeric value (e.g., ASCII code) of next character; an
                   8010: optional @code{'} may be present after the character.
1.26      crook    8011: @end itemize
1.1       anton    8012: 
1.26      crook    8013: Here are some examples, with the equivalent decimal number shown after
                   8014: in braces:
1.1       anton    8015: 
1.26      crook    8016: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133     anton    8017: 'A (65),
                   8018: -'a' (-97),
1.26      crook    8019: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    8020: 
1.26      crook    8021: @cindex number conversion - traps for the unwary
1.29      crook    8022: @noindent
1.26      crook    8023: Number conversion has a number of traps for the unwary:
1.1       anton    8024: 
1.26      crook    8025: @itemize @bullet
                   8026: @item
                   8027: You cannot determine the current number base using the code sequence
1.35      anton    8028: @code{base @@ .} -- the number base is always 10 in the current number
                   8029: base. Instead, use something like @code{base @@ dec.}
1.26      crook    8030: @item
                   8031: If the number base is set to a value greater than 14 (for example,
                   8032: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   8033: it to be intepreted as either a single-precision integer or a
                   8034: floating-point number (Gforth treats it as an integer). The ambiguity
                   8035: can be resolved by explicitly stating the sign of the mantissa and/or
                   8036: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   8037: ambiguity arises; either representation will be treated as a
                   8038: floating-point number.
                   8039: @item
1.29      crook    8040: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    8041: It is used to specify file types.
                   8042: @item
1.72      anton    8043: ANS Forth requires the @code{.} of a double-precision number to be the
                   8044: final character in the string.  Gforth allows the @code{.} to be
                   8045: anywhere after the first digit.
1.26      crook    8046: @item
                   8047: The number conversion process does not check for overflow.
                   8048: @item
1.72      anton    8049: In an ANS Forth program @code{base} is required to be decimal when
                   8050: converting floating-point numbers.  In Gforth, number conversion to
                   8051: floating-point numbers always uses base &10, irrespective of the value
                   8052: of @code{base}.
1.26      crook    8053: @end itemize
1.1       anton    8054: 
1.49      anton    8055: You can read numbers into your programs with the words described in
1.181     anton    8056: @ref{Line input and conversion}.
1.1       anton    8057: 
1.82      anton    8058: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26      crook    8059: @subsection Interpret/Compile states
                   8060: @cindex Interpret/Compile states
1.1       anton    8061: 
1.29      crook    8062: A standard program is not permitted to change @code{state}
                   8063: explicitly. However, it can change @code{state} implicitly, using the
                   8064: words @code{[} and @code{]}. When @code{[} is executed it switches
                   8065: @code{state} to interpret state, and therefore the text interpreter
                   8066: starts interpreting. When @code{]} is executed it switches @code{state}
                   8067: to compile state and therefore the text interpreter starts
1.44      crook    8068: compiling. The most common usage for these words is for switching into
                   8069: interpret state and back from within a colon definition; this technique
1.49      anton    8070: can be used to compile a literal (for an example, @pxref{Literals}) or
                   8071: for conditional compilation (for an example, @pxref{Interpreter
                   8072: Directives}).
1.44      crook    8073: 
1.35      anton    8074: 
                   8075: @c This is a bad example: It's non-standard, and it's not necessary.
                   8076: @c However, I can't think of a good example for switching into compile
                   8077: @c state when there is no current word (@code{state}-smart words are not a
                   8078: @c good reason).  So maybe we should use an example for switching into
                   8079: @c interpret @code{state} in a colon def. - anton
1.44      crook    8080: @c nac-> I agree. I started out by putting in the example, then realised
                   8081: @c that it was non-ANS, so wrote more words around it. I hope this
                   8082: @c re-written version is acceptable to you. I do want to keep the example
                   8083: @c as it is helpful for showing what is and what is not portable, particularly
                   8084: @c where it outlaws a style in common use.
                   8085: 
1.72      anton    8086: @c anton: it's more important to show what's portable.  After we have done
1.83      anton    8087: @c that, we can also show what's not.  In any case, I have written a
                   8088: @c section Compiling Words which also deals with [ ].
1.35      anton    8089: 
1.95      anton    8090: @c  !! The following example does not work in Gforth 0.5.9 or later.
1.29      crook    8091: 
1.95      anton    8092: @c  @code{[} and @code{]} also give you the ability to switch into compile
                   8093: @c  state and back, but we cannot think of any useful Standard application
                   8094: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
                   8095: 
                   8096: @c  @example
                   8097: @c  : AA ." this is A" ;
                   8098: @c  : BB ." this is B" ;
                   8099: @c  : CC ." this is C" ;
                   8100: 
                   8101: @c  create table ] aa bb cc [
                   8102: 
                   8103: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   8104: @c    cells table + @@ execute ;
                   8105: @c  @end example
                   8106: 
                   8107: @c  This example builds a jump table; @code{0 go} will display ``@code{this
                   8108: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
                   8109: @c  defining @code{table} like this:
                   8110: 
                   8111: @c  @example
                   8112: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
                   8113: @c  @end example
                   8114: 
                   8115: @c  The problem with this code is that the definition of @code{table} is not
                   8116: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
                   8117: @c  @i{may} work on systems where code space and data space co-incide, the
                   8118: @c  Standard only allows data space to be assigned for a @code{CREATE}d
                   8119: @c  word. In addition, the Standard only allows @code{@@} to access data
                   8120: @c  space, whilst this example is using it to access code space. The only
                   8121: @c  portable, Standard way to build this table is to build it in data space,
                   8122: @c  like this:
                   8123: 
                   8124: @c  @example
                   8125: @c  create table ' aa , ' bb , ' cc ,
                   8126: @c  @end example
1.29      crook    8127: 
1.95      anton    8128: @c  doc-state
1.44      crook    8129: 
1.29      crook    8130: 
1.82      anton    8131: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
1.26      crook    8132: @subsection Interpreter Directives
                   8133: @cindex interpreter directives
1.72      anton    8134: @cindex conditional compilation
1.1       anton    8135: 
1.29      crook    8136: These words are usually used in interpret state; typically to control
                   8137: which parts of a source file are processed by the text
1.26      crook    8138: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   8139: supplements these with a rich set of immediate control structure words
                   8140: to compensate for the fact that the non-immediate versions can only be
1.29      crook    8141: used in compile state (@pxref{Control Structures}). Typical usages:
                   8142: 
                   8143: @example
1.72      anton    8144: FALSE Constant HAVE-ASSEMBLER
1.29      crook    8145: .
                   8146: .
1.72      anton    8147: HAVE-ASSEMBLER [IF]
1.29      crook    8148: : ASSEMBLER-FEATURE
                   8149:   ...
                   8150: ;
                   8151: [ENDIF]
                   8152: .
                   8153: .
                   8154: : SEE
                   8155:   ... \ general-purpose SEE code
1.72      anton    8156:   [ HAVE-ASSEMBLER [IF] ]
1.29      crook    8157:   ... \ assembler-specific SEE code
                   8158:   [ [ENDIF] ]
                   8159: ;
                   8160: @end example
1.1       anton    8161: 
1.44      crook    8162: 
1.26      crook    8163: doc-[IF]
                   8164: doc-[ELSE]
                   8165: doc-[THEN]
                   8166: doc-[ENDIF]
1.1       anton    8167: 
1.26      crook    8168: doc-[IFDEF]
                   8169: doc-[IFUNDEF]
1.1       anton    8170: 
1.26      crook    8171: doc-[?DO]
                   8172: doc-[DO]
                   8173: doc-[FOR]
                   8174: doc-[LOOP]
                   8175: doc-[+LOOP]
                   8176: doc-[NEXT]
1.1       anton    8177: 
1.26      crook    8178: doc-[BEGIN]
                   8179: doc-[UNTIL]
                   8180: doc-[AGAIN]
                   8181: doc-[WHILE]
                   8182: doc-[REPEAT]
1.1       anton    8183: 
1.27      crook    8184: 
1.26      crook    8185: @c -------------------------------------------------------------
1.111     anton    8186: @node The Input Stream, Word Lists, The Text Interpreter, Words
                   8187: @section The Input Stream
                   8188: @cindex input stream
                   8189: 
                   8190: @c !! integrate this better with the "Text Interpreter" section
                   8191: The text interpreter reads from the input stream, which can come from
                   8192: several sources (@pxref{Input Sources}).  Some words, in particular
                   8193: defining words, but also words like @code{'}, read parameters from the
                   8194: input stream instead of from the stack.
                   8195: 
                   8196: Such words are called parsing words, because they parse the input
                   8197: stream.  Parsing words are hard to use in other words, because it is
                   8198: hard to pass program-generated parameters through the input stream.
                   8199: They also usually have an unintuitive combination of interpretation and
                   8200: compilation semantics when implemented naively, leading to various
                   8201: approaches that try to produce a more intuitive behaviour
                   8202: (@pxref{Combined words}).
                   8203: 
                   8204: It should be obvious by now that parsing words are a bad idea.  If you
                   8205: want to implement a parsing word for convenience, also provide a factor
                   8206: of the word that does not parse, but takes the parameters on the stack.
                   8207: To implement the parsing word on top if it, you can use the following
                   8208: words:
                   8209: 
                   8210: @c anton: these belong in the input stream section
                   8211: doc-parse
1.138     anton    8212: doc-parse-name
1.111     anton    8213: doc-parse-word
                   8214: doc-name
                   8215: doc-word
                   8216: doc-refill
                   8217: 
                   8218: Conversely, if you have the bad luck (or lack of foresight) to have to
                   8219: deal with parsing words without having such factors, how do you pass a
                   8220: string that is not in the input stream to it?
                   8221: 
                   8222: doc-execute-parsing
                   8223: 
1.146     anton    8224: A definition of this word in ANS Forth is provided in
                   8225: @file{compat/execute-parsing.fs}.
                   8226: 
1.111     anton    8227: If you want to run a parsing word on a file, the following word should
                   8228: help:
                   8229: 
                   8230: doc-execute-parsing-file
                   8231: 
                   8232: @c -------------------------------------------------------------
                   8233: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26      crook    8234: @section Word Lists
                   8235: @cindex word lists
1.32      anton    8236: @cindex header space
1.1       anton    8237: 
1.36      anton    8238: A wordlist is a list of named words; you can add new words and look up
                   8239: words by name (and you can remove words in a restricted way with
                   8240: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
                   8241: 
                   8242: @cindex search order stack
                   8243: The text interpreter searches the wordlists present in the search order
                   8244: (a stack of wordlists), from the top to the bottom.  Within each
                   8245: wordlist, the search starts conceptually at the newest word; i.e., if
                   8246: two words in a wordlist have the same name, the newer word is found.
1.1       anton    8247: 
1.26      crook    8248: @cindex compilation word list
1.36      anton    8249: New words are added to the @dfn{compilation wordlist} (aka current
                   8250: wordlist).
1.1       anton    8251: 
1.36      anton    8252: @cindex wid
                   8253: A word list is identified by a cell-sized word list identifier (@i{wid})
                   8254: in much the same way as a file is identified by a file handle. The
                   8255: numerical value of the wid has no (portable) meaning, and might change
                   8256: from session to session.
1.1       anton    8257: 
1.29      crook    8258: The ANS Forth ``Search order'' word set is intended to provide a set of
                   8259: low-level tools that allow various different schemes to be
1.74      anton    8260: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26      crook    8261: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
1.45      crook    8262: Forth.
1.1       anton    8263: 
1.27      crook    8264: @comment TODO: locals section refers to here, saying that every word list (aka
                   8265: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78      anton    8266: @c anton: but better in a separate subsection on wordlist internals
1.1       anton    8267: 
1.45      crook    8268: @comment TODO: document markers, reveal, tables, mappedwordlist
                   8269: 
                   8270: @comment the gforthman- prefix is used to pick out the true definition of a
1.27      crook    8271: @comment word from the source files, rather than some alias.
1.44      crook    8272: 
1.26      crook    8273: doc-forth-wordlist
                   8274: doc-definitions
                   8275: doc-get-current
                   8276: doc-set-current
                   8277: doc-get-order
1.185     anton    8278: doc-set-order
1.26      crook    8279: doc-wordlist
1.30      anton    8280: doc-table
1.79      anton    8281: doc->order
1.36      anton    8282: doc-previous
1.26      crook    8283: doc-also
1.185     anton    8284: doc-forth
1.26      crook    8285: doc-only
1.185     anton    8286: doc-order
1.15      anton    8287: 
1.26      crook    8288: doc-find
                   8289: doc-search-wordlist
1.15      anton    8290: 
1.26      crook    8291: doc-words
                   8292: doc-vlist
1.44      crook    8293: @c doc-words-deferred
1.1       anton    8294: 
1.74      anton    8295: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26      crook    8296: doc-root
                   8297: doc-vocabulary
                   8298: doc-seal
                   8299: doc-vocs
                   8300: doc-current
                   8301: doc-context
1.1       anton    8302: 
1.44      crook    8303: 
1.26      crook    8304: @menu
1.75      anton    8305: * Vocabularies::                
1.67      anton    8306: * Why use word lists?::         
1.75      anton    8307: * Word list example::           
1.26      crook    8308: @end menu
                   8309: 
1.75      anton    8310: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
                   8311: @subsection Vocabularies
                   8312: @cindex Vocabularies, detailed explanation
                   8313: 
                   8314: Here is an example of creating and using a new wordlist using ANS
                   8315: Forth words:
                   8316: 
                   8317: @example
                   8318: wordlist constant my-new-words-wordlist
                   8319: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
                   8320: 
                   8321: \ add it to the search order
                   8322: also my-new-words
                   8323: 
                   8324: \ alternatively, add it to the search order and make it
                   8325: \ the compilation word list
                   8326: also my-new-words definitions
                   8327: \ type "order" to see the problem
                   8328: @end example
                   8329: 
                   8330: The problem with this example is that @code{order} has no way to
                   8331: associate the name @code{my-new-words} with the wid of the word list (in
                   8332: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   8333: that has no associated name). There is no Standard way of associating a
                   8334: name with a wid.
                   8335: 
                   8336: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   8337: associates a name with a wid:
                   8338: 
                   8339: @example
                   8340: vocabulary my-new-words
                   8341: 
                   8342: \ add it to the search order
                   8343: also my-new-words
                   8344: 
                   8345: \ alternatively, add it to the search order and make it
                   8346: \ the compilation word list
                   8347: my-new-words definitions
                   8348: \ type "order" to see that the problem is solved
                   8349: @end example
                   8350: 
                   8351: 
                   8352: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26      crook    8353: @subsection Why use word lists?
                   8354: @cindex word lists - why use them?
                   8355: 
1.74      anton    8356: Here are some reasons why people use wordlists:
1.26      crook    8357: 
                   8358: @itemize @bullet
1.74      anton    8359: 
                   8360: @c anton: Gforth's hashing implementation makes the search speed
                   8361: @c independent from the number of words.  But it is linear with the number
                   8362: @c of wordlists that have to be searched, so in effect using more wordlists
                   8363: @c actually slows down compilation.
                   8364: 
                   8365: @c @item
                   8366: @c To improve compilation speed by reducing the number of header space
                   8367: @c entries that must be searched. This is achieved by creating a new
                   8368: @c word list that contains all of the definitions that are used in the
                   8369: @c definition of a Forth system but which would not usually be used by
                   8370: @c programs running on that system. That word list would be on the search
                   8371: @c list when the Forth system was compiled but would be removed from the
                   8372: @c search list for normal operation. This can be a useful technique for
                   8373: @c low-performance systems (for example, 8-bit processors in embedded
                   8374: @c systems) but is unlikely to be necessary in high-performance desktop
                   8375: @c systems.
                   8376: 
1.26      crook    8377: @item
                   8378: To prevent a set of words from being used outside the context in which
                   8379: they are valid. Two classic examples of this are an integrated editor
                   8380: (all of the edit commands are defined in a separate word list; the
                   8381: search order is set to the editor word list when the editor is invoked;
                   8382: the old search order is restored when the editor is terminated) and an
                   8383: integrated assembler (the op-codes for the machine are defined in a
                   8384: separate word list which is used when a @code{CODE} word is defined).
1.74      anton    8385: 
                   8386: @item
                   8387: To organize the words of an application or library into a user-visible
                   8388: set (in @code{forth-wordlist} or some other common wordlist) and a set
                   8389: of helper words used just for the implementation (hidden in a separate
1.75      anton    8390: wordlist).  This keeps @code{words}' output smaller, separates
                   8391: implementation and interface, and reduces the chance of name conflicts
                   8392: within the common wordlist.
1.74      anton    8393: 
1.26      crook    8394: @item
                   8395: To prevent a name-space clash between multiple definitions with the same
                   8396: name. For example, when building a cross-compiler you might have a word
                   8397: @code{IF} that generates conditional code for your target system. By
                   8398: placing this definition in a different word list you can control whether
                   8399: the host system's @code{IF} or the target system's @code{IF} get used in
                   8400: any particular context by controlling the order of the word lists on the
                   8401: search order stack.
1.74      anton    8402: 
1.26      crook    8403: @end itemize
1.1       anton    8404: 
1.74      anton    8405: The downsides of using wordlists are:
                   8406: 
                   8407: @itemize
                   8408: 
                   8409: @item
                   8410: Debugging becomes more cumbersome.
                   8411: 
                   8412: @item
                   8413: Name conflicts worked around with wordlists are still there, and you
                   8414: have to arrange the search order carefully to get the desired results;
                   8415: if you forget to do that, you get hard-to-find errors (as in any case
                   8416: where you read the code differently from the compiler; @code{see} can
1.75      anton    8417: help seeing which of several possible words the name resolves to in such
                   8418: cases).  @code{See} displays just the name of the words, not what
                   8419: wordlist they belong to, so it might be misleading.  Using unique names
                   8420: is a better approach to avoid name conflicts.
1.74      anton    8421: 
                   8422: @item
                   8423: You have to explicitly undo any changes to the search order.  In many
                   8424: cases it would be more convenient if this happened implicitly.  Gforth
                   8425: currently does not provide such a feature, but it may do so in the
                   8426: future.
                   8427: @end itemize
                   8428: 
                   8429: 
1.75      anton    8430: @node Word list example,  , Why use word lists?, Word Lists
                   8431: @subsection Word list example
                   8432: @cindex word lists - example
1.1       anton    8433: 
1.74      anton    8434: The following example is from the
                   8435: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   8436: garbage collector} and uses wordlists to separate public words from
                   8437: helper words:
                   8438: 
                   8439: @example
                   8440: get-current ( wid )
                   8441: vocabulary garbage-collector also garbage-collector definitions
                   8442: ... \ define helper words
                   8443: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
                   8444: ... \ define the public (i.e., API) words
                   8445:     \ they can refer to the helper words
                   8446: previous \ restore original search order (helper words become invisible)
                   8447: @end example
                   8448: 
1.26      crook    8449: @c -------------------------------------------------------------
                   8450: @node Environmental Queries, Files, Word Lists, Words
                   8451: @section Environmental Queries
                   8452: @cindex environmental queries
1.21      crook    8453: 
1.26      crook    8454: ANS Forth introduced the idea of ``environmental queries'' as a way
                   8455: for a program running on a system to determine certain characteristics of the system.
                   8456: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    8457: 
1.32      anton    8458: The Standard requires that the header space used for environmental queries
                   8459: be distinct from the header space used for definitions.
1.21      crook    8460: 
1.26      crook    8461: Typically, environmental queries are supported by creating a set of
1.29      crook    8462: definitions in a word list that is @i{only} used during environmental
1.26      crook    8463: queries; that is what Gforth does. There is no Standard way of adding
                   8464: definitions to the set of recognised environmental queries, but any
                   8465: implementation that supports the loading of optional word sets must have
                   8466: some mechanism for doing this (after loading the word set, the
                   8467: associated environmental query string must return @code{true}). In
                   8468: Gforth, the word list used to honour environmental queries can be
                   8469: manipulated just like any other word list.
1.21      crook    8470: 
1.44      crook    8471: 
1.26      crook    8472: doc-environment?
                   8473: doc-environment-wordlist
1.21      crook    8474: 
1.26      crook    8475: doc-gforth
                   8476: doc-os-class
1.21      crook    8477: 
1.44      crook    8478: 
1.26      crook    8479: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   8480: returning two items on the stack, querying it using @code{environment?}
                   8481: will return an additional item; the @code{true} flag that shows that the
                   8482: string was recognised.
1.21      crook    8483: 
1.26      crook    8484: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    8485: 
1.26      crook    8486: Here are some examples of using environmental queries:
1.21      crook    8487: 
1.26      crook    8488: @example
                   8489: s" address-unit-bits" environment? 0=
                   8490: [IF]
                   8491:      cr .( environmental attribute address-units-bits unknown... ) cr
1.75      anton    8492: [ELSE]
                   8493:      drop \ ensure balanced stack effect
1.26      crook    8494: [THEN]
1.21      crook    8495: 
1.75      anton    8496: \ this might occur in the prelude of a standard program that uses THROW
                   8497: s" exception" environment? [IF]
                   8498:    0= [IF]
                   8499:       : throw abort" exception thrown" ;
                   8500:    [THEN]
                   8501: [ELSE] \ we don't know, so make sure
                   8502:    : throw abort" exception thrown" ;
                   8503: [THEN]
1.21      crook    8504: 
1.26      crook    8505: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   8506:                         [ELSE] .( Not Gforth..) [THEN]
1.75      anton    8507: 
                   8508: \ a program using v*
                   8509: s" gforth" environment? [IF]
                   8510:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
                   8511:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8512:      >r swap 2swap swap 0e r> 0 ?DO
1.190     anton    8513:        dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
1.75      anton    8514:      LOOP
                   8515:      2drop 2drop ; 
                   8516:   [THEN]
                   8517: [ELSE] \ 
                   8518:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8519:   ...
                   8520: [THEN]
1.26      crook    8521: @end example
1.21      crook    8522: 
1.26      crook    8523: Here is an example of adding a definition to the environment word list:
1.21      crook    8524: 
1.26      crook    8525: @example
                   8526: get-current environment-wordlist set-current
                   8527: true constant block
                   8528: true constant block-ext
                   8529: set-current
                   8530: @end example
1.21      crook    8531: 
1.26      crook    8532: You can see what definitions are in the environment word list like this:
1.21      crook    8533: 
1.26      crook    8534: @example
1.79      anton    8535: environment-wordlist >order words previous
1.26      crook    8536: @end example
1.21      crook    8537: 
                   8538: 
1.26      crook    8539: @c -------------------------------------------------------------
                   8540: @node Files, Blocks, Environmental Queries, Words
                   8541: @section Files
1.28      crook    8542: @cindex files
                   8543: @cindex I/O - file-handling
1.21      crook    8544: 
1.26      crook    8545: Gforth provides facilities for accessing files that are stored in the
                   8546: host operating system's file-system. Files that are processed by Gforth
                   8547: can be divided into two categories:
1.21      crook    8548: 
1.23      crook    8549: @itemize @bullet
                   8550: @item
1.29      crook    8551: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    8552: @item
1.29      crook    8553: Files that are processed by some other program (@dfn{general files}).
1.26      crook    8554: @end itemize
                   8555: 
                   8556: @menu
1.48      anton    8557: * Forth source files::          
                   8558: * General files::               
1.167     anton    8559: * Redirection::                 
1.48      anton    8560: * Search Paths::                
1.26      crook    8561: @end menu
                   8562: 
                   8563: @c -------------------------------------------------------------
                   8564: @node Forth source files, General files, Files, Files
                   8565: @subsection Forth source files
                   8566: @cindex including files
                   8567: @cindex Forth source files
1.21      crook    8568: 
1.26      crook    8569: The simplest way to interpret the contents of a file is to use one of
                   8570: these two formats:
1.21      crook    8571: 
1.26      crook    8572: @example
                   8573: include mysource.fs
                   8574: s" mysource.fs" included
                   8575: @end example
1.21      crook    8576: 
1.75      anton    8577: You usually want to include a file only if it is not included already
1.26      crook    8578: (by, say, another source file). In that case, you can use one of these
1.45      crook    8579: three formats:
1.21      crook    8580: 
1.26      crook    8581: @example
                   8582: require mysource.fs
                   8583: needs mysource.fs
                   8584: s" mysource.fs" required
                   8585: @end example
1.21      crook    8586: 
1.26      crook    8587: @cindex stack effect of included files
                   8588: @cindex including files, stack effect
1.45      crook    8589: It is good practice to write your source files such that interpreting them
                   8590: does not change the stack. Source files designed in this way can be used with
1.26      crook    8591: @code{required} and friends without complications. For example:
1.21      crook    8592: 
1.26      crook    8593: @example
1.75      anton    8594: 1024 require foo.fs drop
1.26      crook    8595: @end example
1.21      crook    8596: 
1.75      anton    8597: Here you want to pass the argument 1024 (e.g., a buffer size) to
                   8598: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
                   8599: ), which allows its use with @code{require}.  Of course with such
                   8600: parameters to required files, you have to ensure that the first
                   8601: @code{require} fits for all uses (i.e., @code{require} it early in the
                   8602: master load file).
1.44      crook    8603: 
1.26      crook    8604: doc-include-file
                   8605: doc-included
1.28      crook    8606: doc-included?
1.26      crook    8607: doc-include
                   8608: doc-required
                   8609: doc-require
                   8610: doc-needs
1.75      anton    8611: @c doc-init-included-files @c internal
                   8612: doc-sourcefilename
                   8613: doc-sourceline#
1.44      crook    8614: 
1.26      crook    8615: A definition in ANS Forth for @code{required} is provided in
                   8616: @file{compat/required.fs}.
1.21      crook    8617: 
1.26      crook    8618: @c -------------------------------------------------------------
1.167     anton    8619: @node General files, Redirection, Forth source files, Files
1.26      crook    8620: @subsection General files
                   8621: @cindex general files
                   8622: @cindex file-handling
1.21      crook    8623: 
1.75      anton    8624: Files are opened/created by name and type. The following file access
                   8625: methods (FAMs) are recognised:
1.44      crook    8626: 
1.75      anton    8627: @cindex fam (file access method)
1.26      crook    8628: doc-r/o
                   8629: doc-r/w
                   8630: doc-w/o
                   8631: doc-bin
1.1       anton    8632: 
1.44      crook    8633: 
1.26      crook    8634: When a file is opened/created, it returns a file identifier,
1.29      crook    8635: @i{wfileid} that is used for all other file commands. All file
                   8636: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    8637: successful operation and an implementation-defined non-zero value in the
                   8638: case of an error.
1.21      crook    8639: 
1.44      crook    8640: 
1.26      crook    8641: doc-open-file
                   8642: doc-create-file
1.21      crook    8643: 
1.26      crook    8644: doc-close-file
                   8645: doc-delete-file
                   8646: doc-rename-file
                   8647: doc-read-file
                   8648: doc-read-line
1.154     anton    8649: doc-key-file
                   8650: doc-key?-file
1.26      crook    8651: doc-write-file
                   8652: doc-write-line
                   8653: doc-emit-file
                   8654: doc-flush-file
1.21      crook    8655: 
1.26      crook    8656: doc-file-status
                   8657: doc-file-position
                   8658: doc-reposition-file
                   8659: doc-file-size
                   8660: doc-resize-file
1.21      crook    8661: 
1.93      anton    8662: doc-slurp-file
                   8663: doc-slurp-fid
1.112     anton    8664: doc-stdin
                   8665: doc-stdout
                   8666: doc-stderr
1.44      crook    8667: 
1.26      crook    8668: @c ---------------------------------------------------------
1.167     anton    8669: @node Redirection, Search Paths, General files, Files
                   8670: @subsection Redirection
                   8671: @cindex Redirection
                   8672: @cindex Input Redirection
                   8673: @cindex Output Redirection
                   8674: 
                   8675: You can redirect the output of @code{type} and @code{emit} and all the
                   8676: words that use them (all output words that don't have an explicit
1.174     anton    8677: target file) to an arbitrary file with the @code{outfile-execute},
                   8678: used like this:
1.167     anton    8679: 
                   8680: @example
1.174     anton    8681: : some-warning ( n -- )
                   8682:     cr ." warning# " . ;
                   8683: 
1.167     anton    8684: : print-some-warning ( n -- )
1.174     anton    8685:     ['] some-warning stderr outfile-execute ;
1.167     anton    8686: @end example
                   8687: 
1.174     anton    8688: After @code{some-warning} is executed, the original output direction
                   8689: is restored; this construct is safe against exceptions.  Similarly,
                   8690: there is @code{infile-execute} for redirecting the input of @code{key}
                   8691: and its users (any input word that does not take a file explicitly).
                   8692: 
                   8693: doc-outfile-execute
                   8694: doc-infile-execute
1.167     anton    8695: 
                   8696: If you do not want to redirect the input or output to a file, you can
                   8697: also make use of the fact that @code{key}, @code{emit} and @code{type}
                   8698: are deferred words (@pxref{Deferred Words}).  However, in that case
                   8699: you have to worry about the restoration and the protection against
                   8700: exceptions yourself; also, note that for redirecting the output in
                   8701: this way, you have to redirect both @code{emit} and @code{type}.
                   8702: 
                   8703: @c ---------------------------------------------------------
                   8704: @node Search Paths,  , Redirection, Files
1.26      crook    8705: @subsection Search Paths
                   8706: @cindex path for @code{included}
                   8707: @cindex file search path
                   8708: @cindex @code{include} search path
                   8709: @cindex search path for files
1.21      crook    8710: 
1.26      crook    8711: If you specify an absolute filename (i.e., a filename starting with
                   8712: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   8713: @samp{C:...})) for @code{included} and friends, that file is included
                   8714: just as you would expect.
1.21      crook    8715: 
1.75      anton    8716: If the filename starts with @file{./}, this refers to the directory that
                   8717: the present file was @code{included} from.  This allows files to include
                   8718: other files relative to their own position (irrespective of the current
                   8719: working directory or the absolute position).  This feature is essential
                   8720: for libraries consisting of several files, where a file may include
                   8721: other files from the library.  It corresponds to @code{#include "..."}
                   8722: in C. If the current input source is not a file, @file{.} refers to the
                   8723: directory of the innermost file being included, or, if there is no file
                   8724: being included, to the current working directory.
                   8725: 
                   8726: For relative filenames (not starting with @file{./}), Gforth uses a
                   8727: search path similar to Forth's search order (@pxref{Word Lists}). It
                   8728: tries to find the given filename in the directories present in the path,
                   8729: and includes the first one it finds. There are separate search paths for
                   8730: Forth source files and general files.  If the search path contains the
                   8731: directory @file{.}, this refers to the directory of the current file, or
                   8732: the working directory, as if the file had been specified with @file{./}.
1.21      crook    8733: 
1.26      crook    8734: Use @file{~+} to refer to the current working directory (as in the
                   8735: @code{bash}).
1.1       anton    8736: 
1.75      anton    8737: @c anton: fold the following subsubsections into this subsection?
1.1       anton    8738: 
1.48      anton    8739: @menu
1.75      anton    8740: * Source Search Paths::         
1.48      anton    8741: * General Search Paths::        
                   8742: @end menu
                   8743: 
1.26      crook    8744: @c ---------------------------------------------------------
1.75      anton    8745: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
                   8746: @subsubsection Source Search Paths
                   8747: @cindex search path control, source files
1.5       anton    8748: 
1.26      crook    8749: The search path is initialized when you start Gforth (@pxref{Invoking
1.75      anton    8750: Gforth}). You can display it and change it using @code{fpath} in
                   8751: combination with the general path handling words.
1.5       anton    8752: 
1.75      anton    8753: doc-fpath
                   8754: @c the functionality of the following words is easily available through
                   8755: @c   fpath and the general path words.  The may go away.
                   8756: @c doc-.fpath
                   8757: @c doc-fpath+
                   8758: @c doc-fpath=
                   8759: @c doc-open-fpath-file
1.44      crook    8760: 
                   8761: @noindent
1.26      crook    8762: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    8763: 
1.26      crook    8764: @example
1.75      anton    8765: fpath path= /usr/lib/forth/|./
1.26      crook    8766: require timer.fs
                   8767: @end example
1.5       anton    8768: 
1.75      anton    8769: 
1.26      crook    8770: @c ---------------------------------------------------------
1.75      anton    8771: @node General Search Paths,  , Source Search Paths, Search Paths
1.26      crook    8772: @subsubsection General Search Paths
1.75      anton    8773: @cindex search path control, source files
1.5       anton    8774: 
1.26      crook    8775: Your application may need to search files in several directories, like
                   8776: @code{included} does. To facilitate this, Gforth allows you to define
                   8777: and use your own search paths, by providing generic equivalents of the
                   8778: Forth search path words:
1.5       anton    8779: 
1.75      anton    8780: doc-open-path-file
                   8781: doc-path-allot
                   8782: doc-clear-path
                   8783: doc-also-path
1.26      crook    8784: doc-.path
                   8785: doc-path+
                   8786: doc-path=
1.5       anton    8787: 
1.75      anton    8788: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44      crook    8789: 
1.75      anton    8790: Here's an example of creating an empty search path:
                   8791: @c
1.26      crook    8792: @example
1.75      anton    8793: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26      crook    8794: @end example
1.5       anton    8795: 
1.26      crook    8796: @c -------------------------------------------------------------
                   8797: @node Blocks, Other I/O, Files, Words
                   8798: @section Blocks
1.28      crook    8799: @cindex I/O - blocks
                   8800: @cindex blocks
                   8801: 
                   8802: When you run Gforth on a modern desk-top computer, it runs under the
                   8803: control of an operating system which provides certain services.  One of
                   8804: these services is @var{file services}, which allows Forth source code
                   8805: and data to be stored in files and read into Gforth (@pxref{Files}).
                   8806: 
                   8807: Traditionally, Forth has been an important programming language on
                   8808: systems where it has interfaced directly to the underlying hardware with
                   8809: no intervening operating system. Forth provides a mechanism, called
1.29      crook    8810: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    8811: 
                   8812: A block is a 1024-byte data area, which can be used to hold data or
                   8813: Forth source code. No structure is imposed on the contents of the
                   8814: block. A block is identified by its number; blocks are numbered
                   8815: contiguously from 1 to an implementation-defined maximum.
                   8816: 
                   8817: A typical system that used blocks but no operating system might use a
                   8818: single floppy-disk drive for mass storage, with the disks formatted to
                   8819: provide 256-byte sectors. Blocks would be implemented by assigning the
                   8820: first four sectors of the disk to block 1, the second four sectors to
                   8821: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   8822: would not contain any file system information, just the set of blocks.
                   8823: 
1.29      crook    8824: @cindex blocks file
1.28      crook    8825: On systems that do provide file services, blocks are typically
1.29      crook    8826: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    8827: file}.  The size of the blocks file will be an exact multiple of 1024
                   8828: bytes, corresponding to the number of blocks it contains. This is the
                   8829: mechanism that Gforth uses.
                   8830: 
1.29      crook    8831: @cindex @file{blocks.fb}
1.75      anton    8832: Only one blocks file can be open at a time. If you use block words without
1.28      crook    8833: having specified a blocks file, Gforth defaults to the blocks file
                   8834: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75      anton    8835: locate a blocks file (@pxref{Source Search Paths}).
1.28      crook    8836: 
1.29      crook    8837: @cindex block buffers
1.28      crook    8838: When you read and write blocks under program control, Gforth uses a
1.29      crook    8839: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    8840: not used when you use @code{load} to interpret the contents of a block.
                   8841: 
1.75      anton    8842: The behaviour of the block buffers is analagous to that of a cache.
                   8843: Each block buffer has three states:
1.28      crook    8844: 
                   8845: @itemize @bullet
                   8846: @item
                   8847: Unassigned
                   8848: @item
                   8849: Assigned-clean
                   8850: @item
                   8851: Assigned-dirty
                   8852: @end itemize
                   8853: 
1.29      crook    8854: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    8855: block, the block (specified by its block number) must be assigned to a
                   8856: block buffer.
                   8857: 
                   8858: The assignment of a block to a block buffer is performed by @code{block}
                   8859: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   8860: contents of a block. Use @code{buffer} when you don't care about the
                   8861: existing contents of the block@footnote{The ANS Forth definition of
1.35      anton    8862: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28      crook    8863: with the particular block is already stored in a block buffer due to an
                   8864: earlier @code{block} command, @code{buffer} will return that block
                   8865: buffer and the existing contents of the block will be
                   8866: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    8867: block buffer for the block.}.
1.28      crook    8868: 
1.47      crook    8869: Once a block has been assigned to a block buffer using @code{block} or
1.75      anton    8870: @code{buffer}, that block buffer becomes the @i{current block
                   8871: buffer}. Data may only be manipulated (read or written) within the
                   8872: current block buffer.
1.47      crook    8873: 
                   8874: When the contents of the current block buffer has been modified it is
1.48      anton    8875: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75      anton    8876: either abandon the changes (by doing nothing) or mark the block as
                   8877: changed (assigned-dirty), using @code{update}. Using @code{update} does
                   8878: not change the blocks file; it simply changes a block buffer's state to
                   8879: @i{assigned-dirty}.  The block will be written implicitly when it's
                   8880: buffer is needed for another block, or explicitly by @code{flush} or
                   8881: @code{save-buffers}.
                   8882: 
                   8883: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
                   8884: blocks file on disk. Leaving Gforth with @code{bye} also performs a
                   8885: @code{flush}.
1.28      crook    8886: 
1.29      crook    8887: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    8888: algorithm to assign a block buffer to a block. That means that any
                   8889: particular block can only be assigned to one specific block buffer,
1.29      crook    8890: called (for the particular operation) the @i{victim buffer}. If the
1.47      crook    8891: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
                   8892: the new block immediately. If it is @i{assigned-dirty} its current
                   8893: contents are written back to the blocks file on disk before it is
1.28      crook    8894: allocated to the new block.
                   8895: 
                   8896: Although no structure is imposed on the contents of a block, it is
                   8897: traditional to display the contents as 16 lines each of 64 characters.  A
                   8898: block provides a single, continuous stream of input (for example, it
                   8899: acts as a single parse area) -- there are no end-of-line characters
                   8900: within a block, and no end-of-file character at the end of a
                   8901: block. There are two consequences of this:
1.26      crook    8902: 
1.28      crook    8903: @itemize @bullet
                   8904: @item
                   8905: The last character of one line wraps straight into the first character
                   8906: of the following line
                   8907: @item
                   8908: The word @code{\} -- comment to end of line -- requires special
                   8909: treatment; in the context of a block it causes all characters until the
                   8910: end of the current 64-character ``line'' to be ignored.
                   8911: @end itemize
                   8912: 
                   8913: In Gforth, when you use @code{block} with a non-existent block number,
1.45      crook    8914: the current blocks file will be extended to the appropriate size and the
1.28      crook    8915: block buffer will be initialised with spaces.
                   8916: 
1.47      crook    8917: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
                   8918: for details) but doesn't encourage the use of blocks; the mechanism is
                   8919: only provided for backward compatibility -- ANS Forth requires blocks to
                   8920: be available when files are.
1.28      crook    8921: 
                   8922: Common techniques that are used when working with blocks include:
                   8923: 
                   8924: @itemize @bullet
                   8925: @item
                   8926: A screen editor that allows you to edit blocks without leaving the Forth
                   8927: environment.
                   8928: @item
                   8929: Shadow screens; where every code block has an associated block
                   8930: containing comments (for example: code in odd block numbers, comments in
                   8931: even block numbers). Typically, the block editor provides a convenient
                   8932: mechanism to toggle between code and comments.
                   8933: @item
                   8934: Load blocks; a single block (typically block 1) contains a number of
                   8935: @code{thru} commands which @code{load} the whole of the application.
                   8936: @end itemize
1.26      crook    8937: 
1.29      crook    8938: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   8939: integrated into a Forth programming environment.
1.26      crook    8940: 
                   8941: @comment TODO what about errors on open-blocks?
1.44      crook    8942: 
1.26      crook    8943: doc-open-blocks
                   8944: doc-use
1.75      anton    8945: doc-block-offset
1.26      crook    8946: doc-get-block-fid
                   8947: doc-block-position
1.28      crook    8948: 
1.75      anton    8949: doc-list
1.28      crook    8950: doc-scr
                   8951: 
1.184     anton    8952: doc-block
1.28      crook    8953: doc-buffer
                   8954: 
1.75      anton    8955: doc-empty-buffers
                   8956: doc-empty-buffer
1.26      crook    8957: doc-update
1.28      crook    8958: doc-updated?
1.26      crook    8959: doc-save-buffers
1.75      anton    8960: doc-save-buffer
1.26      crook    8961: doc-flush
1.28      crook    8962: 
1.26      crook    8963: doc-load
                   8964: doc-thru
                   8965: doc-+load
                   8966: doc-+thru
1.45      crook    8967: doc---gforthman--->
1.26      crook    8968: doc-block-included
                   8969: 
1.44      crook    8970: 
1.26      crook    8971: @c -------------------------------------------------------------
1.126     pazsan   8972: @node Other I/O, OS command line arguments, Blocks, Words
1.26      crook    8973: @section Other I/O
1.28      crook    8974: @cindex I/O - keyboard and display
1.26      crook    8975: 
                   8976: @menu
                   8977: * Simple numeric output::       Predefined formats
                   8978: * Formatted numeric output::    Formatted (pictured) output
                   8979: * String Formats::              How Forth stores strings in memory
1.67      anton    8980: * Displaying characters and strings::  Other stuff
1.231     pazsan   8981: * String words::                Gforth's little string library
1.175     anton    8982: * Terminal output::             Cursor positioning etc.
1.181     anton    8983: * Single-key input::            
                   8984: * Line input and conversion::   
1.112     anton    8985: * Pipes::                       How to create your own pipes
1.149     pazsan   8986: * Xchars and Unicode::          Non-ASCII characters
1.26      crook    8987: @end menu
                   8988: 
                   8989: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   8990: @subsection Simple numeric output
1.28      crook    8991: @cindex numeric output - simple/free-format
1.5       anton    8992: 
1.26      crook    8993: The simplest output functions are those that display numbers from the
                   8994: data or floating-point stacks. Floating-point output is always displayed
                   8995: using base 10. Numbers displayed from the data stack use the value stored
                   8996: in @code{base}.
1.5       anton    8997: 
1.44      crook    8998: 
1.26      crook    8999: doc-.
                   9000: doc-dec.
                   9001: doc-hex.
                   9002: doc-u.
                   9003: doc-.r
                   9004: doc-u.r
                   9005: doc-d.
                   9006: doc-ud.
                   9007: doc-d.r
                   9008: doc-ud.r
                   9009: doc-f.
                   9010: doc-fe.
                   9011: doc-fs.
1.111     anton    9012: doc-f.rdp
1.44      crook    9013: 
1.26      crook    9014: Examples of printing the number 1234.5678E23 in the different floating-point output
                   9015: formats are shown below:
1.5       anton    9016: 
                   9017: @example
1.26      crook    9018: f. 123456779999999000000000000.
                   9019: fe. 123.456779999999E24
                   9020: fs. 1.23456779999999E26
1.5       anton    9021: @end example
                   9022: 
                   9023: 
1.26      crook    9024: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   9025: @subsection Formatted numeric output
1.28      crook    9026: @cindex formatted numeric output
1.26      crook    9027: @cindex pictured numeric output
1.28      crook    9028: @cindex numeric output - formatted
1.26      crook    9029: 
1.29      crook    9030: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    9031: output} for formatted printing of integers.  In this technique, digits
                   9032: are extracted from the number (using the current output radix defined by
                   9033: @code{base}), converted to ASCII codes and appended to a string that is
                   9034: built in a scratch-pad area of memory (@pxref{core-idef,
                   9035: Implementation-defined options, Implementation-defined
                   9036: options}). Arbitrary characters can be appended to the string during the
                   9037: extraction process. The completed string is specified by an address
                   9038: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   9039: under program control.
1.5       anton    9040: 
1.75      anton    9041: All of the integer output words described in the previous section
                   9042: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
                   9043: numeric output.
1.5       anton    9044: 
1.47      crook    9045: Three important things to remember about pictured numeric output:
1.5       anton    9046: 
1.26      crook    9047: @itemize @bullet
                   9048: @item
1.28      crook    9049: It always operates on double-precision numbers; to display a
1.49      anton    9050: single-precision number, convert it first (for ways of doing this
                   9051: @pxref{Double precision}).
1.26      crook    9052: @item
1.28      crook    9053: It always treats the double-precision number as though it were
                   9054: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    9055: @item
                   9056: The string is built up from right to left; least significant digit first.
                   9057: @end itemize
1.5       anton    9058: 
1.44      crook    9059: 
1.26      crook    9060: doc-<#
1.47      crook    9061: doc-<<#
1.26      crook    9062: doc-#
                   9063: doc-#s
                   9064: doc-hold
                   9065: doc-sign
                   9066: doc-#>
1.47      crook    9067: doc-#>>
1.5       anton    9068: 
1.26      crook    9069: doc-represent
1.111     anton    9070: doc-f>str-rdp
                   9071: doc-f>buf-rdp
1.5       anton    9072: 
1.44      crook    9073: 
                   9074: @noindent
1.26      crook    9075: Here are some examples of using pictured numeric output:
1.5       anton    9076: 
                   9077: @example
1.26      crook    9078: : my-u. ( u -- )
                   9079:   \ Simplest use of pns.. behaves like Standard u. 
                   9080:   0              \ convert to unsigned double
1.75      anton    9081:   <<#            \ start conversion
1.26      crook    9082:   #s             \ convert all digits
                   9083:   #>             \ complete conversion
1.75      anton    9084:   TYPE SPACE     \ display, with trailing space
                   9085:   #>> ;          \ release hold area
1.5       anton    9086: 
1.26      crook    9087: : cents-only ( u -- )
                   9088:   0              \ convert to unsigned double
1.75      anton    9089:   <<#            \ start conversion
1.26      crook    9090:   # #            \ convert two least-significant digits
                   9091:   #>             \ complete conversion, discard other digits
1.75      anton    9092:   TYPE SPACE     \ display, with trailing space
                   9093:   #>> ;          \ release hold area
1.5       anton    9094: 
1.26      crook    9095: : dollars-and-cents ( u -- )
                   9096:   0              \ convert to unsigned double
1.75      anton    9097:   <<#            \ start conversion
1.26      crook    9098:   # #            \ convert two least-significant digits
                   9099:   [char] . hold  \ insert decimal point
                   9100:   #s             \ convert remaining digits
                   9101:   [char] $ hold  \ append currency symbol
                   9102:   #>             \ complete conversion
1.75      anton    9103:   TYPE SPACE     \ display, with trailing space
                   9104:   #>> ;          \ release hold area
1.5       anton    9105: 
1.26      crook    9106: : my-. ( n -- )
                   9107:   \ handling negatives.. behaves like Standard .
                   9108:   s>d            \ convert to signed double
                   9109:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    9110:   <<#            \ start conversion
1.26      crook    9111:   #s             \ convert all digits
                   9112:   rot sign       \ get at sign byte, append "-" if needed
                   9113:   #>             \ complete conversion
1.75      anton    9114:   TYPE SPACE     \ display, with trailing space
                   9115:   #>> ;          \ release hold area
1.5       anton    9116: 
1.26      crook    9117: : account. ( n -- )
1.75      anton    9118:   \ accountants don't like minus signs, they use parentheses
1.26      crook    9119:   \ for negative numbers
                   9120:   s>d            \ convert to signed double
                   9121:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    9122:   <<#            \ start conversion
1.26      crook    9123:   2 pick         \ get copy of sign byte
                   9124:   0< IF [char] ) hold THEN \ right-most character of output
                   9125:   #s             \ convert all digits
                   9126:   rot            \ get at sign byte
                   9127:   0< IF [char] ( hold THEN
                   9128:   #>             \ complete conversion
1.75      anton    9129:   TYPE SPACE     \ display, with trailing space
                   9130:   #>> ;          \ release hold area
                   9131: 
1.5       anton    9132: @end example
                   9133: 
1.26      crook    9134: Here are some examples of using these words:
1.5       anton    9135: 
                   9136: @example
1.26      crook    9137: 1 my-u. 1
                   9138: hex -1 my-u. decimal FFFFFFFF
                   9139: 1 cents-only 01
                   9140: 1234 cents-only 34
                   9141: 2 dollars-and-cents $0.02
                   9142: 1234 dollars-and-cents $12.34
                   9143: 123 my-. 123
                   9144: -123 my. -123
                   9145: 123 account. 123
                   9146: -456 account. (456)
1.5       anton    9147: @end example
                   9148: 
                   9149: 
1.26      crook    9150: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   9151: @subsection String Formats
1.27      crook    9152: @cindex strings - see character strings
                   9153: @cindex character strings - formats
1.28      crook    9154: @cindex I/O - see character strings
1.75      anton    9155: @cindex counted strings
                   9156: 
                   9157: @c anton: this does not really belong here; maybe the memory section,
                   9158: @c  or the principles chapter
1.26      crook    9159: 
1.27      crook    9160: Forth commonly uses two different methods for representing character
                   9161: strings:
1.26      crook    9162: 
                   9163: @itemize @bullet
                   9164: @item
                   9165: @cindex address of counted string
1.45      crook    9166: @cindex counted string
1.29      crook    9167: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   9168: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   9169: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    9170: memory.
                   9171: @item
1.29      crook    9172: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   9173: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    9174: first byte of the string.
                   9175: @end itemize
                   9176: 
                   9177: ANS Forth encourages the use of the second format when representing
1.75      anton    9178: strings.
1.26      crook    9179: 
1.44      crook    9180: 
1.26      crook    9181: doc-count
                   9182: 
1.44      crook    9183: 
1.49      anton    9184: For words that move, copy and search for strings see @ref{Memory
                   9185: Blocks}. For words that display characters and strings see
                   9186: @ref{Displaying characters and strings}.
1.26      crook    9187: 
1.231     pazsan   9188: @node Displaying characters and strings, String words, String Formats, Other I/O
1.26      crook    9189: @subsection Displaying characters and strings
1.27      crook    9190: @cindex characters - compiling and displaying
                   9191: @cindex character strings - compiling and displaying
1.26      crook    9192: 
                   9193: This section starts with a glossary of Forth words and ends with a set
                   9194: of examples.
                   9195: 
                   9196: doc-bl
                   9197: doc-space
                   9198: doc-spaces
                   9199: doc-emit
                   9200: doc-toupper
                   9201: doc-."
                   9202: doc-.(
1.98      anton    9203: doc-.\"
1.26      crook    9204: doc-type
1.44      crook    9205: doc-typewhite
1.26      crook    9206: doc-cr
1.27      crook    9207: @cindex cursor control
1.26      crook    9208: doc-s"
1.98      anton    9209: doc-s\"
1.26      crook    9210: doc-c"
                   9211: doc-char
                   9212: doc-[char]
                   9213: 
1.44      crook    9214: 
                   9215: @noindent
1.26      crook    9216: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    9217: 
                   9218: @example
1.26      crook    9219: .( text-1)
                   9220: : my-word
                   9221:   ." text-2" cr
                   9222:   .( text-3)
                   9223: ;
                   9224: 
                   9225: ." text-4"
                   9226: 
                   9227: : my-char
                   9228:   [char] ALPHABET emit
                   9229:   char emit
                   9230: ;
1.5       anton    9231: @end example
                   9232: 
1.26      crook    9233: When you load this code into Gforth, the following output is generated:
1.5       anton    9234: 
1.26      crook    9235: @example
1.30      anton    9236: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    9237: @end example
1.5       anton    9238: 
1.26      crook    9239: @itemize @bullet
                   9240: @item
                   9241: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   9242: is an immediate word; it behaves in the same way whether it is used inside
                   9243: or outside a colon definition.
                   9244: @item
                   9245: Message @code{text-4} is displayed because of Gforth's added interpretation
                   9246: semantics for @code{."}.
                   9247: @item
1.29      crook    9248: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    9249: performs the compilation semantics for @code{."} within the definition of
                   9250: @code{my-word}.
                   9251: @end itemize
1.5       anton    9252: 
1.26      crook    9253: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    9254: 
1.26      crook    9255: @example
1.30      anton    9256: @kbd{my-word @key{RET}} text-2
1.26      crook    9257:  ok
1.30      anton    9258: @kbd{my-char fred @key{RET}} Af ok
                   9259: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    9260: @end example
1.5       anton    9261: 
                   9262: @itemize @bullet
                   9263: @item
1.26      crook    9264: Message @code{text-2} is displayed because of the run-time behaviour of
                   9265: @code{."}.
                   9266: @item
                   9267: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   9268: on the stack at run-time. @code{emit} always displays the character
                   9269: when @code{my-char} is executed.
                   9270: @item
                   9271: @code{char} parses a string at run-time and the second @code{emit} displays
                   9272: the first character of the string.
1.5       anton    9273: @item
1.26      crook    9274: If you type @code{see my-char} you can see that @code{[char]} discarded
                   9275: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   9276: definition of @code{my-char}.
1.5       anton    9277: @end itemize
                   9278: 
1.231     pazsan   9279: @node String words, Terminal output, Displaying characters and strings, Other I/O
                   9280: @subsection String words
                   9281: @cindex string words
                   9282: 
                   9283: The following string library stores strings in ordinary variables,
                   9284: which then contain a pointer to a counted string stored allocated from
                   9285: the heap.  Instead of a count byte, there's a whole count cell,
                   9286: sufficient for all normal use.  The string library originates from
                   9287: bigFORTH.
                   9288: 
                   9289: doc-delete
                   9290: doc-insert
                   9291: doc-$!
                   9292: doc-$@
                   9293: doc-$@len
                   9294: doc-$!len
                   9295: doc-$del
                   9296: doc-$ins
                   9297: doc-$+!
                   9298: doc-$off
                   9299: doc-$init
                   9300: doc-$split
                   9301: doc-$iter
1.238     pazsan   9302: doc-$over
                   9303: doc-$[]
                   9304: doc-$[]!
                   9305: doc-$[]+!
                   9306: doc-$[]@
1.5       anton    9307: 
1.231     pazsan   9308: @node Terminal output, Single-key input, String words, Other I/O
1.175     anton    9309: @subsection Terminal output
                   9310: @cindex output to terminal
                   9311: @cindex terminal output
                   9312: 
                   9313: If you are outputting to a terminal, you may want to control the
                   9314: positioning of the cursor:
                   9315: @cindex cursor positioning
                   9316: 
                   9317: doc-at-xy
                   9318: 
                   9319: In order to know where to position the cursor, it is often helpful to
                   9320: know the size of the screen:
                   9321: @cindex terminal size 
                   9322: 
                   9323: doc-form
                   9324: 
                   9325: And sometimes you want to use:
                   9326: @cindex clear screen
                   9327: 
                   9328: doc-page
                   9329: 
                   9330: Note that on non-terminals you should use @code{12 emit}, not
                   9331: @code{page}, to get a form feed.
                   9332: 
1.5       anton    9333: 
1.181     anton    9334: @node Single-key input, Line input and conversion, Terminal output, Other I/O
                   9335: @subsection Single-key input
                   9336: @cindex single-key input
                   9337: @cindex input, single-key
                   9338: 
                   9339: If you want to get a single printable character, you can use
                   9340: @code{key}; to check whether a character is available for @code{key},
                   9341: you can use @code{key?}.
1.5       anton    9342: 
1.181     anton    9343: doc-key
                   9344: doc-key?
1.27      crook    9345: 
1.181     anton    9346: If you want to process a mix of printable and non-printable
                   9347: characters, you can do that with @code{ekey} and friends.  @code{Ekey}
                   9348: produces a keyboard event that you have to convert into a character
                   9349: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
                   9350: 
                   9351: Typical code for using EKEY looks like this:
                   9352: 
                   9353: @example
                   9354: ekey ekey>char if ( c )
                   9355:   ... \ do something with the character
                   9356: else ekey>fkey if ( key-id )
                   9357:   case
                   9358:     k-up                                  of ... endof
                   9359:     k-f1                                  of ... endof
                   9360:     k-left k-shift-mask or k-ctrl-mask or of ... endof
                   9361:     ...
                   9362:   endcase
                   9363: else ( keyboard-event )
                   9364:   drop \ just ignore an unknown keyboard event type
                   9365: then then
                   9366: @end example
1.44      crook    9367: 
1.45      crook    9368: doc-ekey
1.141     anton    9369: doc-ekey>char
1.181     anton    9370: doc-ekey>fkey
1.45      crook    9371: doc-ekey?
1.141     anton    9372: 
1.181     anton    9373: The key identifiers for cursor keys are:
1.141     anton    9374: 
                   9375: doc-k-left
                   9376: doc-k-right
1.185     anton    9377: doc-k-up
                   9378: doc-k-down
                   9379: doc-k-home
                   9380: doc-k-end
1.141     anton    9381: doc-k-prior
                   9382: doc-k-next
                   9383: doc-k-insert
                   9384: doc-k-delete
                   9385: 
1.181     anton    9386: The key identifiers for function keys (aka keypad keys) are:
1.141     anton    9387: 
1.181     anton    9388: doc-k-f1
                   9389: doc-k-f2
                   9390: doc-k-f3
                   9391: doc-k-f4
                   9392: doc-k-f5
                   9393: doc-k-f6
                   9394: doc-k-f7
                   9395: doc-k-f8
                   9396: doc-k-f9
                   9397: doc-k-f10
                   9398: doc-k-f11
                   9399: doc-k-f12
                   9400: 
                   9401: Note that @code{k-f11} and @code{k-f12} are not as widely available.
                   9402: 
                   9403: You can combine these key identifiers with masks for various shift keys:
                   9404: 
                   9405: doc-k-shift-mask
                   9406: doc-k-ctrl-mask
                   9407: doc-k-alt-mask
                   9408: 
                   9409: Note that, even if a Forth system has @code{ekey>fkey} and the key
                   9410: identifier words, the keys are not necessarily available or it may not
                   9411: necessarily be able to report all the keys and all the possible
                   9412: combinations with shift masks.  Therefore, write your programs in such
                   9413: a way that they are still useful even if the keys and key combinations
                   9414: cannot be pressed or are not recognized.
                   9415: 
                   9416: Examples: Older keyboards often do not have an F11 and F12 key.  If
                   9417: you run Gforth in an xterm, the xterm catches a number of combinations
                   9418: (e.g., @key{Shift-Up}), and never passes it to Gforth.  Finally,
                   9419: Gforth currently does not recognize and report combinations with
                   9420: multiple shift keys (so the @key{shift-ctrl-left} case in the example
                   9421: above would never be entered).
                   9422: 
                   9423: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
                   9424: you need the ANSI.SYS driver to get that behaviour); it works by
                   9425: recognizing the escape sequences that ANSI terminals send when such a
                   9426: key is pressed.  If you have a terminal that sends other escape
                   9427: sequences, you will not get useful results on Gforth.  Other Forth
                   9428: systems may work in a different way.
                   9429: 
1.200     anton    9430: Gforth also provides a few words for outputting names of function
                   9431: keys:
                   9432: 
                   9433: doc-fkey.
                   9434: doc-simple-fkey-string
                   9435: 
1.181     anton    9436: 
                   9437: @node  Line input and conversion, Pipes, Single-key input, Other I/O
                   9438: @subsection Line input and conversion
                   9439: @cindex line input from terminal
                   9440: @cindex input, linewise from terminal
                   9441: @cindex convertin strings to numbers
                   9442: @cindex I/O - see input
                   9443: 
                   9444: For ways of storing character strings in memory see @ref{String Formats}.
                   9445: 
                   9446: @comment TODO examples for >number >float accept key key? pad parse word refill
                   9447: @comment then index them
1.141     anton    9448: 
                   9449: Words for inputting one line from the keyboard:
                   9450: 
                   9451: doc-accept
                   9452: doc-edit-line
                   9453: 
                   9454: Conversion words:
                   9455: 
1.143     anton    9456: doc-s>number?
                   9457: doc-s>unumber?
1.26      crook    9458: doc->number
                   9459: doc->float
1.237     pazsan   9460: doc->float1
1.141     anton    9461: 
1.27      crook    9462: @comment obsolescent words..
1.141     anton    9463: Obsolescent input and conversion words:
                   9464: 
1.27      crook    9465: doc-convert
1.26      crook    9466: doc-expect
1.27      crook    9467: doc-span
1.5       anton    9468: 
                   9469: 
1.181     anton    9470: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
1.112     anton    9471: @subsection Pipes
                   9472: @cindex pipes, creating your own
                   9473: 
                   9474: In addition to using Gforth in pipes created by other processes
                   9475: (@pxref{Gforth in pipes}), you can create your own pipe with
                   9476: @code{open-pipe}, and read from or write to it.
                   9477: 
                   9478: doc-open-pipe
                   9479: doc-close-pipe
                   9480: 
                   9481: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
                   9482: you don't catch this exception, Gforth will catch it and exit, usually
                   9483: silently (@pxref{Gforth in pipes}).  Since you probably do not want
                   9484: this, you should wrap a @code{catch} or @code{try} block around the code
                   9485: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
                   9486: problem yourself, and then return to regular processing.
                   9487: 
                   9488: doc-broken-pipe-error
                   9489: 
1.155     anton    9490: @node Xchars and Unicode,  , Pipes, Other I/O
                   9491: @subsection Xchars and Unicode
1.149     pazsan   9492: 
1.188     pazsan   9493: ASCII is only appropriate for the English language. Most western
                   9494: languages however fit somewhat into the Forth frame, since a byte is
                   9495: sufficient to encode the few special characters in each (though not
                   9496: always the same encoding can be used; latin-1 is most widely used,
                   9497: though). For other languages, different char-sets have to be used,
                   9498: several of them variable-width. Most prominent representant is
                   9499: UTF-8. Let's call these extended characters xchars. The primitive
                   9500: fixed-size characters stored as bytes are called pchars in this
                   9501: section.
                   9502: 
                   9503: The xchar words add a few data types:
                   9504: 
                   9505: @itemize
                   9506: 
                   9507: @item
                   9508: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
                   9509: and is a subset of unsigned cell. Note: UTF-8 can not store more that
                   9510: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
                   9511: character set can be used.
                   9512: 
                   9513: @item
                   9514: @var{xc-addr} is the address of an xchar in memory. Alignment
                   9515: requirements are the same as @var{c-addr}. The memory representation of an
                   9516: xchar differs from the stack representation, and depends on the
                   9517: encoding used. An xchar may use a variable number of pchars in memory.
                   9518: 
                   9519: @item
                   9520: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
                   9521: @var{xc-addr}, @var{u} pchars long.
                   9522: 
                   9523: @end itemize
                   9524: 
                   9525: doc-xc-size
                   9526: doc-x-size
                   9527: doc-xc@+
                   9528: doc-xc!+?
                   9529: doc-xchar+
                   9530: doc-xchar-
                   9531: doc-+x/string
                   9532: doc-x\string-
                   9533: doc--trailing-garbage
                   9534: doc-x-width
                   9535: doc-xkey
                   9536: doc-xemit
                   9537: 
                   9538: There's a new environment query
                   9539: 
                   9540: doc-xchar-encoding
1.112     anton    9541: 
1.121     anton    9542: @node OS command line arguments, Locals, Other I/O, Words
                   9543: @section OS command line arguments
                   9544: @cindex OS command line arguments
                   9545: @cindex command line arguments, OS
                   9546: @cindex arguments, OS command line
                   9547: 
                   9548: The usual way to pass arguments to Gforth programs on the command line
                   9549: is via the @option{-e} option, e.g.
                   9550: 
                   9551: @example
                   9552: gforth -e "123 456" foo.fs -e bye
                   9553: @end example
                   9554: 
                   9555: However, you may want to interpret the command-line arguments directly.
                   9556: In that case, you can access the (image-specific) command-line arguments
1.123     anton    9557: through @code{next-arg}:
1.121     anton    9558: 
1.123     anton    9559: doc-next-arg
1.121     anton    9560: 
1.123     anton    9561: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121     anton    9562: 
                   9563: @example
                   9564: : echo ( -- )
1.122     anton    9565:     begin
1.123     anton    9566:        next-arg 2dup 0 0 d<> while
                   9567:            type space
                   9568:     repeat
                   9569:     2drop ;
1.121     anton    9570: 
                   9571: echo cr bye
                   9572: @end example
                   9573: 
                   9574: This can be invoked with
                   9575: 
                   9576: @example
                   9577: gforth echo.fs hello world
                   9578: @end example
1.123     anton    9579: 
                   9580: and it will print
                   9581: 
                   9582: @example
                   9583: hello world
                   9584: @end example
                   9585: 
                   9586: The next lower level of dealing with the OS command line are the
                   9587: following words:
                   9588: 
                   9589: doc-arg
                   9590: doc-shift-args
                   9591: 
                   9592: Finally, at the lowest level Gforth provides the following words:
                   9593: 
                   9594: doc-argc
                   9595: doc-argv
1.121     anton    9596: 
1.78      anton    9597: @c -------------------------------------------------------------
1.126     pazsan   9598: @node Locals, Structures, OS command line arguments, Words
1.78      anton    9599: @section Locals
                   9600: @cindex locals
                   9601: 
                   9602: Local variables can make Forth programming more enjoyable and Forth
                   9603: programs easier to read. Unfortunately, the locals of ANS Forth are
                   9604: laden with restrictions. Therefore, we provide not only the ANS Forth
                   9605: locals wordset, but also our own, more powerful locals wordset (we
                   9606: implemented the ANS Forth locals wordset through our locals wordset).
1.44      crook    9607: 
1.78      anton    9608: The ideas in this section have also been published in M. Anton Ertl,
                   9609: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
                   9610: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12      anton    9611: 
                   9612: @menu
1.78      anton    9613: * Gforth locals::               
                   9614: * ANS Forth locals::            
1.5       anton    9615: @end menu
                   9616: 
1.78      anton    9617: @node Gforth locals, ANS Forth locals, Locals, Locals
                   9618: @subsection Gforth locals
                   9619: @cindex Gforth locals
                   9620: @cindex locals, Gforth style
1.5       anton    9621: 
1.78      anton    9622: Locals can be defined with
1.44      crook    9623: 
1.78      anton    9624: @example
                   9625: @{ local1 local2 ... -- comment @}
                   9626: @end example
                   9627: or
                   9628: @example
                   9629: @{ local1 local2 ... @}
                   9630: @end example
1.5       anton    9631: 
1.78      anton    9632: E.g.,
                   9633: @example
                   9634: : max @{ n1 n2 -- n3 @}
                   9635:  n1 n2 > if
                   9636:    n1
                   9637:  else
                   9638:    n2
                   9639:  endif ;
                   9640: @end example
1.44      crook    9641: 
1.78      anton    9642: The similarity of locals definitions with stack comments is intended. A
                   9643: locals definition often replaces the stack comment of a word. The order
                   9644: of the locals corresponds to the order in a stack comment and everything
                   9645: after the @code{--} is really a comment.
1.77      anton    9646: 
1.78      anton    9647: This similarity has one disadvantage: It is too easy to confuse locals
                   9648: declarations with stack comments, causing bugs and making them hard to
                   9649: find. However, this problem can be avoided by appropriate coding
                   9650: conventions: Do not use both notations in the same program. If you do,
                   9651: they should be distinguished using additional means, e.g. by position.
1.77      anton    9652: 
1.78      anton    9653: @cindex types of locals
                   9654: @cindex locals types
                   9655: The name of the local may be preceded by a type specifier, e.g.,
                   9656: @code{F:} for a floating point value:
1.5       anton    9657: 
1.78      anton    9658: @example
                   9659: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   9660: \ complex multiplication
                   9661:  Ar Br f* Ai Bi f* f-
                   9662:  Ar Bi f* Ai Br f* f+ ;
                   9663: @end example
1.44      crook    9664: 
1.78      anton    9665: @cindex flavours of locals
                   9666: @cindex locals flavours
                   9667: @cindex value-flavoured locals
                   9668: @cindex variable-flavoured locals
                   9669: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   9670: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   9671: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   9672: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   9673: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   9674: produces its address (which becomes invalid when the variable's scope is
                   9675: left). E.g., the standard word @code{emit} can be defined in terms of
                   9676: @code{type} like this:
1.5       anton    9677: 
1.78      anton    9678: @example
                   9679: : emit @{ C^ char* -- @}
                   9680:     char* 1 type ;
                   9681: @end example
1.5       anton    9682: 
1.78      anton    9683: @cindex default type of locals
                   9684: @cindex locals, default type
                   9685: A local without type specifier is a @code{W:} local. Both flavours of
                   9686: locals are initialized with values from the data or FP stack.
1.44      crook    9687: 
1.78      anton    9688: Currently there is no way to define locals with user-defined data
                   9689: structures, but we are working on it.
1.5       anton    9690: 
1.78      anton    9691: Gforth allows defining locals everywhere in a colon definition. This
                   9692: poses the following questions:
1.5       anton    9693: 
1.78      anton    9694: @menu
                   9695: * Where are locals visible by name?::  
                   9696: * How long do locals live?::    
                   9697: * Locals programming style::    
                   9698: * Locals implementation::       
                   9699: @end menu
1.44      crook    9700: 
1.78      anton    9701: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   9702: @subsubsection Where are locals visible by name?
                   9703: @cindex locals visibility
                   9704: @cindex visibility of locals
                   9705: @cindex scope of locals
1.5       anton    9706: 
1.78      anton    9707: Basically, the answer is that locals are visible where you would expect
                   9708: it in block-structured languages, and sometimes a little longer. If you
                   9709: want to restrict the scope of a local, enclose its definition in
                   9710: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    9711: 
                   9712: 
1.78      anton    9713: doc-scope
                   9714: doc-endscope
1.5       anton    9715: 
                   9716: 
1.78      anton    9717: These words behave like control structure words, so you can use them
                   9718: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   9719: arbitrary ways.
1.77      anton    9720: 
1.78      anton    9721: If you want a more exact answer to the visibility question, here's the
                   9722: basic principle: A local is visible in all places that can only be
                   9723: reached through the definition of the local@footnote{In compiler
                   9724: construction terminology, all places dominated by the definition of the
                   9725: local.}. In other words, it is not visible in places that can be reached
                   9726: without going through the definition of the local. E.g., locals defined
                   9727: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   9728: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   9729: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77      anton    9730: 
1.78      anton    9731: The reasoning behind this solution is: We want to have the locals
                   9732: visible as long as it is meaningful. The user can always make the
                   9733: visibility shorter by using explicit scoping. In a place that can
                   9734: only be reached through the definition of a local, the meaning of a
                   9735: local name is clear. In other places it is not: How is the local
                   9736: initialized at the control flow path that does not contain the
                   9737: definition? Which local is meant, if the same name is defined twice in
                   9738: two independent control flow paths?
1.77      anton    9739: 
1.78      anton    9740: This should be enough detail for nearly all users, so you can skip the
                   9741: rest of this section. If you really must know all the gory details and
                   9742: options, read on.
1.77      anton    9743: 
1.78      anton    9744: In order to implement this rule, the compiler has to know which places
                   9745: are unreachable. It knows this automatically after @code{AHEAD},
                   9746: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   9747: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   9748: compiler that the control flow never reaches that place. If
                   9749: @code{UNREACHABLE} is not used where it could, the only consequence is
                   9750: that the visibility of some locals is more limited than the rule above
                   9751: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   9752: lie to the compiler), buggy code will be produced.
1.77      anton    9753: 
1.5       anton    9754: 
1.78      anton    9755: doc-unreachable
1.5       anton    9756: 
1.23      crook    9757: 
1.78      anton    9758: Another problem with this rule is that at @code{BEGIN}, the compiler
                   9759: does not know which locals will be visible on the incoming
                   9760: back-edge. All problems discussed in the following are due to this
                   9761: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   9762: loops as examples; the discussion also applies to @code{?DO} and other
                   9763: loops). Perhaps the most insidious example is:
1.26      crook    9764: @example
1.78      anton    9765: AHEAD
                   9766: BEGIN
                   9767:   x
                   9768: [ 1 CS-ROLL ] THEN
                   9769:   @{ x @}
                   9770:   ...
                   9771: UNTIL
1.26      crook    9772: @end example
1.23      crook    9773: 
1.78      anton    9774: This should be legal according to the visibility rule. The use of
                   9775: @code{x} can only be reached through the definition; but that appears
                   9776: textually below the use.
                   9777: 
                   9778: From this example it is clear that the visibility rules cannot be fully
                   9779: implemented without major headaches. Our implementation treats common
                   9780: cases as advertised and the exceptions are treated in a safe way: The
                   9781: compiler makes a reasonable guess about the locals visible after a
                   9782: @code{BEGIN}; if it is too pessimistic, the
                   9783: user will get a spurious error about the local not being defined; if the
                   9784: compiler is too optimistic, it will notice this later and issue a
                   9785: warning. In the case above the compiler would complain about @code{x}
                   9786: being undefined at its use. You can see from the obscure examples in
                   9787: this section that it takes quite unusual control structures to get the
                   9788: compiler into trouble, and even then it will often do fine.
1.23      crook    9789: 
1.78      anton    9790: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   9791: is that all locals visible before the @code{BEGIN} will also be
                   9792: visible after the @code{BEGIN}. This guess is valid for all loops that
                   9793: are entered only through the @code{BEGIN}, in particular, for normal
                   9794: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   9795: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   9796: compiler. When the branch to the @code{BEGIN} is finally generated by
                   9797: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   9798: warns the user if it was too optimistic:
1.26      crook    9799: @example
1.78      anton    9800: IF
                   9801:   @{ x @}
                   9802: BEGIN
                   9803:   \ x ? 
                   9804: [ 1 cs-roll ] THEN
                   9805:   ...
                   9806: UNTIL
1.26      crook    9807: @end example
1.23      crook    9808: 
1.78      anton    9809: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   9810: optimistically assumes that it lives until the @code{THEN}. It notices
                   9811: this difference when it compiles the @code{UNTIL} and issues a
                   9812: warning. The user can avoid the warning, and make sure that @code{x}
                   9813: is not used in the wrong area by using explicit scoping:
                   9814: @example
                   9815: IF
                   9816:   SCOPE
                   9817:   @{ x @}
                   9818:   ENDSCOPE
                   9819: BEGIN
                   9820: [ 1 cs-roll ] THEN
                   9821:   ...
                   9822: UNTIL
                   9823: @end example
1.23      crook    9824: 
1.78      anton    9825: Since the guess is optimistic, there will be no spurious error messages
                   9826: about undefined locals.
1.44      crook    9827: 
1.78      anton    9828: If the @code{BEGIN} is not reachable from above (e.g., after
                   9829: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   9830: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   9831: defined later. Therefore, the compiler assumes that no locals are
                   9832: visible after the @code{BEGIN}. However, the user can use
                   9833: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   9834: visible at the BEGIN as at the point where the top control-flow stack
                   9835: item was created.
1.23      crook    9836: 
1.44      crook    9837: 
1.78      anton    9838: doc-assume-live
1.26      crook    9839: 
1.23      crook    9840: 
1.78      anton    9841: @noindent
                   9842: E.g.,
                   9843: @example
                   9844: @{ x @}
                   9845: AHEAD
                   9846: ASSUME-LIVE
                   9847: BEGIN
                   9848:   x
                   9849: [ 1 CS-ROLL ] THEN
                   9850:   ...
                   9851: UNTIL
                   9852: @end example
1.44      crook    9853: 
1.78      anton    9854: Other cases where the locals are defined before the @code{BEGIN} can be
                   9855: handled by inserting an appropriate @code{CS-ROLL} before the
                   9856: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   9857: behind the @code{ASSUME-LIVE}).
1.23      crook    9858: 
1.78      anton    9859: Cases where locals are defined after the @code{BEGIN} (but should be
                   9860: visible immediately after the @code{BEGIN}) can only be handled by
                   9861: rearranging the loop. E.g., the ``most insidious'' example above can be
                   9862: arranged into:
                   9863: @example
                   9864: BEGIN
                   9865:   @{ x @}
                   9866:   ... 0=
                   9867: WHILE
                   9868:   x
                   9869: REPEAT
                   9870: @end example
1.44      crook    9871: 
1.78      anton    9872: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
                   9873: @subsubsection How long do locals live?
                   9874: @cindex locals lifetime
                   9875: @cindex lifetime of locals
1.23      crook    9876: 
1.78      anton    9877: The right answer for the lifetime question would be: A local lives at
                   9878: least as long as it can be accessed. For a value-flavoured local this
                   9879: means: until the end of its visibility. However, a variable-flavoured
                   9880: local could be accessed through its address far beyond its visibility
                   9881: scope. Ultimately, this would mean that such locals would have to be
                   9882: garbage collected. Since this entails un-Forth-like implementation
                   9883: complexities, I adopted the same cowardly solution as some other
                   9884: languages (e.g., C): The local lives only as long as it is visible;
                   9885: afterwards its address is invalid (and programs that access it
                   9886: afterwards are erroneous).
1.23      crook    9887: 
1.78      anton    9888: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
                   9889: @subsubsection Locals programming style
                   9890: @cindex locals programming style
                   9891: @cindex programming style, locals
1.23      crook    9892: 
1.78      anton    9893: The freedom to define locals anywhere has the potential to change
                   9894: programming styles dramatically. In particular, the need to use the
                   9895: return stack for intermediate storage vanishes. Moreover, all stack
                   9896: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   9897: determined arguments) can be eliminated: If the stack items are in the
                   9898: wrong order, just write a locals definition for all of them; then
                   9899: write the items in the order you want.
1.23      crook    9900: 
1.78      anton    9901: This seems a little far-fetched and eliminating stack manipulations is
                   9902: unlikely to become a conscious programming objective. Still, the number
                   9903: of stack manipulations will be reduced dramatically if local variables
                   9904: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
                   9905: a traditional implementation of @code{max}).
1.23      crook    9906: 
1.78      anton    9907: This shows one potential benefit of locals: making Forth programs more
                   9908: readable. Of course, this benefit will only be realized if the
                   9909: programmers continue to honour the principle of factoring instead of
                   9910: using the added latitude to make the words longer.
1.23      crook    9911: 
1.78      anton    9912: @cindex single-assignment style for locals
                   9913: Using @code{TO} can and should be avoided.  Without @code{TO},
                   9914: every value-flavoured local has only a single assignment and many
                   9915: advantages of functional languages apply to Forth. I.e., programs are
                   9916: easier to analyse, to optimize and to read: It is clear from the
                   9917: definition what the local stands for, it does not turn into something
                   9918: different later.
1.23      crook    9919: 
1.78      anton    9920: E.g., a definition using @code{TO} might look like this:
                   9921: @example
                   9922: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9923:  u1 u2 min 0
                   9924:  ?do
                   9925:    addr1 c@@ addr2 c@@ -
                   9926:    ?dup-if
                   9927:      unloop exit
                   9928:    then
                   9929:    addr1 char+ TO addr1
                   9930:    addr2 char+ TO addr2
                   9931:  loop
                   9932:  u1 u2 - ;
1.26      crook    9933: @end example
1.78      anton    9934: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   9935: every loop iteration. @code{strcmp} is a typical example of the
                   9936: readability problems of using @code{TO}. When you start reading
                   9937: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   9938: string. Only near the end of the loop you realize that it is something
                   9939: else.
1.23      crook    9940: 
1.78      anton    9941: This can be avoided by defining two locals at the start of the loop that
                   9942: are initialized with the right value for the current iteration.
                   9943: @example
                   9944: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9945:  addr1 addr2
                   9946:  u1 u2 min 0 
                   9947:  ?do @{ s1 s2 @}
                   9948:    s1 c@@ s2 c@@ -
                   9949:    ?dup-if
                   9950:      unloop exit
                   9951:    then
                   9952:    s1 char+ s2 char+
                   9953:  loop
                   9954:  2drop
                   9955:  u1 u2 - ;
                   9956: @end example
                   9957: Here it is clear from the start that @code{s1} has a different value
                   9958: in every loop iteration.
1.23      crook    9959: 
1.78      anton    9960: @node Locals implementation,  , Locals programming style, Gforth locals
                   9961: @subsubsection Locals implementation
                   9962: @cindex locals implementation
                   9963: @cindex implementation of locals
1.23      crook    9964: 
1.78      anton    9965: @cindex locals stack
                   9966: Gforth uses an extra locals stack. The most compelling reason for
                   9967: this is that the return stack is not float-aligned; using an extra stack
                   9968: also eliminates the problems and restrictions of using the return stack
                   9969: as locals stack. Like the other stacks, the locals stack grows toward
                   9970: lower addresses. A few primitives allow an efficient implementation:
                   9971: 
                   9972: 
                   9973: doc-@local#
                   9974: doc-f@local#
                   9975: doc-laddr#
                   9976: doc-lp+!#
                   9977: doc-lp!
                   9978: doc->l
                   9979: doc-f>l
                   9980: 
                   9981: 
                   9982: In addition to these primitives, some specializations of these
                   9983: primitives for commonly occurring inline arguments are provided for
                   9984: efficiency reasons, e.g., @code{@@local0} as specialization of
                   9985: @code{@@local#} for the inline argument 0. The following compiling words
                   9986: compile the right specialized version, or the general version, as
                   9987: appropriate:
1.23      crook    9988: 
1.5       anton    9989: 
1.107     dvdkhlng 9990: @c doc-compile-@local
                   9991: @c doc-compile-f@local
1.78      anton    9992: doc-compile-lp+!
1.5       anton    9993: 
                   9994: 
1.78      anton    9995: Combinations of conditional branches and @code{lp+!#} like
                   9996: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   9997: is taken) are provided for efficiency and correctness in loops.
1.5       anton    9998: 
1.78      anton    9999: A special area in the dictionary space is reserved for keeping the
                   10000: local variable names. @code{@{} switches the dictionary pointer to this
                   10001: area and @code{@}} switches it back and generates the locals
                   10002: initializing code. @code{W:} etc.@ are normal defining words. This
                   10003: special area is cleared at the start of every colon definition.
1.5       anton    10004: 
1.78      anton    10005: @cindex word list for defining locals
                   10006: A special feature of Gforth's dictionary is used to implement the
                   10007: definition of locals without type specifiers: every word list (aka
                   10008: vocabulary) has its own methods for searching
                   10009: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   10010: with a special search method: When it is searched for a word, it
                   10011: actually creates that word using @code{W:}. @code{@{} changes the search
                   10012: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   10013: and then the word list for defining locals without type specifiers.
1.5       anton    10014: 
1.78      anton    10015: The lifetime rules support a stack discipline within a colon
                   10016: definition: The lifetime of a local is either nested with other locals
                   10017: lifetimes or it does not overlap them.
1.23      crook    10018: 
1.78      anton    10019: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   10020: pointer manipulation is generated. Between control structure words
                   10021: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   10022: is the simplest of the other three control flow words. It has to
                   10023: restore the locals stack depth of the corresponding @code{BEGIN}
                   10024: before branching. The code looks like this:
                   10025: @format
                   10026: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   10027: @code{branch} <begin>
                   10028: @end format
1.26      crook    10029: 
1.78      anton    10030: @code{UNTIL} is a little more complicated: If it branches back, it
                   10031: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   10032: the locals stack must not be changed. The compiler generates the
                   10033: following code:
                   10034: @format
                   10035: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   10036: @end format
                   10037: The locals stack pointer is only adjusted if the branch is taken.
1.44      crook    10038: 
1.78      anton    10039: @code{THEN} can produce somewhat inefficient code:
                   10040: @format
                   10041: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   10042: <orig target>:
                   10043: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   10044: @end format
                   10045: The second @code{lp+!#} adjusts the locals stack pointer from the
                   10046: level at the @i{orig} point to the level after the @code{THEN}. The
                   10047: first @code{lp+!#} adjusts the locals stack pointer from the current
                   10048: level to the level at the orig point, so the complete effect is an
                   10049: adjustment from the current level to the right level after the
                   10050: @code{THEN}.
1.26      crook    10051: 
1.78      anton    10052: @cindex locals information on the control-flow stack
                   10053: @cindex control-flow stack items, locals information
                   10054: In a conventional Forth implementation a dest control-flow stack entry
                   10055: is just the target address and an orig entry is just the address to be
                   10056: patched. Our locals implementation adds a word list to every orig or dest
                   10057: item. It is the list of locals visible (or assumed visible) at the point
                   10058: described by the entry. Our implementation also adds a tag to identify
                   10059: the kind of entry, in particular to differentiate between live and dead
                   10060: (reachable and unreachable) orig entries.
1.26      crook    10061: 
1.78      anton    10062: A few unusual operations have to be performed on locals word lists:
1.44      crook    10063: 
1.5       anton    10064: 
1.78      anton    10065: doc-common-list
                   10066: doc-sub-list?
                   10067: doc-list-size
1.52      anton    10068: 
                   10069: 
1.78      anton    10070: Several features of our locals word list implementation make these
                   10071: operations easy to implement: The locals word lists are organised as
                   10072: linked lists; the tails of these lists are shared, if the lists
                   10073: contain some of the same locals; and the address of a name is greater
                   10074: than the address of the names behind it in the list.
1.5       anton    10075: 
1.78      anton    10076: Another important implementation detail is the variable
                   10077: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   10078: determine if they can be reached directly or only through the branch
                   10079: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   10080: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   10081: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5       anton    10082: 
1.78      anton    10083: Counted loops are similar to other loops in most respects, but
                   10084: @code{LEAVE} requires special attention: It performs basically the same
                   10085: service as @code{AHEAD}, but it does not create a control-flow stack
                   10086: entry. Therefore the information has to be stored elsewhere;
                   10087: traditionally, the information was stored in the target fields of the
                   10088: branches created by the @code{LEAVE}s, by organizing these fields into a
                   10089: linked list. Unfortunately, this clever trick does not provide enough
                   10090: space for storing our extended control flow information. Therefore, we
                   10091: introduce another stack, the leave stack. It contains the control-flow
                   10092: stack entries for all unresolved @code{LEAVE}s.
1.44      crook    10093: 
1.78      anton    10094: Local names are kept until the end of the colon definition, even if
                   10095: they are no longer visible in any control-flow path. In a few cases
                   10096: this may lead to increased space needs for the locals name area, but
                   10097: usually less than reclaiming this space would cost in code size.
1.5       anton    10098: 
1.44      crook    10099: 
1.78      anton    10100: @node ANS Forth locals,  , Gforth locals, Locals
                   10101: @subsection ANS Forth locals
                   10102: @cindex locals, ANS Forth style
1.5       anton    10103: 
1.78      anton    10104: The ANS Forth locals wordset does not define a syntax for locals, but
                   10105: words that make it possible to define various syntaxes. One of the
                   10106: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   10107: wordset, i.e.:
1.29      crook    10108: 
                   10109: @example
1.78      anton    10110: @{ local1 local2 ... -- comment @}
                   10111: @end example
                   10112: @noindent
                   10113: or
                   10114: @example
                   10115: @{ local1 local2 ... @}
1.29      crook    10116: @end example
                   10117: 
1.78      anton    10118: The order of the locals corresponds to the order in a stack comment. The
                   10119: restrictions are:
1.5       anton    10120: 
1.78      anton    10121: @itemize @bullet
                   10122: @item
                   10123: Locals can only be cell-sized values (no type specifiers are allowed).
                   10124: @item
                   10125: Locals can be defined only outside control structures.
                   10126: @item
                   10127: Locals can interfere with explicit usage of the return stack. For the
                   10128: exact (and long) rules, see the standard. If you don't use return stack
                   10129: accessing words in a definition using locals, you will be all right. The
                   10130: purpose of this rule is to make locals implementation on the return
                   10131: stack easier.
                   10132: @item
                   10133: The whole definition must be in one line.
                   10134: @end itemize
1.5       anton    10135: 
1.78      anton    10136: Locals defined in ANS Forth behave like @code{VALUE}s
                   10137: (@pxref{Values}). I.e., they are initialized from the stack. Using their
                   10138: name produces their value. Their value can be changed using @code{TO}.
1.77      anton    10139: 
1.78      anton    10140: Since the syntax above is supported by Gforth directly, you need not do
                   10141: anything to use it. If you want to port a program using this syntax to
                   10142: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   10143: syntax on the other system.
1.5       anton    10144: 
1.78      anton    10145: Note that a syntax shown in the standard, section A.13 looks
                   10146: similar, but is quite different in having the order of locals
                   10147: reversed. Beware!
1.5       anton    10148: 
1.78      anton    10149: The ANS Forth locals wordset itself consists of one word:
1.5       anton    10150: 
1.78      anton    10151: doc-(local)
1.5       anton    10152: 
1.78      anton    10153: The ANS Forth locals extension wordset defines a syntax using
                   10154: @code{locals|}, but it is so awful that we strongly recommend not to use
                   10155: it. We have implemented this syntax to make porting to Gforth easy, but
                   10156: do not document it here. The problem with this syntax is that the locals
                   10157: are defined in an order reversed with respect to the standard stack
                   10158: comment notation, making programs harder to read, and easier to misread
                   10159: and miswrite. The only merit of this syntax is that it is easy to
                   10160: implement using the ANS Forth locals wordset.
1.53      anton    10161: 
                   10162: 
1.78      anton    10163: @c ----------------------------------------------------------
                   10164: @node Structures, Object-oriented Forth, Locals, Words
                   10165: @section  Structures
                   10166: @cindex structures
                   10167: @cindex records
1.53      anton    10168: 
1.78      anton    10169: This section presents the structure package that comes with Gforth. A
                   10170: version of the package implemented in ANS Forth is available in
                   10171: @file{compat/struct.fs}. This package was inspired by a posting on
                   10172: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   10173: possibly John Hayes). A version of this section has been published in
                   10174: M. Anton Ertl,
                   10175: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
                   10176: Another Forth Structures Package}, Forth Dimensions 19(3), pages
                   10177: 13--16. Marcel Hendrix provided helpful comments.
1.53      anton    10178: 
1.78      anton    10179: @menu
                   10180: * Why explicit structure support?::  
                   10181: * Structure Usage::             
                   10182: * Structure Naming Convention::  
                   10183: * Structure Implementation::    
                   10184: * Structure Glossary::          
1.183     anton    10185: * Forth200x Structures::        
1.78      anton    10186: @end menu
1.55      anton    10187: 
1.78      anton    10188: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   10189: @subsection Why explicit structure support?
1.53      anton    10190: 
1.78      anton    10191: @cindex address arithmetic for structures
                   10192: @cindex structures using address arithmetic
                   10193: If we want to use a structure containing several fields, we could simply
                   10194: reserve memory for it, and access the fields using address arithmetic
                   10195: (@pxref{Address arithmetic}). As an example, consider a structure with
                   10196: the following fields
1.57      anton    10197: 
1.78      anton    10198: @table @code
                   10199: @item a
                   10200: is a float
                   10201: @item b
                   10202: is a cell
                   10203: @item c
                   10204: is a float
                   10205: @end table
1.57      anton    10206: 
1.78      anton    10207: Given the (float-aligned) base address of the structure we get the
                   10208: address of the field
1.52      anton    10209: 
1.78      anton    10210: @table @code
                   10211: @item a
                   10212: without doing anything further.
                   10213: @item b
                   10214: with @code{float+}
                   10215: @item c
                   10216: with @code{float+ cell+ faligned}
                   10217: @end table
1.52      anton    10218: 
1.78      anton    10219: It is easy to see that this can become quite tiring. 
1.52      anton    10220: 
1.78      anton    10221: Moreover, it is not very readable, because seeing a
                   10222: @code{cell+} tells us neither which kind of structure is
                   10223: accessed nor what field is accessed; we have to somehow infer the kind
                   10224: of structure, and then look up in the documentation, which field of
                   10225: that structure corresponds to that offset.
1.53      anton    10226: 
1.78      anton    10227: Finally, this kind of address arithmetic also causes maintenance
                   10228: troubles: If you add or delete a field somewhere in the middle of the
                   10229: structure, you have to find and change all computations for the fields
                   10230: afterwards.
1.52      anton    10231: 
1.78      anton    10232: So, instead of using @code{cell+} and friends directly, how
                   10233: about storing the offsets in constants:
1.52      anton    10234: 
1.78      anton    10235: @example
                   10236: 0 constant a-offset
                   10237: 0 float+ constant b-offset
                   10238: 0 float+ cell+ faligned c-offset
                   10239: @end example
1.64      pazsan   10240: 
1.78      anton    10241: Now we can get the address of field @code{x} with @code{x-offset
                   10242: +}. This is much better in all respects. Of course, you still
                   10243: have to change all later offset definitions if you add a field. You can
                   10244: fix this by declaring the offsets in the following way:
1.57      anton    10245: 
1.78      anton    10246: @example
                   10247: 0 constant a-offset
                   10248: a-offset float+ constant b-offset
                   10249: b-offset cell+ faligned constant c-offset
                   10250: @end example
1.57      anton    10251: 
1.78      anton    10252: Since we always use the offsets with @code{+}, we could use a defining
                   10253: word @code{cfield} that includes the @code{+} in the action of the
                   10254: defined word:
1.64      pazsan   10255: 
1.78      anton    10256: @example
                   10257: : cfield ( n "name" -- )
                   10258:     create ,
                   10259: does> ( name execution: addr1 -- addr2 )
                   10260:     @@ + ;
1.64      pazsan   10261: 
1.78      anton    10262: 0 cfield a
                   10263: 0 a float+ cfield b
                   10264: 0 b cell+ faligned cfield c
                   10265: @end example
1.64      pazsan   10266: 
1.78      anton    10267: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64      pazsan   10268: 
1.78      anton    10269: The structure field words now can be used quite nicely. However,
                   10270: their definition is still a bit cumbersome: We have to repeat the
                   10271: name, the information about size and alignment is distributed before
                   10272: and after the field definitions etc.  The structure package presented
                   10273: here addresses these problems.
1.64      pazsan   10274: 
1.78      anton    10275: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   10276: @subsection Structure Usage
                   10277: @cindex structure usage
1.57      anton    10278: 
1.78      anton    10279: @cindex @code{field} usage
                   10280: @cindex @code{struct} usage
                   10281: @cindex @code{end-struct} usage
                   10282: You can define a structure for a (data-less) linked list with:
1.57      anton    10283: @example
1.78      anton    10284: struct
                   10285:     cell% field list-next
                   10286: end-struct list%
1.57      anton    10287: @end example
                   10288: 
1.78      anton    10289: With the address of the list node on the stack, you can compute the
                   10290: address of the field that contains the address of the next node with
                   10291: @code{list-next}. E.g., you can determine the length of a list
                   10292: with:
1.57      anton    10293: 
                   10294: @example
1.78      anton    10295: : list-length ( list -- n )
                   10296: \ "list" is a pointer to the first element of a linked list
                   10297: \ "n" is the length of the list
                   10298:     0 BEGIN ( list1 n1 )
                   10299:         over
                   10300:     WHILE ( list1 n1 )
                   10301:         1+ swap list-next @@ swap
                   10302:     REPEAT
                   10303:     nip ;
1.57      anton    10304: @end example
                   10305: 
1.78      anton    10306: You can reserve memory for a list node in the dictionary with
                   10307: @code{list% %allot}, which leaves the address of the list node on the
                   10308: stack. For the equivalent allocation on the heap you can use @code{list%
                   10309: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   10310: use @code{list% %allocate}). You can get the the size of a list
                   10311: node with @code{list% %size} and its alignment with @code{list%
                   10312: %alignment}.
                   10313: 
                   10314: Note that in ANS Forth the body of a @code{create}d word is
                   10315: @code{aligned} but not necessarily @code{faligned};
                   10316: therefore, if you do a:
1.57      anton    10317: 
                   10318: @example
1.78      anton    10319: create @emph{name} foo% %allot drop
1.57      anton    10320: @end example
                   10321: 
1.78      anton    10322: @noindent
                   10323: then the memory alloted for @code{foo%} is guaranteed to start at the
                   10324: body of @code{@emph{name}} only if @code{foo%} contains only character,
                   10325: cell and double fields.  Therefore, if your structure contains floats,
                   10326: better use
1.57      anton    10327: 
                   10328: @example
1.78      anton    10329: foo% %allot constant @emph{name}
1.57      anton    10330: @end example
                   10331: 
1.78      anton    10332: @cindex structures containing structures
                   10333: You can include a structure @code{foo%} as a field of
                   10334: another structure, like this:
1.65      anton    10335: @example
1.78      anton    10336: struct
                   10337: ...
                   10338:     foo% field ...
                   10339: ...
                   10340: end-struct ...
1.65      anton    10341: @end example
1.52      anton    10342: 
1.78      anton    10343: @cindex structure extension
                   10344: @cindex extended records
                   10345: Instead of starting with an empty structure, you can extend an
                   10346: existing structure. E.g., a plain linked list without data, as defined
                   10347: above, is hardly useful; You can extend it to a linked list of integers,
                   10348: like this:@footnote{This feature is also known as @emph{extended
                   10349: records}. It is the main innovation in the Oberon language; in other
                   10350: words, adding this feature to Modula-2 led Wirth to create a new
                   10351: language, write a new compiler etc.  Adding this feature to Forth just
                   10352: required a few lines of code.}
1.52      anton    10353: 
1.78      anton    10354: @example
                   10355: list%
                   10356:     cell% field intlist-int
                   10357: end-struct intlist%
                   10358: @end example
1.55      anton    10359: 
1.78      anton    10360: @code{intlist%} is a structure with two fields:
                   10361: @code{list-next} and @code{intlist-int}.
1.55      anton    10362: 
1.78      anton    10363: @cindex structures containing arrays
                   10364: You can specify an array type containing @emph{n} elements of
                   10365: type @code{foo%} like this:
1.55      anton    10366: 
                   10367: @example
1.78      anton    10368: foo% @emph{n} *
1.56      anton    10369: @end example
1.55      anton    10370: 
1.78      anton    10371: You can use this array type in any place where you can use a normal
                   10372: type, e.g., when defining a @code{field}, or with
                   10373: @code{%allot}.
                   10374: 
                   10375: @cindex first field optimization
                   10376: The first field is at the base address of a structure and the word for
                   10377: this field (e.g., @code{list-next}) actually does not change the address
                   10378: on the stack. You may be tempted to leave it away in the interest of
                   10379: run-time and space efficiency. This is not necessary, because the
                   10380: structure package optimizes this case: If you compile a first-field
                   10381: words, no code is generated. So, in the interest of readability and
                   10382: maintainability you should include the word for the field when accessing
                   10383: the field.
1.52      anton    10384: 
                   10385: 
1.78      anton    10386: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   10387: @subsection Structure Naming Convention
                   10388: @cindex structure naming convention
1.52      anton    10389: 
1.78      anton    10390: The field names that come to (my) mind are often quite generic, and,
                   10391: if used, would cause frequent name clashes. E.g., many structures
                   10392: probably contain a @code{counter} field. The structure names
                   10393: that come to (my) mind are often also the logical choice for the names
                   10394: of words that create such a structure.
1.52      anton    10395: 
1.78      anton    10396: Therefore, I have adopted the following naming conventions: 
1.52      anton    10397: 
1.78      anton    10398: @itemize @bullet
                   10399: @cindex field naming convention
                   10400: @item
                   10401: The names of fields are of the form
                   10402: @code{@emph{struct}-@emph{field}}, where
                   10403: @code{@emph{struct}} is the basic name of the structure, and
                   10404: @code{@emph{field}} is the basic name of the field. You can
                   10405: think of field words as converting the (address of the)
                   10406: structure into the (address of the) field.
1.52      anton    10407: 
1.78      anton    10408: @cindex structure naming convention
                   10409: @item
                   10410: The names of structures are of the form
                   10411: @code{@emph{struct}%}, where
                   10412: @code{@emph{struct}} is the basic name of the structure.
                   10413: @end itemize
1.52      anton    10414: 
1.78      anton    10415: This naming convention does not work that well for fields of extended
                   10416: structures; e.g., the integer list structure has a field
                   10417: @code{intlist-int}, but has @code{list-next}, not
                   10418: @code{intlist-next}.
1.53      anton    10419: 
1.78      anton    10420: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   10421: @subsection Structure Implementation
                   10422: @cindex structure implementation
                   10423: @cindex implementation of structures
1.52      anton    10424: 
1.78      anton    10425: The central idea in the implementation is to pass the data about the
                   10426: structure being built on the stack, not in some global
                   10427: variable. Everything else falls into place naturally once this design
                   10428: decision is made.
1.53      anton    10429: 
1.78      anton    10430: The type description on the stack is of the form @emph{align
                   10431: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   10432: very simple.
1.53      anton    10433: 
1.78      anton    10434: @code{field} is a defining word that uses @code{Create}
                   10435: and @code{DOES>}. The body of the field contains the offset
                   10436: of the field, and the normal @code{DOES>} action is simply:
1.53      anton    10437: 
                   10438: @example
1.78      anton    10439: @@ +
1.53      anton    10440: @end example
                   10441: 
1.78      anton    10442: @noindent
                   10443: i.e., add the offset to the address, giving the stack effect
                   10444: @i{addr1 -- addr2} for a field.
                   10445: 
                   10446: @cindex first field optimization, implementation
                   10447: This simple structure is slightly complicated by the optimization
                   10448: for fields with offset 0, which requires a different
                   10449: @code{DOES>}-part (because we cannot rely on there being
                   10450: something on the stack if such a field is invoked during
                   10451: compilation). Therefore, we put the different @code{DOES>}-parts
                   10452: in separate words, and decide which one to invoke based on the
                   10453: offset. For a zero offset, the field is basically a noop; it is
                   10454: immediate, and therefore no code is generated when it is compiled.
1.53      anton    10455: 
1.183     anton    10456: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
1.78      anton    10457: @subsection Structure Glossary
                   10458: @cindex structure glossary
1.53      anton    10459: 
1.5       anton    10460: 
1.78      anton    10461: doc-%align
                   10462: doc-%alignment
                   10463: doc-%alloc
                   10464: doc-%allocate
                   10465: doc-%allot
                   10466: doc-cell%
                   10467: doc-char%
                   10468: doc-dfloat%
                   10469: doc-double%
                   10470: doc-end-struct
                   10471: doc-field
                   10472: doc-float%
                   10473: doc-naligned
                   10474: doc-sfloat%
                   10475: doc-%size
                   10476: doc-struct
1.54      anton    10477: 
                   10478: 
1.183     anton    10479: @node Forth200x Structures,  , Structure Glossary, Structures
                   10480: @subsection Forth200x Structures
                   10481: @cindex Structures in Forth200x
                   10482: 
                   10483: The Forth 200x standard defines a slightly less convenient form of
                   10484: structures.  In general (when using @code{field+}, you have to perform
                   10485: the alignment yourself, but there are a number of convenience words
                   10486: (e.g., @code{field:} that perform the alignment for you.
                   10487: 
                   10488: A typical usage example is:
                   10489: 
                   10490: @example
                   10491: 0
                   10492:   field:                   s-a
                   10493:   faligned 2 floats +field s-b
                   10494: constant s-struct
                   10495: @end example
                   10496: 
                   10497: An alternative way of writing this structure is:
                   10498: 
                   10499: @example
                   10500: begin-structure s-struct
                   10501:   field:                   s-a
                   10502:   faligned 2 floats +field s-b
                   10503: end-structure
                   10504: @end example
                   10505: 
                   10506: doc-begin-structure
                   10507: doc-end-structure
                   10508: doc-+field
                   10509: doc-cfield:
                   10510: doc-field:
                   10511: doc-2field:
                   10512: doc-ffield:
                   10513: doc-sffield:
                   10514: doc-dffield:
                   10515: 
1.26      crook    10516: @c -------------------------------------------------------------
1.78      anton    10517: @node Object-oriented Forth, Programming Tools, Structures, Words
                   10518: @section Object-oriented Forth
                   10519: 
                   10520: Gforth comes with three packages for object-oriented programming:
                   10521: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   10522: is preloaded, so you have to @code{include} them before use. The most
                   10523: important differences between these packages (and others) are discussed
                   10524: in @ref{Comparison with other object models}. All packages are written
                   10525: in ANS Forth and can be used with any other ANS Forth.
1.5       anton    10526: 
1.78      anton    10527: @menu
                   10528: * Why object-oriented programming?::  
                   10529: * Object-Oriented Terminology::  
                   10530: * Objects::                     
                   10531: * OOF::                         
                   10532: * Mini-OOF::                    
                   10533: * Comparison with other object models::  
                   10534: @end menu
1.5       anton    10535: 
1.78      anton    10536: @c ----------------------------------------------------------------
                   10537: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
                   10538: @subsection Why object-oriented programming?
                   10539: @cindex object-oriented programming motivation
                   10540: @cindex motivation for object-oriented programming
1.44      crook    10541: 
1.78      anton    10542: Often we have to deal with several data structures (@emph{objects}),
                   10543: that have to be treated similarly in some respects, but differently in
                   10544: others. Graphical objects are the textbook example: circles, triangles,
                   10545: dinosaurs, icons, and others, and we may want to add more during program
                   10546: development. We want to apply some operations to any graphical object,
                   10547: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   10548: has to do something different for every kind of object.
                   10549: @comment TODO add some other operations eg perimeter, area
                   10550: @comment and tie in to concrete examples later..
1.5       anton    10551: 
1.78      anton    10552: We could implement @code{draw} as a big @code{CASE}
                   10553: control structure that executes the appropriate code depending on the
                   10554: kind of object to be drawn. This would be not be very elegant, and,
                   10555: moreover, we would have to change @code{draw} every time we add
                   10556: a new kind of graphical object (say, a spaceship).
1.44      crook    10557: 
1.78      anton    10558: What we would rather do is: When defining spaceships, we would tell
                   10559: the system: ``Here's how you @code{draw} a spaceship; you figure
                   10560: out the rest''.
1.5       anton    10561: 
1.78      anton    10562: This is the problem that all systems solve that (rightfully) call
                   10563: themselves object-oriented; the object-oriented packages presented here
                   10564: solve this problem (and not much else).
                   10565: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44      crook    10566: 
1.78      anton    10567: @c ------------------------------------------------------------------------
                   10568: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
                   10569: @subsection Object-Oriented Terminology
                   10570: @cindex object-oriented terminology
                   10571: @cindex terminology for object-oriented programming
1.5       anton    10572: 
1.78      anton    10573: This section is mainly for reference, so you don't have to understand
                   10574: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   10575: short:
1.44      crook    10576: 
1.78      anton    10577: @table @emph
                   10578: @cindex class
                   10579: @item class
                   10580: a data structure definition with some extras.
1.5       anton    10581: 
1.78      anton    10582: @cindex object
                   10583: @item object
                   10584: an instance of the data structure described by the class definition.
1.5       anton    10585: 
1.78      anton    10586: @cindex instance variables
                   10587: @item instance variables
                   10588: fields of the data structure.
1.5       anton    10589: 
1.78      anton    10590: @cindex selector
                   10591: @cindex method selector
                   10592: @cindex virtual function
                   10593: @item selector
                   10594: (or @emph{method selector}) a word (e.g.,
                   10595: @code{draw}) that performs an operation on a variety of data
                   10596: structures (classes). A selector describes @emph{what} operation to
                   10597: perform. In C++ terminology: a (pure) virtual function.
1.5       anton    10598: 
1.78      anton    10599: @cindex method
                   10600: @item method
                   10601: the concrete definition that performs the operation
                   10602: described by the selector for a specific class. A method specifies
                   10603: @emph{how} the operation is performed for a specific class.
1.5       anton    10604: 
1.78      anton    10605: @cindex selector invocation
                   10606: @cindex message send
                   10607: @cindex invoking a selector
                   10608: @item selector invocation
                   10609: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   10610: is used for determining which method is used. In Smalltalk terminology:
                   10611: a message (consisting of the selector and the other arguments) is sent
                   10612: to the object.
1.5       anton    10613: 
1.78      anton    10614: @cindex receiving object
                   10615: @item receiving object
                   10616: the object used for determining the method executed by a selector
                   10617: invocation. In the @file{objects.fs} model, it is the object that is on
                   10618: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   10619: the Smalltalk @emph{message} terminology.)
1.5       anton    10620: 
1.78      anton    10621: @cindex child class
                   10622: @cindex parent class
                   10623: @cindex inheritance
                   10624: @item child class
                   10625: a class that has (@emph{inherits}) all properties (instance variables,
                   10626: selectors, methods) from a @emph{parent class}. In Smalltalk
                   10627: terminology: The subclass inherits from the superclass. In C++
                   10628: terminology: The derived class inherits from the base class.
1.5       anton    10629: 
1.78      anton    10630: @end table
1.5       anton    10631: 
1.78      anton    10632: @c If you wonder about the message sending terminology, it comes from
                   10633: @c a time when each object had it's own task and objects communicated via
                   10634: @c message passing; eventually the Smalltalk developers realized that
                   10635: @c they can do most things through simple (indirect) calls. They kept the
                   10636: @c terminology.
1.5       anton    10637: 
1.78      anton    10638: @c --------------------------------------------------------------
                   10639: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   10640: @subsection The @file{objects.fs} model
                   10641: @cindex objects
                   10642: @cindex object-oriented programming
1.26      crook    10643: 
1.78      anton    10644: @cindex @file{objects.fs}
                   10645: @cindex @file{oof.fs}
1.26      crook    10646: 
1.78      anton    10647: This section describes the @file{objects.fs} package. This material also
                   10648: has been published in M. Anton Ertl,
                   10649: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
                   10650: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
                   10651: 37--43.
                   10652: @c McKewan's and Zsoter's packages
1.26      crook    10653: 
1.78      anton    10654: This section assumes that you have read @ref{Structures}.
1.5       anton    10655: 
1.78      anton    10656: The techniques on which this model is based have been used to implement
                   10657: the parser generator, Gray, and have also been used in Gforth for
                   10658: implementing the various flavours of word lists (hashed or not,
                   10659: case-sensitive or not, special-purpose word lists for locals etc.).
1.5       anton    10660: 
                   10661: 
1.26      crook    10662: @menu
1.78      anton    10663: * Properties of the Objects model::  
                   10664: * Basic Objects Usage::         
                   10665: * The Objects base class::      
                   10666: * Creating objects::            
                   10667: * Object-Oriented Programming Style::  
                   10668: * Class Binding::               
                   10669: * Method conveniences::         
                   10670: * Classes and Scoping::         
                   10671: * Dividing classes::            
                   10672: * Object Interfaces::           
                   10673: * Objects Implementation::      
                   10674: * Objects Glossary::            
1.26      crook    10675: @end menu
1.5       anton    10676: 
1.78      anton    10677: Marcel Hendrix provided helpful comments on this section.
1.5       anton    10678: 
1.78      anton    10679: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   10680: @subsubsection Properties of the @file{objects.fs} model
                   10681: @cindex @file{objects.fs} properties
1.5       anton    10682: 
1.78      anton    10683: @itemize @bullet
                   10684: @item
                   10685: It is straightforward to pass objects on the stack. Passing
                   10686: selectors on the stack is a little less convenient, but possible.
1.44      crook    10687: 
1.78      anton    10688: @item
                   10689: Objects are just data structures in memory, and are referenced by their
                   10690: address. You can create words for objects with normal defining words
                   10691: like @code{constant}. Likewise, there is no difference between instance
                   10692: variables that contain objects and those that contain other data.
1.5       anton    10693: 
1.78      anton    10694: @item
                   10695: Late binding is efficient and easy to use.
1.44      crook    10696: 
1.78      anton    10697: @item
                   10698: It avoids parsing, and thus avoids problems with state-smartness
                   10699: and reduced extensibility; for convenience there are a few parsing
                   10700: words, but they have non-parsing counterparts. There are also a few
                   10701: defining words that parse. This is hard to avoid, because all standard
                   10702: defining words parse (except @code{:noname}); however, such
                   10703: words are not as bad as many other parsing words, because they are not
                   10704: state-smart.
1.5       anton    10705: 
1.78      anton    10706: @item
                   10707: It does not try to incorporate everything. It does a few things and does
                   10708: them well (IMO). In particular, this model was not designed to support
                   10709: information hiding (although it has features that may help); you can use
                   10710: a separate package for achieving this.
1.5       anton    10711: 
1.78      anton    10712: @item
                   10713: It is layered; you don't have to learn and use all features to use this
                   10714: model. Only a few features are necessary (@pxref{Basic Objects Usage},
                   10715: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
                   10716: are optional and independent of each other.
1.5       anton    10717: 
1.78      anton    10718: @item
                   10719: An implementation in ANS Forth is available.
1.5       anton    10720: 
1.78      anton    10721: @end itemize
1.5       anton    10722: 
1.44      crook    10723: 
1.78      anton    10724: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   10725: @subsubsection Basic @file{objects.fs} Usage
                   10726: @cindex basic objects usage
                   10727: @cindex objects, basic usage
1.5       anton    10728: 
1.78      anton    10729: You can define a class for graphical objects like this:
1.44      crook    10730: 
1.78      anton    10731: @cindex @code{class} usage
                   10732: @cindex @code{end-class} usage
                   10733: @cindex @code{selector} usage
1.5       anton    10734: @example
1.78      anton    10735: object class \ "object" is the parent class
                   10736:   selector draw ( x y graphical -- )
                   10737: end-class graphical
                   10738: @end example
                   10739: 
                   10740: This code defines a class @code{graphical} with an
                   10741: operation @code{draw}.  We can perform the operation
                   10742: @code{draw} on any @code{graphical} object, e.g.:
                   10743: 
                   10744: @example
                   10745: 100 100 t-rex draw
1.26      crook    10746: @end example
1.5       anton    10747: 
1.78      anton    10748: @noindent
                   10749: where @code{t-rex} is a word (say, a constant) that produces a
                   10750: graphical object.
                   10751: 
                   10752: @comment TODO add a 2nd operation eg perimeter.. and use for
                   10753: @comment a concrete example
1.5       anton    10754: 
1.78      anton    10755: @cindex abstract class
                   10756: How do we create a graphical object? With the present definitions,
                   10757: we cannot create a useful graphical object. The class
                   10758: @code{graphical} describes graphical objects in general, but not
                   10759: any concrete graphical object type (C++ users would call it an
                   10760: @emph{abstract class}); e.g., there is no method for the selector
                   10761: @code{draw} in the class @code{graphical}.
1.5       anton    10762: 
1.78      anton    10763: For concrete graphical objects, we define child classes of the
                   10764: class @code{graphical}, e.g.:
1.5       anton    10765: 
1.78      anton    10766: @cindex @code{overrides} usage
                   10767: @cindex @code{field} usage in class definition
1.26      crook    10768: @example
1.78      anton    10769: graphical class \ "graphical" is the parent class
                   10770:   cell% field circle-radius
1.5       anton    10771: 
1.78      anton    10772: :noname ( x y circle -- )
                   10773:   circle-radius @@ draw-circle ;
                   10774: overrides draw
1.5       anton    10775: 
1.78      anton    10776: :noname ( n-radius circle -- )
                   10777:   circle-radius ! ;
                   10778: overrides construct
1.5       anton    10779: 
1.78      anton    10780: end-class circle
                   10781: @end example
1.44      crook    10782: 
1.78      anton    10783: Here we define a class @code{circle} as a child of @code{graphical},
                   10784: with field @code{circle-radius} (which behaves just like a field
                   10785: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   10786: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   10787: defined in @code{object}, the parent class of @code{graphical}).
1.5       anton    10788: 
1.78      anton    10789: Now we can create a circle on the heap (i.e.,
                   10790: @code{allocate}d memory) with:
1.44      crook    10791: 
1.78      anton    10792: @cindex @code{heap-new} usage
1.5       anton    10793: @example
1.78      anton    10794: 50 circle heap-new constant my-circle
1.5       anton    10795: @end example
                   10796: 
1.78      anton    10797: @noindent
                   10798: @code{heap-new} invokes @code{construct}, thus
                   10799: initializing the field @code{circle-radius} with 50. We can draw
                   10800: this new circle at (100,100) with:
1.5       anton    10801: 
                   10802: @example
1.78      anton    10803: 100 100 my-circle draw
1.5       anton    10804: @end example
                   10805: 
1.78      anton    10806: @cindex selector invocation, restrictions
                   10807: @cindex class definition, restrictions
                   10808: Note: You can only invoke a selector if the object on the TOS
                   10809: (the receiving object) belongs to the class where the selector was
                   10810: defined or one of its descendents; e.g., you can invoke
                   10811: @code{draw} only for objects belonging to @code{graphical}
                   10812: or its descendents (e.g., @code{circle}).  Immediately before
                   10813: @code{end-class}, the search order has to be the same as
                   10814: immediately after @code{class}.
                   10815: 
                   10816: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   10817: @subsubsection The @file{object.fs} base class
                   10818: @cindex @code{object} class
                   10819: 
                   10820: When you define a class, you have to specify a parent class.  So how do
                   10821: you start defining classes? There is one class available from the start:
                   10822: @code{object}. It is ancestor for all classes and so is the
                   10823: only class that has no parent. It has two selectors: @code{construct}
                   10824: and @code{print}.
                   10825: 
                   10826: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   10827: @subsubsection Creating objects
                   10828: @cindex creating objects
                   10829: @cindex object creation
                   10830: @cindex object allocation options
                   10831: 
                   10832: @cindex @code{heap-new} discussion
                   10833: @cindex @code{dict-new} discussion
                   10834: @cindex @code{construct} discussion
                   10835: You can create and initialize an object of a class on the heap with
                   10836: @code{heap-new} ( ... class -- object ) and in the dictionary
                   10837: (allocation with @code{allot}) with @code{dict-new} (
                   10838: ... class -- object ). Both words invoke @code{construct}, which
                   10839: consumes the stack items indicated by "..." above.
                   10840: 
                   10841: @cindex @code{init-object} discussion
                   10842: @cindex @code{class-inst-size} discussion
                   10843: If you want to allocate memory for an object yourself, you can get its
                   10844: alignment and size with @code{class-inst-size 2@@} ( class --
                   10845: align size ). Once you have memory for an object, you can initialize
                   10846: it with @code{init-object} ( ... class object -- );
                   10847: @code{construct} does only a part of the necessary work.
                   10848: 
                   10849: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   10850: @subsubsection Object-Oriented Programming Style
                   10851: @cindex object-oriented programming style
                   10852: @cindex programming style, object-oriented
1.5       anton    10853: 
1.78      anton    10854: This section is not exhaustive.
1.5       anton    10855: 
1.78      anton    10856: @cindex stack effects of selectors
                   10857: @cindex selectors and stack effects
                   10858: In general, it is a good idea to ensure that all methods for the
                   10859: same selector have the same stack effect: when you invoke a selector,
                   10860: you often have no idea which method will be invoked, so, unless all
                   10861: methods have the same stack effect, you will not know the stack effect
                   10862: of the selector invocation.
1.5       anton    10863: 
1.78      anton    10864: One exception to this rule is methods for the selector
                   10865: @code{construct}. We know which method is invoked, because we
                   10866: specify the class to be constructed at the same place. Actually, I
                   10867: defined @code{construct} as a selector only to give the users a
                   10868: convenient way to specify initialization. The way it is used, a
                   10869: mechanism different from selector invocation would be more natural
                   10870: (but probably would take more code and more space to explain).
1.5       anton    10871: 
1.78      anton    10872: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   10873: @subsubsection Class Binding
                   10874: @cindex class binding
                   10875: @cindex early binding
1.5       anton    10876: 
1.78      anton    10877: @cindex late binding
                   10878: Normal selector invocations determine the method at run-time depending
                   10879: on the class of the receiving object. This run-time selection is called
                   10880: @i{late binding}.
1.5       anton    10881: 
1.78      anton    10882: Sometimes it's preferable to invoke a different method. For example,
                   10883: you might want to use the simple method for @code{print}ing
                   10884: @code{object}s instead of the possibly long-winded @code{print} method
                   10885: of the receiver class. You can achieve this by replacing the invocation
                   10886: of @code{print} with:
1.5       anton    10887: 
1.78      anton    10888: @cindex @code{[bind]} usage
1.5       anton    10889: @example
1.78      anton    10890: [bind] object print
1.5       anton    10891: @end example
                   10892: 
1.78      anton    10893: @noindent
                   10894: in compiled code or:
                   10895: 
                   10896: @cindex @code{bind} usage
1.5       anton    10897: @example
1.78      anton    10898: bind object print
1.5       anton    10899: @end example
                   10900: 
1.78      anton    10901: @cindex class binding, alternative to
                   10902: @noindent
                   10903: in interpreted code. Alternatively, you can define the method with a
                   10904: name (e.g., @code{print-object}), and then invoke it through the
                   10905: name. Class binding is just a (often more convenient) way to achieve
                   10906: the same effect; it avoids name clutter and allows you to invoke
                   10907: methods directly without naming them first.
1.5       anton    10908: 
1.78      anton    10909: @cindex superclass binding
                   10910: @cindex parent class binding
                   10911: A frequent use of class binding is this: When we define a method
                   10912: for a selector, we often want the method to do what the selector does
                   10913: in the parent class, and a little more. There is a special word for
                   10914: this purpose: @code{[parent]}; @code{[parent]
                   10915: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   10916: selector}}, where @code{@emph{parent}} is the parent
                   10917: class of the current class. E.g., a method definition might look like:
1.44      crook    10918: 
1.78      anton    10919: @cindex @code{[parent]} usage
                   10920: @example
                   10921: :noname
                   10922:   dup [parent] foo \ do parent's foo on the receiving object
                   10923:   ... \ do some more
                   10924: ; overrides foo
                   10925: @end example
1.6       pazsan   10926: 
1.78      anton    10927: @cindex class binding as optimization
                   10928: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   10929: March 1997), Andrew McKewan presents class binding as an optimization
                   10930: technique. I recommend not using it for this purpose unless you are in
                   10931: an emergency. Late binding is pretty fast with this model anyway, so the
                   10932: benefit of using class binding is small; the cost of using class binding
                   10933: where it is not appropriate is reduced maintainability.
1.44      crook    10934: 
1.78      anton    10935: While we are at programming style questions: You should bind
                   10936: selectors only to ancestor classes of the receiving object. E.g., say,
                   10937: you know that the receiving object is of class @code{foo} or its
                   10938: descendents; then you should bind only to @code{foo} and its
                   10939: ancestors.
1.12      anton    10940: 
1.78      anton    10941: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   10942: @subsubsection Method conveniences
                   10943: @cindex method conveniences
1.44      crook    10944: 
1.78      anton    10945: In a method you usually access the receiving object pretty often.  If
                   10946: you define the method as a plain colon definition (e.g., with
                   10947: @code{:noname}), you may have to do a lot of stack
                   10948: gymnastics. To avoid this, you can define the method with @code{m:
                   10949: ... ;m}. E.g., you could define the method for
                   10950: @code{draw}ing a @code{circle} with
1.6       pazsan   10951: 
1.78      anton    10952: @cindex @code{this} usage
                   10953: @cindex @code{m:} usage
                   10954: @cindex @code{;m} usage
                   10955: @example
                   10956: m: ( x y circle -- )
                   10957:   ( x y ) this circle-radius @@ draw-circle ;m
                   10958: @end example
1.6       pazsan   10959: 
1.78      anton    10960: @cindex @code{exit} in @code{m: ... ;m}
                   10961: @cindex @code{exitm} discussion
                   10962: @cindex @code{catch} in @code{m: ... ;m}
                   10963: When this method is executed, the receiver object is removed from the
                   10964: stack; you can access it with @code{this} (admittedly, in this
                   10965: example the use of @code{m: ... ;m} offers no advantage). Note
                   10966: that I specify the stack effect for the whole method (i.e. including
                   10967: the receiver object), not just for the code between @code{m:}
                   10968: and @code{;m}. You cannot use @code{exit} in
                   10969: @code{m:...;m}; instead, use
                   10970: @code{exitm}.@footnote{Moreover, for any word that calls
                   10971: @code{catch} and was defined before loading
                   10972: @code{objects.fs}, you have to redefine it like I redefined
                   10973: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12      anton    10974: 
1.78      anton    10975: @cindex @code{inst-var} usage
                   10976: You will frequently use sequences of the form @code{this
                   10977: @emph{field}} (in the example above: @code{this
                   10978: circle-radius}). If you use the field only in this way, you can
                   10979: define it with @code{inst-var} and eliminate the
                   10980: @code{this} before the field name. E.g., the @code{circle}
                   10981: class above could also be defined with:
1.6       pazsan   10982: 
1.78      anton    10983: @example
                   10984: graphical class
                   10985:   cell% inst-var radius
1.6       pazsan   10986: 
1.78      anton    10987: m: ( x y circle -- )
                   10988:   radius @@ draw-circle ;m
                   10989: overrides draw
1.6       pazsan   10990: 
1.78      anton    10991: m: ( n-radius circle -- )
                   10992:   radius ! ;m
                   10993: overrides construct
1.6       pazsan   10994: 
1.78      anton    10995: end-class circle
                   10996: @end example
1.6       pazsan   10997: 
1.78      anton    10998: @code{radius} can only be used in @code{circle} and its
                   10999: descendent classes and inside @code{m:...;m}.
1.6       pazsan   11000: 
1.78      anton    11001: @cindex @code{inst-value} usage
                   11002: You can also define fields with @code{inst-value}, which is
                   11003: to @code{inst-var} what @code{value} is to
                   11004: @code{variable}.  You can change the value of such a field with
                   11005: @code{[to-inst]}.  E.g., we could also define the class
                   11006: @code{circle} like this:
1.44      crook    11007: 
1.78      anton    11008: @example
                   11009: graphical class
                   11010:   inst-value radius
1.6       pazsan   11011: 
1.78      anton    11012: m: ( x y circle -- )
                   11013:   radius draw-circle ;m
                   11014: overrides draw
1.44      crook    11015: 
1.78      anton    11016: m: ( n-radius circle -- )
                   11017:   [to-inst] radius ;m
                   11018: overrides construct
1.6       pazsan   11019: 
1.78      anton    11020: end-class circle
                   11021: @end example
1.6       pazsan   11022: 
1.78      anton    11023: @c !! :m is easy to confuse with m:.  Another name would be better.
1.6       pazsan   11024: 
1.78      anton    11025: @c Finally, you can define named methods with @code{:m}.  One use of this
                   11026: @c feature is the definition of words that occur only in one class and are
                   11027: @c not intended to be overridden, but which still need method context
                   11028: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
                   11029: @c would be bound frequently, if defined anonymously.
1.6       pazsan   11030: 
                   11031: 
1.78      anton    11032: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
                   11033: @subsubsection Classes and Scoping
                   11034: @cindex classes and scoping
                   11035: @cindex scoping and classes
1.6       pazsan   11036: 
1.78      anton    11037: Inheritance is frequent, unlike structure extension. This exacerbates
                   11038: the problem with the field name convention (@pxref{Structure Naming
                   11039: Convention}): One always has to remember in which class the field was
                   11040: originally defined; changing a part of the class structure would require
                   11041: changes for renaming in otherwise unaffected code.
1.6       pazsan   11042: 
1.78      anton    11043: @cindex @code{inst-var} visibility
                   11044: @cindex @code{inst-value} visibility
                   11045: To solve this problem, I added a scoping mechanism (which was not in my
                   11046: original charter): A field defined with @code{inst-var} (or
                   11047: @code{inst-value}) is visible only in the class where it is defined and in
                   11048: the descendent classes of this class.  Using such fields only makes
                   11049: sense in @code{m:}-defined methods in these classes anyway.
1.6       pazsan   11050: 
1.78      anton    11051: This scoping mechanism allows us to use the unadorned field name,
                   11052: because name clashes with unrelated words become much less likely.
1.6       pazsan   11053: 
1.78      anton    11054: @cindex @code{protected} discussion
                   11055: @cindex @code{private} discussion
                   11056: Once we have this mechanism, we can also use it for controlling the
                   11057: visibility of other words: All words defined after
                   11058: @code{protected} are visible only in the current class and its
                   11059: descendents. @code{public} restores the compilation
                   11060: (i.e. @code{current}) word list that was in effect before. If you
                   11061: have several @code{protected}s without an intervening
                   11062: @code{public} or @code{set-current}, @code{public}
                   11063: will restore the compilation word list in effect before the first of
                   11064: these @code{protected}s.
1.6       pazsan   11065: 
1.78      anton    11066: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
                   11067: @subsubsection Dividing classes
                   11068: @cindex Dividing classes
                   11069: @cindex @code{methods}...@code{end-methods}
1.6       pazsan   11070: 
1.78      anton    11071: You may want to do the definition of methods separate from the
                   11072: definition of the class, its selectors, fields, and instance variables,
                   11073: i.e., separate the implementation from the definition.  You can do this
                   11074: in the following way:
1.6       pazsan   11075: 
1.78      anton    11076: @example
                   11077: graphical class
                   11078:   inst-value radius
                   11079: end-class circle
1.6       pazsan   11080: 
1.78      anton    11081: ... \ do some other stuff
1.6       pazsan   11082: 
1.78      anton    11083: circle methods \ now we are ready
1.44      crook    11084: 
1.78      anton    11085: m: ( x y circle -- )
                   11086:   radius draw-circle ;m
                   11087: overrides draw
1.6       pazsan   11088: 
1.78      anton    11089: m: ( n-radius circle -- )
                   11090:   [to-inst] radius ;m
                   11091: overrides construct
1.44      crook    11092: 
1.78      anton    11093: end-methods
                   11094: @end example
1.7       pazsan   11095: 
1.78      anton    11096: You can use several @code{methods}...@code{end-methods} sections.  The
                   11097: only things you can do to the class in these sections are: defining
                   11098: methods, and overriding the class's selectors.  You must not define new
                   11099: selectors or fields.
1.7       pazsan   11100: 
1.78      anton    11101: Note that you often have to override a selector before using it.  In
                   11102: particular, you usually have to override @code{construct} with a new
                   11103: method before you can invoke @code{heap-new} and friends.  E.g., you
                   11104: must not create a circle before the @code{overrides construct} sequence
                   11105: in the example above.
1.7       pazsan   11106: 
1.78      anton    11107: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
                   11108: @subsubsection Object Interfaces
                   11109: @cindex object interfaces
                   11110: @cindex interfaces for objects
1.7       pazsan   11111: 
1.78      anton    11112: In this model you can only call selectors defined in the class of the
                   11113: receiving objects or in one of its ancestors. If you call a selector
                   11114: with a receiving object that is not in one of these classes, the
                   11115: result is undefined; if you are lucky, the program crashes
                   11116: immediately.
1.7       pazsan   11117: 
1.78      anton    11118: @cindex selectors common to hardly-related classes
                   11119: Now consider the case when you want to have a selector (or several)
                   11120: available in two classes: You would have to add the selector to a
                   11121: common ancestor class, in the worst case to @code{object}. You
                   11122: may not want to do this, e.g., because someone else is responsible for
                   11123: this ancestor class.
1.7       pazsan   11124: 
1.78      anton    11125: The solution for this problem is interfaces. An interface is a
                   11126: collection of selectors. If a class implements an interface, the
                   11127: selectors become available to the class and its descendents. A class
                   11128: can implement an unlimited number of interfaces. For the problem
                   11129: discussed above, we would define an interface for the selector(s), and
                   11130: both classes would implement the interface.
1.7       pazsan   11131: 
1.78      anton    11132: As an example, consider an interface @code{storage} for
                   11133: writing objects to disk and getting them back, and a class
                   11134: @code{foo} that implements it. The code would look like this:
1.7       pazsan   11135: 
1.78      anton    11136: @cindex @code{interface} usage
                   11137: @cindex @code{end-interface} usage
                   11138: @cindex @code{implementation} usage
                   11139: @example
                   11140: interface
                   11141:   selector write ( file object -- )
                   11142:   selector read1 ( file object -- )
                   11143: end-interface storage
1.13      pazsan   11144: 
1.78      anton    11145: bar class
                   11146:   storage implementation
1.13      pazsan   11147: 
1.78      anton    11148: ... overrides write
                   11149: ... overrides read1
                   11150: ...
                   11151: end-class foo
                   11152: @end example
1.13      pazsan   11153: 
1.78      anton    11154: @noindent
                   11155: (I would add a word @code{read} @i{( file -- object )} that uses
                   11156: @code{read1} internally, but that's beyond the point illustrated
                   11157: here.)
1.13      pazsan   11158: 
1.78      anton    11159: Note that you cannot use @code{protected} in an interface; and
                   11160: of course you cannot define fields.
1.13      pazsan   11161: 
1.78      anton    11162: In the Neon model, all selectors are available for all classes;
                   11163: therefore it does not need interfaces. The price you pay in this model
                   11164: is slower late binding, and therefore, added complexity to avoid late
                   11165: binding.
1.13      pazsan   11166: 
1.78      anton    11167: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   11168: @subsubsection @file{objects.fs} Implementation
                   11169: @cindex @file{objects.fs} implementation
1.13      pazsan   11170: 
1.78      anton    11171: @cindex @code{object-map} discussion
                   11172: An object is a piece of memory, like one of the data structures
                   11173: described with @code{struct...end-struct}. It has a field
                   11174: @code{object-map} that points to the method map for the object's
                   11175: class.
1.13      pazsan   11176: 
1.78      anton    11177: @cindex method map
                   11178: @cindex virtual function table
                   11179: The @emph{method map}@footnote{This is Self terminology; in C++
                   11180: terminology: virtual function table.} is an array that contains the
                   11181: execution tokens (@i{xt}s) of the methods for the object's class. Each
                   11182: selector contains an offset into a method map.
1.13      pazsan   11183: 
1.78      anton    11184: @cindex @code{selector} implementation, class
                   11185: @code{selector} is a defining word that uses
                   11186: @code{CREATE} and @code{DOES>}. The body of the
                   11187: selector contains the offset; the @code{DOES>} action for a
                   11188: class selector is, basically:
1.8       pazsan   11189: 
                   11190: @example
1.78      anton    11191: ( object addr ) @@ over object-map @@ + @@ execute
1.13      pazsan   11192: @end example
                   11193: 
1.78      anton    11194: Since @code{object-map} is the first field of the object, it
                   11195: does not generate any code. As you can see, calling a selector has a
                   11196: small, constant cost.
1.26      crook    11197: 
1.78      anton    11198: @cindex @code{current-interface} discussion
                   11199: @cindex class implementation and representation
                   11200: A class is basically a @code{struct} combined with a method
                   11201: map. During the class definition the alignment and size of the class
                   11202: are passed on the stack, just as with @code{struct}s, so
                   11203: @code{field} can also be used for defining class
                   11204: fields. However, passing more items on the stack would be
                   11205: inconvenient, so @code{class} builds a data structure in memory,
                   11206: which is accessed through the variable
                   11207: @code{current-interface}. After its definition is complete, the
                   11208: class is represented on the stack by a pointer (e.g., as parameter for
                   11209: a child class definition).
1.26      crook    11210: 
1.78      anton    11211: A new class starts off with the alignment and size of its parent,
                   11212: and a copy of the parent's method map. Defining new fields extends the
                   11213: size and alignment; likewise, defining new selectors extends the
                   11214: method map. @code{overrides} just stores a new @i{xt} in the method
                   11215: map at the offset given by the selector.
1.13      pazsan   11216: 
1.78      anton    11217: @cindex class binding, implementation
                   11218: Class binding just gets the @i{xt} at the offset given by the selector
                   11219: from the class's method map and @code{compile,}s (in the case of
                   11220: @code{[bind]}) it.
1.13      pazsan   11221: 
1.78      anton    11222: @cindex @code{this} implementation
                   11223: @cindex @code{catch} and @code{this}
                   11224: @cindex @code{this} and @code{catch}
                   11225: I implemented @code{this} as a @code{value}. At the
                   11226: start of an @code{m:...;m} method the old @code{this} is
                   11227: stored to the return stack and restored at the end; and the object on
                   11228: the TOS is stored @code{TO this}. This technique has one
                   11229: disadvantage: If the user does not leave the method via
                   11230: @code{;m}, but via @code{throw} or @code{exit},
                   11231: @code{this} is not restored (and @code{exit} may
                   11232: crash). To deal with the @code{throw} problem, I have redefined
                   11233: @code{catch} to save and restore @code{this}; the same
                   11234: should be done with any word that can catch an exception. As for
                   11235: @code{exit}, I simply forbid it (as a replacement, there is
                   11236: @code{exitm}).
1.13      pazsan   11237: 
1.78      anton    11238: @cindex @code{inst-var} implementation
                   11239: @code{inst-var} is just the same as @code{field}, with
                   11240: a different @code{DOES>} action:
1.13      pazsan   11241: @example
1.78      anton    11242: @@ this +
1.8       pazsan   11243: @end example
1.78      anton    11244: Similar for @code{inst-value}.
1.8       pazsan   11245: 
1.78      anton    11246: @cindex class scoping implementation
                   11247: Each class also has a word list that contains the words defined with
                   11248: @code{inst-var} and @code{inst-value}, and its protected
                   11249: words. It also has a pointer to its parent. @code{class} pushes
                   11250: the word lists of the class and all its ancestors onto the search order stack,
                   11251: and @code{end-class} drops them.
1.20      pazsan   11252: 
1.78      anton    11253: @cindex interface implementation
                   11254: An interface is like a class without fields, parent and protected
                   11255: words; i.e., it just has a method map. If a class implements an
                   11256: interface, its method map contains a pointer to the method map of the
                   11257: interface. The positive offsets in the map are reserved for class
                   11258: methods, therefore interface map pointers have negative
                   11259: offsets. Interfaces have offsets that are unique throughout the
                   11260: system, unlike class selectors, whose offsets are only unique for the
                   11261: classes where the selector is available (invokable).
1.20      pazsan   11262: 
1.78      anton    11263: This structure means that interface selectors have to perform one
                   11264: indirection more than class selectors to find their method. Their body
                   11265: contains the interface map pointer offset in the class method map, and
                   11266: the method offset in the interface method map. The
                   11267: @code{does>} action for an interface selector is, basically:
1.20      pazsan   11268: 
                   11269: @example
1.78      anton    11270: ( object selector-body )
                   11271: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   11272: swap object-map @@ + @@ ( object selector-body map )
                   11273: swap selector-offset @@ + @@ execute
1.20      pazsan   11274: @end example
                   11275: 
1.78      anton    11276: where @code{object-map} and @code{selector-offset} are
                   11277: first fields and generate no code.
1.20      pazsan   11278: 
1.78      anton    11279: As a concrete example, consider the following code:
1.20      pazsan   11280: 
                   11281: @example
1.78      anton    11282: interface
                   11283:   selector if1sel1
                   11284:   selector if1sel2
                   11285: end-interface if1
1.20      pazsan   11286: 
1.78      anton    11287: object class
                   11288:   if1 implementation
                   11289:   selector cl1sel1
                   11290:   cell% inst-var cl1iv1
1.20      pazsan   11291: 
1.78      anton    11292: ' m1 overrides construct
                   11293: ' m2 overrides if1sel1
                   11294: ' m3 overrides if1sel2
                   11295: ' m4 overrides cl1sel2
                   11296: end-class cl1
1.20      pazsan   11297: 
1.78      anton    11298: create obj1 object dict-new drop
                   11299: create obj2 cl1    dict-new drop
                   11300: @end example
1.20      pazsan   11301: 
1.78      anton    11302: The data structure created by this code (including the data structure
                   11303: for @code{object}) is shown in the
                   11304: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
                   11305: @comment TODO add this diagram..
1.20      pazsan   11306: 
1.78      anton    11307: @node Objects Glossary,  , Objects Implementation, Objects
                   11308: @subsubsection @file{objects.fs} Glossary
                   11309: @cindex @file{objects.fs} Glossary
1.20      pazsan   11310: 
                   11311: 
1.78      anton    11312: doc---objects-bind
                   11313: doc---objects-<bind>
                   11314: doc---objects-bind'
                   11315: doc---objects-[bind]
                   11316: doc---objects-class
                   11317: doc---objects-class->map
                   11318: doc---objects-class-inst-size
                   11319: doc---objects-class-override!
1.79      anton    11320: doc---objects-class-previous
                   11321: doc---objects-class>order
1.78      anton    11322: doc---objects-construct
                   11323: doc---objects-current'
                   11324: doc---objects-[current]
                   11325: doc---objects-current-interface
                   11326: doc---objects-dict-new
                   11327: doc---objects-end-class
                   11328: doc---objects-end-class-noname
                   11329: doc---objects-end-interface
                   11330: doc---objects-end-interface-noname
                   11331: doc---objects-end-methods
                   11332: doc---objects-exitm
                   11333: doc---objects-heap-new
                   11334: doc---objects-implementation
                   11335: doc---objects-init-object
                   11336: doc---objects-inst-value
                   11337: doc---objects-inst-var
                   11338: doc---objects-interface
                   11339: doc---objects-m:
                   11340: doc---objects-:m
                   11341: doc---objects-;m
                   11342: doc---objects-method
                   11343: doc---objects-methods
                   11344: doc---objects-object
                   11345: doc---objects-overrides
                   11346: doc---objects-[parent]
                   11347: doc---objects-print
                   11348: doc---objects-protected
                   11349: doc---objects-public
                   11350: doc---objects-selector
                   11351: doc---objects-this
                   11352: doc---objects-<to-inst>
                   11353: doc---objects-[to-inst]
                   11354: doc---objects-to-this
                   11355: doc---objects-xt-new
1.20      pazsan   11356: 
                   11357: 
1.78      anton    11358: @c -------------------------------------------------------------
                   11359: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   11360: @subsection The @file{oof.fs} model
                   11361: @cindex oof
                   11362: @cindex object-oriented programming
1.20      pazsan   11363: 
1.78      anton    11364: @cindex @file{objects.fs}
                   11365: @cindex @file{oof.fs}
1.20      pazsan   11366: 
1.78      anton    11367: This section describes the @file{oof.fs} package.
1.20      pazsan   11368: 
1.78      anton    11369: The package described in this section has been used in bigFORTH since 1991, and
                   11370: used for two large applications: a chromatographic system used to
                   11371: create new medicaments, and a graphic user interface library (MINOS).
1.20      pazsan   11372: 
1.78      anton    11373: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   11374: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   11375: 10(2), 1994.
1.20      pazsan   11376: 
1.78      anton    11377: @menu
                   11378: * Properties of the OOF model::  
                   11379: * Basic OOF Usage::             
                   11380: * The OOF base class::          
                   11381: * Class Declaration::           
                   11382: * Class Implementation::        
                   11383: @end menu
1.20      pazsan   11384: 
1.78      anton    11385: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   11386: @subsubsection Properties of the @file{oof.fs} model
                   11387: @cindex @file{oof.fs} properties
1.20      pazsan   11388: 
1.78      anton    11389: @itemize @bullet
                   11390: @item
                   11391: This model combines object oriented programming with information
                   11392: hiding. It helps you writing large application, where scoping is
                   11393: necessary, because it provides class-oriented scoping.
1.20      pazsan   11394: 
1.78      anton    11395: @item
                   11396: Named objects, object pointers, and object arrays can be created,
                   11397: selector invocation uses the ``object selector'' syntax. Selector invocation
                   11398: to objects and/or selectors on the stack is a bit less convenient, but
                   11399: possible.
1.44      crook    11400: 
1.78      anton    11401: @item
                   11402: Selector invocation and instance variable usage of the active object is
                   11403: straightforward, since both make use of the active object.
1.44      crook    11404: 
1.78      anton    11405: @item
                   11406: Late binding is efficient and easy to use.
1.20      pazsan   11407: 
1.78      anton    11408: @item
                   11409: State-smart objects parse selectors. However, extensibility is provided
                   11410: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20      pazsan   11411: 
1.78      anton    11412: @item
                   11413: An implementation in ANS Forth is available.
1.20      pazsan   11414: 
1.78      anton    11415: @end itemize
1.23      crook    11416: 
                   11417: 
1.78      anton    11418: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   11419: @subsubsection Basic @file{oof.fs} Usage
                   11420: @cindex @file{oof.fs} usage
1.23      crook    11421: 
1.78      anton    11422: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23      crook    11423: 
1.78      anton    11424: You can define a class for graphical objects like this:
1.23      crook    11425: 
1.78      anton    11426: @cindex @code{class} usage
                   11427: @cindex @code{class;} usage
                   11428: @cindex @code{method} usage
                   11429: @example
                   11430: object class graphical \ "object" is the parent class
1.139     pazsan   11431:   method draw ( x y -- )
1.78      anton    11432: class;
                   11433: @end example
1.23      crook    11434: 
1.78      anton    11435: This code defines a class @code{graphical} with an
                   11436: operation @code{draw}.  We can perform the operation
                   11437: @code{draw} on any @code{graphical} object, e.g.:
1.23      crook    11438: 
1.78      anton    11439: @example
                   11440: 100 100 t-rex draw
                   11441: @end example
1.23      crook    11442: 
1.78      anton    11443: @noindent
                   11444: where @code{t-rex} is an object or object pointer, created with e.g.
                   11445: @code{graphical : t-rex}.
1.23      crook    11446: 
1.78      anton    11447: @cindex abstract class
                   11448: How do we create a graphical object? With the present definitions,
                   11449: we cannot create a useful graphical object. The class
                   11450: @code{graphical} describes graphical objects in general, but not
                   11451: any concrete graphical object type (C++ users would call it an
                   11452: @emph{abstract class}); e.g., there is no method for the selector
                   11453: @code{draw} in the class @code{graphical}.
1.23      crook    11454: 
1.78      anton    11455: For concrete graphical objects, we define child classes of the
                   11456: class @code{graphical}, e.g.:
1.23      crook    11457: 
1.78      anton    11458: @example
                   11459: graphical class circle \ "graphical" is the parent class
                   11460:   cell var circle-radius
                   11461: how:
                   11462:   : draw ( x y -- )
                   11463:     circle-radius @@ draw-circle ;
1.23      crook    11464: 
1.139     pazsan   11465:   : init ( n-radius -- )
1.78      anton    11466:     circle-radius ! ;
                   11467: class;
                   11468: @end example
1.1       anton    11469: 
1.78      anton    11470: Here we define a class @code{circle} as a child of @code{graphical},
                   11471: with a field @code{circle-radius}; it defines new methods for the
                   11472: selectors @code{draw} and @code{init} (@code{init} is defined in
                   11473: @code{object}, the parent class of @code{graphical}).
1.1       anton    11474: 
1.78      anton    11475: Now we can create a circle in the dictionary with:
1.1       anton    11476: 
1.78      anton    11477: @example
                   11478: 50 circle : my-circle
                   11479: @end example
1.21      crook    11480: 
1.78      anton    11481: @noindent
                   11482: @code{:} invokes @code{init}, thus initializing the field
                   11483: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   11484: with:
1.1       anton    11485: 
1.78      anton    11486: @example
                   11487: 100 100 my-circle draw
                   11488: @end example
1.1       anton    11489: 
1.78      anton    11490: @cindex selector invocation, restrictions
                   11491: @cindex class definition, restrictions
                   11492: Note: You can only invoke a selector if the receiving object belongs to
                   11493: the class where the selector was defined or one of its descendents;
                   11494: e.g., you can invoke @code{draw} only for objects belonging to
                   11495: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   11496: mechanism will check if you try to invoke a selector that is not
                   11497: defined in this class hierarchy, so you'll get an error at compilation
                   11498: time.
1.1       anton    11499: 
                   11500: 
1.78      anton    11501: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   11502: @subsubsection The @file{oof.fs} base class
                   11503: @cindex @file{oof.fs} base class
1.1       anton    11504: 
1.78      anton    11505: When you define a class, you have to specify a parent class.  So how do
                   11506: you start defining classes? There is one class available from the start:
                   11507: @code{object}. You have to use it as ancestor for all classes. It is the
                   11508: only class that has no parent. Classes are also objects, except that
                   11509: they don't have instance variables; class manipulation such as
                   11510: inheritance or changing definitions of a class is handled through
                   11511: selectors of the class @code{object}.
1.1       anton    11512: 
1.78      anton    11513: @code{object} provides a number of selectors:
1.1       anton    11514: 
1.78      anton    11515: @itemize @bullet
                   11516: @item
                   11517: @code{class} for subclassing, @code{definitions} to add definitions
                   11518: later on, and @code{class?} to get type informations (is the class a
                   11519: subclass of the class passed on the stack?).
1.1       anton    11520: 
1.78      anton    11521: doc---object-class
                   11522: doc---object-definitions
                   11523: doc---object-class?
1.1       anton    11524: 
                   11525: 
1.26      crook    11526: @item
1.78      anton    11527: @code{init} and @code{dispose} as constructor and destructor of the
                   11528: object. @code{init} is invocated after the object's memory is allocated,
                   11529: while @code{dispose} also handles deallocation. Thus if you redefine
                   11530: @code{dispose}, you have to call the parent's dispose with @code{super
                   11531: dispose}, too.
                   11532: 
                   11533: doc---object-init
                   11534: doc---object-dispose
                   11535: 
1.1       anton    11536: 
1.26      crook    11537: @item
1.78      anton    11538: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   11539: @code{[]} to create named and unnamed objects and object arrays or
                   11540: object pointers.
                   11541: 
                   11542: doc---object-new
                   11543: doc---object-new[]
                   11544: doc---object-:
                   11545: doc---object-ptr
                   11546: doc---object-asptr
                   11547: doc---object-[]
                   11548: 
1.1       anton    11549: 
1.26      crook    11550: @item
1.78      anton    11551: @code{::} and @code{super} for explicit scoping. You should use explicit
                   11552: scoping only for super classes or classes with the same set of instance
                   11553: variables. Explicitly-scoped selectors use early binding.
1.21      crook    11554: 
1.78      anton    11555: doc---object-::
                   11556: doc---object-super
1.21      crook    11557: 
                   11558: 
1.26      crook    11559: @item
1.78      anton    11560: @code{self} to get the address of the object
1.21      crook    11561: 
1.78      anton    11562: doc---object-self
1.21      crook    11563: 
                   11564: 
1.78      anton    11565: @item
                   11566: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   11567: pointers and instance defers.
1.21      crook    11568: 
1.78      anton    11569: doc---object-bind
                   11570: doc---object-bound
                   11571: doc---object-link
                   11572: doc---object-is
1.21      crook    11573: 
                   11574: 
1.78      anton    11575: @item
                   11576: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   11577: form the stack, and @code{postpone} to generate selector invocation code.
1.21      crook    11578: 
1.78      anton    11579: doc---object-'
                   11580: doc---object-postpone
1.21      crook    11581: 
                   11582: 
1.78      anton    11583: @item
                   11584: @code{with} and @code{endwith} to select the active object from the
                   11585: stack, and enable its scope. Using @code{with} and @code{endwith}
                   11586: also allows you to create code using selector @code{postpone} without being
                   11587: trapped by the state-smart objects.
1.21      crook    11588: 
1.78      anton    11589: doc---object-with
                   11590: doc---object-endwith
1.21      crook    11591: 
                   11592: 
1.78      anton    11593: @end itemize
1.21      crook    11594: 
1.78      anton    11595: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   11596: @subsubsection Class Declaration
                   11597: @cindex class declaration
1.21      crook    11598: 
1.78      anton    11599: @itemize @bullet
                   11600: @item
                   11601: Instance variables
1.21      crook    11602: 
1.78      anton    11603: doc---oof-var
1.21      crook    11604: 
                   11605: 
1.78      anton    11606: @item
                   11607: Object pointers
1.21      crook    11608: 
1.78      anton    11609: doc---oof-ptr
                   11610: doc---oof-asptr
1.21      crook    11611: 
                   11612: 
1.78      anton    11613: @item
                   11614: Instance defers
1.21      crook    11615: 
1.78      anton    11616: doc---oof-defer
1.21      crook    11617: 
                   11618: 
1.78      anton    11619: @item
                   11620: Method selectors
1.21      crook    11621: 
1.78      anton    11622: doc---oof-early
                   11623: doc---oof-method
1.21      crook    11624: 
                   11625: 
1.78      anton    11626: @item
                   11627: Class-wide variables
1.21      crook    11628: 
1.78      anton    11629: doc---oof-static
1.21      crook    11630: 
                   11631: 
1.78      anton    11632: @item
                   11633: End declaration
1.1       anton    11634: 
1.78      anton    11635: doc---oof-how:
                   11636: doc---oof-class;
1.21      crook    11637: 
                   11638: 
1.78      anton    11639: @end itemize
1.21      crook    11640: 
1.78      anton    11641: @c -------------------------------------------------------------
                   11642: @node Class Implementation,  , Class Declaration, OOF
                   11643: @subsubsection Class Implementation
                   11644: @cindex class implementation
1.21      crook    11645: 
1.78      anton    11646: @c -------------------------------------------------------------
                   11647: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   11648: @subsection The @file{mini-oof.fs} model
                   11649: @cindex mini-oof
1.21      crook    11650: 
1.78      anton    11651: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79      anton    11652: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78      anton    11653: and reduces to the bare minimum of features. This is based on a posting
                   11654: of Bernd Paysan in comp.lang.forth.
1.21      crook    11655: 
1.78      anton    11656: @menu
                   11657: * Basic Mini-OOF Usage::        
                   11658: * Mini-OOF Example::            
                   11659: * Mini-OOF Implementation::     
                   11660: @end menu
1.21      crook    11661: 
1.78      anton    11662: @c -------------------------------------------------------------
                   11663: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
                   11664: @subsubsection Basic @file{mini-oof.fs} Usage
                   11665: @cindex mini-oof usage
1.21      crook    11666: 
1.78      anton    11667: There is a base class (@code{class}, which allocates one cell for the
                   11668: object pointer) plus seven other words: to define a method, a variable,
                   11669: a class; to end a class, to resolve binding, to allocate an object and
                   11670: to compile a class method.
                   11671: @comment TODO better description of the last one
1.26      crook    11672: 
1.21      crook    11673: 
1.78      anton    11674: doc-object
                   11675: doc-method
                   11676: doc-var
                   11677: doc-class
                   11678: doc-end-class
                   11679: doc-defines
                   11680: doc-new
                   11681: doc-::
1.21      crook    11682: 
                   11683: 
                   11684: 
1.78      anton    11685: @c -------------------------------------------------------------
                   11686: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   11687: @subsubsection Mini-OOF Example
                   11688: @cindex mini-oof example
1.1       anton    11689: 
1.78      anton    11690: A short example shows how to use this package. This example, in slightly
                   11691: extended form, is supplied as @file{moof-exm.fs}
                   11692: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20      pazsan   11693: 
1.26      crook    11694: @example
1.78      anton    11695: object class
                   11696:   method init
                   11697:   method draw
                   11698: end-class graphical
1.26      crook    11699: @end example
1.20      pazsan   11700: 
1.78      anton    11701: This code defines a class @code{graphical} with an
                   11702: operation @code{draw}.  We can perform the operation
                   11703: @code{draw} on any @code{graphical} object, e.g.:
1.20      pazsan   11704: 
1.26      crook    11705: @example
1.78      anton    11706: 100 100 t-rex draw
1.26      crook    11707: @end example
1.12      anton    11708: 
1.78      anton    11709: where @code{t-rex} is an object or object pointer, created with e.g.
                   11710: @code{graphical new Constant t-rex}.
1.12      anton    11711: 
1.78      anton    11712: For concrete graphical objects, we define child classes of the
                   11713: class @code{graphical}, e.g.:
1.12      anton    11714: 
1.26      crook    11715: @example
                   11716: graphical class
1.78      anton    11717:   cell var circle-radius
                   11718: end-class circle \ "graphical" is the parent class
1.12      anton    11719: 
1.78      anton    11720: :noname ( x y -- )
                   11721:   circle-radius @@ draw-circle ; circle defines draw
                   11722: :noname ( r -- )
                   11723:   circle-radius ! ; circle defines init
                   11724: @end example
1.12      anton    11725: 
1.78      anton    11726: There is no implicit init method, so we have to define one. The creation
                   11727: code of the object now has to call init explicitely.
1.21      crook    11728: 
1.78      anton    11729: @example
                   11730: circle new Constant my-circle
                   11731: 50 my-circle init
1.12      anton    11732: @end example
                   11733: 
1.78      anton    11734: It is also possible to add a function to create named objects with
                   11735: automatic call of @code{init}, given that all objects have @code{init}
                   11736: on the same place:
1.38      anton    11737: 
1.78      anton    11738: @example
                   11739: : new: ( .. o "name" -- )
                   11740:     new dup Constant init ;
                   11741: 80 circle new: large-circle
                   11742: @end example
1.12      anton    11743: 
1.78      anton    11744: We can draw this new circle at (100,100) with:
1.12      anton    11745: 
1.78      anton    11746: @example
                   11747: 100 100 my-circle draw
                   11748: @end example
1.12      anton    11749: 
1.78      anton    11750: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
                   11751: @subsubsection @file{mini-oof.fs} Implementation
1.12      anton    11752: 
1.78      anton    11753: Object-oriented systems with late binding typically use a
                   11754: ``vtable''-approach: the first variable in each object is a pointer to a
                   11755: table, which contains the methods as function pointers. The vtable
                   11756: may also contain other information.
1.12      anton    11757: 
1.79      anton    11758: So first, let's declare selectors:
1.37      anton    11759: 
                   11760: @example
1.79      anton    11761: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
1.78      anton    11762:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
                   11763: @end example
1.37      anton    11764: 
1.79      anton    11765: During selector declaration, the number of selectors and instance
                   11766: variables is on the stack (in address units). @code{method} creates one
                   11767: selector and increments the selector number. To execute a selector, it
1.78      anton    11768: takes the object, fetches the vtable pointer, adds the offset, and
1.79      anton    11769: executes the method @i{xt} stored there. Each selector takes the object
                   11770: it is invoked with as top of stack parameter; it passes the parameters
                   11771: (including the object) unchanged to the appropriate method which should
1.78      anton    11772: consume that object.
1.37      anton    11773: 
1.78      anton    11774: Now, we also have to declare instance variables
1.37      anton    11775: 
1.78      anton    11776: @example
1.79      anton    11777: : var ( m v size "name" -- m v' ) Create  over , +
1.78      anton    11778:   DOES> ( o -- addr ) @@ + ;
1.37      anton    11779: @end example
                   11780: 
1.78      anton    11781: As before, a word is created with the current offset. Instance
                   11782: variables can have different sizes (cells, floats, doubles, chars), so
                   11783: all we do is take the size and add it to the offset. If your machine
                   11784: has alignment restrictions, put the proper @code{aligned} or
                   11785: @code{faligned} before the variable, to adjust the variable
                   11786: offset. That's why it is on the top of stack.
1.37      anton    11787: 
1.78      anton    11788: We need a starting point (the base object) and some syntactic sugar:
1.37      anton    11789: 
1.78      anton    11790: @example
                   11791: Create object  1 cells , 2 cells ,
1.79      anton    11792: : class ( class -- class selectors vars ) dup 2@@ ;
1.78      anton    11793: @end example
1.12      anton    11794: 
1.78      anton    11795: For inheritance, the vtable of the parent object has to be
                   11796: copied when a new, derived class is declared. This gives all the
                   11797: methods of the parent class, which can be overridden, though.
1.12      anton    11798: 
1.78      anton    11799: @example
1.79      anton    11800: : end-class  ( class selectors vars "name" -- )
1.78      anton    11801:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   11802:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
                   11803: @end example
1.12      anton    11804: 
1.78      anton    11805: The first line creates the vtable, initialized with
                   11806: @code{noop}s. The second line is the inheritance mechanism, it
                   11807: copies the xts from the parent vtable.
1.12      anton    11808: 
1.78      anton    11809: We still have no way to define new methods, let's do that now:
1.12      anton    11810: 
1.26      crook    11811: @example
1.79      anton    11812: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78      anton    11813: @end example
1.12      anton    11814: 
1.78      anton    11815: To allocate a new object, we need a word, too:
1.12      anton    11816: 
1.78      anton    11817: @example
                   11818: : new ( class -- o )  here over @@ allot swap over ! ;
1.12      anton    11819: @end example
                   11820: 
1.78      anton    11821: Sometimes derived classes want to access the method of the
                   11822: parent object. There are two ways to achieve this with Mini-OOF:
                   11823: first, you could use named words, and second, you could look up the
                   11824: vtable of the parent object.
1.12      anton    11825: 
1.78      anton    11826: @example
                   11827: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
                   11828: @end example
1.12      anton    11829: 
                   11830: 
1.78      anton    11831: Nothing can be more confusing than a good example, so here is
                   11832: one. First let's declare a text object (called
                   11833: @code{button}), that stores text and position:
1.12      anton    11834: 
1.78      anton    11835: @example
                   11836: object class
                   11837:   cell var text
                   11838:   cell var len
                   11839:   cell var x
                   11840:   cell var y
                   11841:   method init
                   11842:   method draw
                   11843: end-class button
                   11844: @end example
1.12      anton    11845: 
1.78      anton    11846: @noindent
                   11847: Now, implement the two methods, @code{draw} and @code{init}:
1.21      crook    11848: 
1.26      crook    11849: @example
1.78      anton    11850: :noname ( o -- )
                   11851:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
                   11852:  button defines draw
                   11853: :noname ( addr u o -- )
                   11854:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
                   11855:  button defines init
1.26      crook    11856: @end example
1.12      anton    11857: 
1.78      anton    11858: @noindent
                   11859: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79      anton    11860: new data and no new selectors:
1.78      anton    11861: 
                   11862: @example
                   11863: button class
                   11864: end-class bold-button
1.12      anton    11865: 
1.78      anton    11866: : bold   27 emit ." [1m" ;
                   11867: : normal 27 emit ." [0m" ;
                   11868: @end example
1.1       anton    11869: 
1.78      anton    11870: @noindent
                   11871: The class @code{bold-button} has a different draw method to
                   11872: @code{button}, but the new method is defined in terms of the draw method
                   11873: for @code{button}:
1.20      pazsan   11874: 
1.78      anton    11875: @example
                   11876: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   11877: @end example
1.21      crook    11878: 
1.78      anton    11879: @noindent
1.79      anton    11880: Finally, create two objects and apply selectors:
1.21      crook    11881: 
1.26      crook    11882: @example
1.78      anton    11883: button new Constant foo
                   11884: s" thin foo" foo init
                   11885: page
                   11886: foo draw
                   11887: bold-button new Constant bar
                   11888: s" fat bar" bar init
                   11889: 1 bar y !
                   11890: bar draw
1.26      crook    11891: @end example
1.21      crook    11892: 
                   11893: 
1.78      anton    11894: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
                   11895: @subsection Comparison with other object models
                   11896: @cindex comparison of object models
                   11897: @cindex object models, comparison
                   11898: 
                   11899: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   11900: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   11901: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   11902: relation of the object models described here to two well-known and two
                   11903: closely-related (by the use of method maps) models.  Andras Zsoter
                   11904: helped us with this section.
                   11905: 
                   11906: @cindex Neon model
                   11907: The most popular model currently seems to be the Neon model (see
                   11908: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   11909: 1997) by Andrew McKewan) but this model has a number of limitations
                   11910: @footnote{A longer version of this critique can be
                   11911: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   11912: Dimensions, May 1997) by Anton Ertl.}:
                   11913: 
                   11914: @itemize @bullet
                   11915: @item
                   11916: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
                   11917: to pass objects on the stack.
1.21      crook    11918: 
1.78      anton    11919: @item
                   11920: It requires that the selector parses the input stream (at
1.79      anton    11921: compile time); this leads to reduced extensibility and to bugs that are
1.78      anton    11922: hard to find.
1.21      crook    11923: 
1.78      anton    11924: @item
1.79      anton    11925: It allows using every selector on every object; this eliminates the
                   11926: need for interfaces, but makes it harder to create efficient
                   11927: implementations.
1.78      anton    11928: @end itemize
1.21      crook    11929: 
1.78      anton    11930: @cindex Pountain's object-oriented model
                   11931: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   11932: Press, London, 1987) by Dick Pountain. However, it is not really about
                   11933: object-oriented programming, because it hardly deals with late
                   11934: binding. Instead, it focuses on features like information hiding and
                   11935: overloading that are characteristic of modular languages like Ada (83).
1.26      crook    11936: 
1.78      anton    11937: @cindex Zsoter's object-oriented model
1.79      anton    11938: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
                   11939: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
                   11940: describes a model that makes heavy use of an active object (like
                   11941: @code{this} in @file{objects.fs}): The active object is not only used
                   11942: for accessing all fields, but also specifies the receiving object of
                   11943: every selector invocation; you have to change the active object
                   11944: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
                   11945: changes more or less implicitly at @code{m: ... ;m}. Such a change at
                   11946: the method entry point is unnecessary with Zsoter's model, because the
                   11947: receiving object is the active object already. On the other hand, the
                   11948: explicit change is absolutely necessary in that model, because otherwise
                   11949: no one could ever change the active object. An ANS Forth implementation
                   11950: of this model is available through
                   11951: @uref{http://www.forth.org/oopf.html}.
1.21      crook    11952: 
1.78      anton    11953: @cindex @file{oof.fs}, differences to other models
                   11954: The @file{oof.fs} model combines information hiding and overloading
                   11955: resolution (by keeping names in various word lists) with object-oriented
                   11956: programming. It sets the active object implicitly on method entry, but
                   11957: also allows explicit changing (with @code{>o...o>} or with
                   11958: @code{with...endwith}). It uses parsing and state-smart objects and
                   11959: classes for resolving overloading and for early binding: the object or
                   11960: class parses the selector and determines the method from this. If the
                   11961: selector is not parsed by an object or class, it performs a call to the
                   11962: selector for the active object (late binding), like Zsoter's model.
                   11963: Fields are always accessed through the active object. The big
                   11964: disadvantage of this model is the parsing and the state-smartness, which
                   11965: reduces extensibility and increases the opportunities for subtle bugs;
                   11966: essentially, you are only safe if you never tick or @code{postpone} an
                   11967: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21      crook    11968: 
1.78      anton    11969: @cindex @file{mini-oof.fs}, differences to other models
                   11970: The @file{mini-oof.fs} model is quite similar to a very stripped-down
                   11971: version of the @file{objects.fs} model, but syntactically it is a
                   11972: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21      crook    11973: 
                   11974: 
1.78      anton    11975: @c -------------------------------------------------------------
1.150     anton    11976: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78      anton    11977: @section Programming Tools
                   11978: @cindex programming tools
1.21      crook    11979: 
1.78      anton    11980: @c !! move this and assembler down below OO stuff.
1.21      crook    11981: 
1.78      anton    11982: @menu
1.150     anton    11983: * Examining::                   Data and Code.
                   11984: * Forgetting words::            Usually before reloading.
1.78      anton    11985: * Debugging::                   Simple and quick.
                   11986: * Assertions::                  Making your programs self-checking.
                   11987: * Singlestep Debugger::         Executing your program word by word.
                   11988: @end menu
1.21      crook    11989: 
1.78      anton    11990: @node Examining, Forgetting words, Programming Tools, Programming Tools
                   11991: @subsection Examining data and code
                   11992: @cindex examining data and code
                   11993: @cindex data examination
                   11994: @cindex code examination
1.44      crook    11995: 
1.78      anton    11996: The following words inspect the stack non-destructively:
1.21      crook    11997: 
1.78      anton    11998: doc-.s
                   11999: doc-f.s
1.158     anton    12000: doc-maxdepth-.s
1.44      crook    12001: 
1.78      anton    12002: There is a word @code{.r} but it does @i{not} display the return stack!
                   12003: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21      crook    12004: 
1.78      anton    12005: doc-depth
                   12006: doc-fdepth
                   12007: doc-clearstack
1.124     anton    12008: doc-clearstacks
1.21      crook    12009: 
1.78      anton    12010: The following words inspect memory.
1.21      crook    12011: 
1.78      anton    12012: doc-?
                   12013: doc-dump
1.21      crook    12014: 
1.78      anton    12015: And finally, @code{see} allows to inspect code:
1.21      crook    12016: 
1.78      anton    12017: doc-see
                   12018: doc-xt-see
1.111     anton    12019: doc-simple-see
                   12020: doc-simple-see-range
1.182     anton    12021: doc-see-code
                   12022: doc-see-code-range
1.21      crook    12023: 
1.78      anton    12024: @node Forgetting words, Debugging, Examining, Programming Tools
                   12025: @subsection Forgetting words
                   12026: @cindex words, forgetting
                   12027: @cindex forgeting words
1.21      crook    12028: 
1.78      anton    12029: @c  anton: other, maybe better places for this subsection: Defining Words;
                   12030: @c  Dictionary allocation.  At least a reference should be there.
1.21      crook    12031: 
1.78      anton    12032: Forth allows you to forget words (and everything that was alloted in the
                   12033: dictonary after them) in a LIFO manner.
1.21      crook    12034: 
1.78      anton    12035: doc-marker
1.21      crook    12036: 
1.78      anton    12037: The most common use of this feature is during progam development: when
                   12038: you change a source file, forget all the words it defined and load it
                   12039: again (since you also forget everything defined after the source file
                   12040: was loaded, you have to reload that, too).  Note that effects like
                   12041: storing to variables and destroyed system words are not undone when you
                   12042: forget words.  With a system like Gforth, that is fast enough at
                   12043: starting up and compiling, I find it more convenient to exit and restart
                   12044: Gforth, as this gives me a clean slate.
1.21      crook    12045: 
1.78      anton    12046: Here's an example of using @code{marker} at the start of a source file
                   12047: that you are debugging; it ensures that you only ever have one copy of
                   12048: the file's definitions compiled at any time:
1.21      crook    12049: 
1.78      anton    12050: @example
                   12051: [IFDEF] my-code
                   12052:     my-code
                   12053: [ENDIF]
1.26      crook    12054: 
1.78      anton    12055: marker my-code
                   12056: init-included-files
1.21      crook    12057: 
1.78      anton    12058: \ .. definitions start here
                   12059: \ .
                   12060: \ .
                   12061: \ end
                   12062: @end example
1.21      crook    12063: 
1.26      crook    12064: 
1.78      anton    12065: @node Debugging, Assertions, Forgetting words, Programming Tools
                   12066: @subsection Debugging
                   12067: @cindex debugging
1.21      crook    12068: 
1.78      anton    12069: Languages with a slow edit/compile/link/test development loop tend to
                   12070: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21      crook    12071: 
1.78      anton    12072: A much better (faster) way in fast-compiling languages is to add
                   12073: printing code at well-selected places, let the program run, look at
                   12074: the output, see where things went wrong, add more printing code, etc.,
                   12075: until the bug is found.
1.21      crook    12076: 
1.78      anton    12077: The simple debugging aids provided in @file{debugs.fs}
                   12078: are meant to support this style of debugging.
1.21      crook    12079: 
1.78      anton    12080: The word @code{~~} prints debugging information (by default the source
                   12081: location and the stack contents). It is easy to insert. If you use Emacs
                   12082: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   12083: query-replace them with nothing). The deferred words
1.101     anton    12084: @code{printdebugdata} and @code{.debugline} control the output of
1.78      anton    12085: @code{~~}. The default source location output format works well with
                   12086: Emacs' compilation mode, so you can step through the program at the
                   12087: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   12088: is that you can step in any direction and you know where the crash has
                   12089: happened or where the strange data has occurred).
1.21      crook    12090: 
1.78      anton    12091: doc-~~
                   12092: doc-printdebugdata
1.101     anton    12093: doc-.debugline
1.203     anton    12094: doc-debug-fid
1.21      crook    12095: 
1.106     anton    12096: @cindex filenames in @code{~~} output
                   12097: @code{~~} (and assertions) will usually print the wrong file name if a
                   12098: marker is executed in the same file after their occurance.  They will
                   12099: print @samp{*somewhere*} as file name if a marker is executed in the
                   12100: same file before their occurance.
                   12101: 
                   12102: 
1.78      anton    12103: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   12104: @subsection Assertions
                   12105: @cindex assertions
1.21      crook    12106: 
1.78      anton    12107: It is a good idea to make your programs self-checking, especially if you
                   12108: make an assumption that may become invalid during maintenance (for
                   12109: example, that a certain field of a data structure is never zero). Gforth
                   12110: supports @dfn{assertions} for this purpose. They are used like this:
1.21      crook    12111: 
                   12112: @example
1.78      anton    12113: assert( @i{flag} )
1.26      crook    12114: @end example
                   12115: 
1.78      anton    12116: The code between @code{assert(} and @code{)} should compute a flag, that
                   12117: should be true if everything is alright and false otherwise. It should
                   12118: not change anything else on the stack. The overall stack effect of the
                   12119: assertion is @code{( -- )}. E.g.
1.21      crook    12120: 
1.26      crook    12121: @example
1.78      anton    12122: assert( 1 1 + 2 = ) \ what we learn in school
                   12123: assert( dup 0<> ) \ assert that the top of stack is not zero
                   12124: assert( false ) \ this code should not be reached
1.21      crook    12125: @end example
                   12126: 
1.78      anton    12127: The need for assertions is different at different times. During
                   12128: debugging, we want more checking, in production we sometimes care more
                   12129: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   12130: becomes a comment. Depending on the importance of an assertion and the
                   12131: time it takes to check it, you may want to turn off some assertions and
                   12132: keep others turned on. Gforth provides several levels of assertions for
                   12133: this purpose:
                   12134: 
                   12135: 
                   12136: doc-assert0(
                   12137: doc-assert1(
                   12138: doc-assert2(
                   12139: doc-assert3(
                   12140: doc-assert(
                   12141: doc-)
1.21      crook    12142: 
                   12143: 
1.78      anton    12144: The variable @code{assert-level} specifies the highest assertions that
                   12145: are turned on. I.e., at the default @code{assert-level} of one,
                   12146: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   12147: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26      crook    12148: 
1.78      anton    12149: The value of @code{assert-level} is evaluated at compile-time, not at
                   12150: run-time. Therefore you cannot turn assertions on or off at run-time;
                   12151: you have to set the @code{assert-level} appropriately before compiling a
                   12152: piece of code. You can compile different pieces of code at different
                   12153: @code{assert-level}s (e.g., a trusted library at level 1 and
                   12154: newly-written code at level 3).
1.26      crook    12155: 
                   12156: 
1.78      anton    12157: doc-assert-level
1.26      crook    12158: 
                   12159: 
1.78      anton    12160: If an assertion fails, a message compatible with Emacs' compilation mode
                   12161: is produced and the execution is aborted (currently with @code{ABORT"}.
                   12162: If there is interest, we will introduce a special throw code. But if you
                   12163: intend to @code{catch} a specific condition, using @code{throw} is
                   12164: probably more appropriate than an assertion).
1.106     anton    12165: 
                   12166: @cindex filenames in assertion output
                   12167: Assertions (and @code{~~}) will usually print the wrong file name if a
                   12168: marker is executed in the same file after their occurance.  They will
                   12169: print @samp{*somewhere*} as file name if a marker is executed in the
                   12170: same file before their occurance.
1.44      crook    12171: 
1.78      anton    12172: Definitions in ANS Forth for these assertion words are provided
                   12173: in @file{compat/assert.fs}.
1.26      crook    12174: 
1.44      crook    12175: 
1.78      anton    12176: @node Singlestep Debugger,  , Assertions, Programming Tools
                   12177: @subsection Singlestep Debugger
                   12178: @cindex singlestep Debugger
                   12179: @cindex debugging Singlestep
1.44      crook    12180: 
1.189     anton    12181: The singlestep debugger works only with the engine @code{gforth-itc}.
1.112     anton    12182: 
1.78      anton    12183: When you create a new word there's often the need to check whether it
                   12184: behaves correctly or not. You can do this by typing @code{dbg
                   12185: badword}. A debug session might look like this:
1.26      crook    12186: 
1.78      anton    12187: @example
                   12188: : badword 0 DO i . LOOP ;  ok
                   12189: 2 dbg badword 
                   12190: : badword  
                   12191: Scanning code...
1.44      crook    12192: 
1.78      anton    12193: Nesting debugger ready!
1.44      crook    12194: 
1.78      anton    12195: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   12196: 400D4740  8049F68 DO             -> [ 0 ] 
                   12197: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   12198: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   12199: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   12200: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   12201: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   12202: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   12203: 400D4758  804B384 ;              ->  ok
                   12204: @end example
1.21      crook    12205: 
1.78      anton    12206: Each line displayed is one step. You always have to hit return to
                   12207: execute the next word that is displayed. If you don't want to execute
                   12208: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   12209: an overview what keys are available:
1.44      crook    12210: 
1.78      anton    12211: @table @i
1.44      crook    12212: 
1.78      anton    12213: @item @key{RET}
                   12214: Next; Execute the next word.
1.21      crook    12215: 
1.78      anton    12216: @item n
                   12217: Nest; Single step through next word.
1.44      crook    12218: 
1.78      anton    12219: @item u
                   12220: Unnest; Stop debugging and execute rest of word. If we got to this word
                   12221: with nest, continue debugging with the calling word.
1.44      crook    12222: 
1.78      anton    12223: @item d
                   12224: Done; Stop debugging and execute rest.
1.21      crook    12225: 
1.78      anton    12226: @item s
                   12227: Stop; Abort immediately.
1.44      crook    12228: 
1.78      anton    12229: @end table
1.44      crook    12230: 
1.78      anton    12231: Debugging large application with this mechanism is very difficult, because
                   12232: you have to nest very deeply into the program before the interesting part
                   12233: begins. This takes a lot of time. 
1.26      crook    12234: 
1.78      anton    12235: To do it more directly put a @code{BREAK:} command into your source code.
                   12236: When program execution reaches @code{BREAK:} the single step debugger is
                   12237: invoked and you have all the features described above.
1.44      crook    12238: 
1.78      anton    12239: If you have more than one part to debug it is useful to know where the
                   12240: program has stopped at the moment. You can do this by the 
                   12241: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   12242: string is typed out when the ``breakpoint'' is reached.
1.44      crook    12243: 
1.26      crook    12244: 
1.78      anton    12245: doc-dbg
                   12246: doc-break:
                   12247: doc-break"
1.44      crook    12248: 
1.150     anton    12249: @c ------------------------------------------------------------
                   12250: @node C Interface, Assembler and Code Words, Programming Tools, Words
                   12251: @section C Interface
                   12252: @cindex C interface
                   12253: @cindex foreign language interface
                   12254: @cindex interface to C functions
                   12255: 
1.178     anton    12256: Note that the C interface is not yet complete; callbacks are missing,
                   12257: as well as a way of declaring structs, unions, and their fields.
1.150     anton    12258: 
                   12259: @menu
                   12260: * Calling C Functions::         
                   12261: * Declaring C Functions::       
1.180     anton    12262: * Calling C function pointers::  
1.196     anton    12263: * Defining library interfaces::  
                   12264: * Declaring OS-level libraries::  
1.150     anton    12265: * Callbacks::                   
1.178     anton    12266: * C interface internals::       
1.155     anton    12267: * Low-Level C Interface Words::  
1.150     anton    12268: @end menu
                   12269: 
1.151     pazsan   12270: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150     anton    12271: @subsection Calling C functions
1.155     anton    12272: @cindex C functions, calls to
                   12273: @cindex calling C functions
1.150     anton    12274: 
1.151     pazsan   12275: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150     anton    12276: can call it as follows: You push the arguments on the stack(s), and
                   12277: then call the word for the C function.  The arguments have to be
                   12278: pushed in the same order as the arguments appear in the C
                   12279: documentation (i.e., the first argument is deepest on the stack).
                   12280: Integer and pointer arguments have to be pushed on the data stack,
                   12281: floating-point arguments on the FP stack; these arguments are consumed
1.155     anton    12282: by the called C function.
1.150     anton    12283: 
1.155     anton    12284: On returning from the C function, the return value, if any, resides on
                   12285: the appropriate stack: an integer return value is pushed on the data
                   12286: stack, an FP return value on the FP stack, and a void return value
                   12287: results in not pushing anything.  Note that most C functions have a
                   12288: return value, even if that is often not used in C; in Forth, you have
                   12289: to @code{drop} this return value explicitly if you do not use it.
1.150     anton    12290: 
1.177     anton    12291: The C interface automatically converts between the C type and the
                   12292: Forth type as necessary, on a best-effort basis (in some cases, there
                   12293: may be some loss).
1.150     anton    12294: 
                   12295: As an example, consider the POSIX function @code{lseek()}:
                   12296: 
                   12297: @example
                   12298: off_t lseek(int fd, off_t offset, int whence);
                   12299: @end example
                   12300: 
                   12301: This function takes three integer arguments, and returns an integer
                   12302: argument, so a Forth call for setting the current file offset to the
                   12303: start of the file could look like this:
                   12304: 
                   12305: @example
                   12306: fd @@ 0 SEEK_SET lseek -1 = if
                   12307:   ... \ error handling
                   12308: then
                   12309: @end example
                   12310: 
                   12311: You might be worried that an @code{off_t} does not fit into a cell, so
                   12312: you could not pass larger offsets to lseek, and might get only a part
1.155     anton    12313: of the return values.  In that case, in your declaration of the
                   12314: function (@pxref{Declaring C Functions}) you should declare it to use
                   12315: double-cells for the off_t argument and return value, and maybe give
                   12316: the resulting Forth word a different name, like @code{dlseek}; the
                   12317: result could be called like this:
1.150     anton    12318: 
                   12319: @example
                   12320: fd @@ 0. SEEK_SET dlseek -1. d= if
                   12321:   ... \ error handling
                   12322: then
                   12323: @end example
                   12324: 
                   12325: Passing and returning structs or unions is currently not supported by
                   12326: our interface@footnote{If you know the calling convention of your C
                   12327: compiler, you usually can call such functions in some way, but that
                   12328: way is usually not portable between platforms, and sometimes not even
                   12329: between C compilers.}.
                   12330: 
1.177     anton    12331: Calling functions with a variable number of arguments (@emph{variadic}
                   12332: functions, e.g., @code{printf()}) is only supported by having you
                   12333: declare one function-calling word for each argument pattern, and
                   12334: calling the appropriate word for the desired pattern.
                   12335: 
1.150     anton    12336: 
1.155     anton    12337: 
1.180     anton    12338: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
1.150     anton    12339: @subsection Declaring C Functions
1.155     anton    12340: @cindex C functions, declarations
                   12341: @cindex declaring C functions
1.150     anton    12342: 
                   12343: Before you can call @code{lseek} or @code{dlseek}, you have to declare
1.177     anton    12344: it.  The declaration consists of two parts: 
                   12345: 
                   12346: @table @b
                   12347: 
                   12348: @item The C part
1.179     anton    12349: is the C declaration of the function, or more typically and portably,
                   12350: a C-style @code{#include} of a file that contains the declaration of
                   12351: the C function.
1.177     anton    12352: 
                   12353: @item The Forth part
                   12354: declares the Forth types of the parameters and the Forth word name
                   12355: corresponding to the C function.
                   12356: 
                   12357: @end table
                   12358: 
                   12359: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
                   12360: declarations are:
                   12361: 
                   12362: @example
                   12363: \c #define _FILE_OFFSET_BITS 64
                   12364: \c #include <sys/types.h>
                   12365: \c #include <unistd.h>
                   12366: c-function lseek lseek n n n -- n
                   12367: c-function dlseek lseek n d n -- d
                   12368: @end example
                   12369: 
1.178     anton    12370: The C part of the declarations is prefixed by @code{\c}, and the rest
1.177     anton    12371: of the line is ordinary C code.  You can use as many lines of C
                   12372: declarations as you like, and they are visible for all further
                   12373: function declarations.
                   12374: 
                   12375: The Forth part declares each interface word with @code{c-function},
                   12376: followed by the Forth name of the word, the C name of the called
                   12377: function, and the stack effect of the word.  The stack effect contains
1.178     anton    12378: an arbitrary number of types of parameters, then @code{--}, and then
1.177     anton    12379: exactly one type for the return value.  The possible types are:
                   12380: 
                   12381: @table @code
                   12382: 
                   12383: @item n
                   12384: single-cell integer
                   12385: 
                   12386: @item a
                   12387: address (single-cell)
                   12388: 
                   12389: @item d
                   12390: double-cell integer
                   12391: 
                   12392: @item r
                   12393: floating-point value
                   12394: