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

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.191     anton      64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007 Free Software Foundation, Inc.
1.29      crook      65: 
1.113     anton      66: @quotation
                     67: Permission is granted to copy, distribute and/or modify this document
                     68: under the terms of the GNU Free Documentation License, Version 1.1 or
                     69: any later version published by the Free Software Foundation; with no
                     70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
                     71: and with the Back-Cover Texts as in (a) below.  A copy of the
                     72: license is included in the section entitled ``GNU Free Documentation
                     73: License.''
                     74: 
                     75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
                     76: this GNU Manual, like GNU software.  Copies published by the Free
                     77: Software Foundation raise funds for GNU development.''
                     78: @end quotation
                     79: @end copying
1.10      anton      80: 
1.113     anton      81: @dircategory Software development
                     82: @direntry
                     83: * Gforth: (gforth).             A fast interpreter for the Forth language.
                     84: @end direntry
                     85: @c The Texinfo manual also recommends doing this, but for Gforth it may
                     86: @c  not make much sense
                     87: @c @dircategory Individual utilities
                     88: @c @direntry
                     89: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
                     90: @c @end direntry
1.1       anton      91: 
                     92: @titlepage
1.113     anton      93: @title Gforth
                     94: @subtitle for version @value{VERSION}, @value{UPDATED}
                     95: @author Neal Crook
                     96: @author Anton Ertl
1.114     anton      97: @author David Kuehling
1.113     anton      98: @author Bernd Paysan
                     99: @author Jens Wilke
1.1       anton     100: @page
                    101: @vskip 0pt plus 1filll
1.113     anton     102: @insertcopying
                    103: @end titlepage
1.1       anton     104: 
1.113     anton     105: @contents
1.1       anton     106: 
1.113     anton     107: @ifnottex
                    108: @node Top, Goals, (dir), (dir)
                    109: @top Gforth
1.1       anton     110: 
1.113     anton     111: @insertcopying
1.49      anton     112: @end ifnottex
1.1       anton     113: 
                    114: @menu
1.26      crook     115: * Goals::                       About the Gforth Project
1.29      crook     116: * Gforth Environment::          Starting (and exiting) Gforth
1.48      anton     117: * Tutorial::                    Hands-on Forth Tutorial
1.21      crook     118: * Introduction::                An introduction to ANS Forth
1.1       anton     119: * Words::                       Forth words available in Gforth
1.24      anton     120: * Error messages::              How to interpret them
1.1       anton     121: * Tools::                       Programming tools
                    122: * ANS conformance::             Implementation-defined options etc.
1.65      anton     123: * Standard vs Extensions::      Should I use extensions?
1.1       anton     124: * Model::                       The abstract machine of Gforth
                    125: * Integrating Gforth::          Forth as scripting language for applications
                    126: * Emacs and Gforth::            The Gforth Mode
                    127: * Image Files::                 @code{.fi} files contain compiled code
                    128: * Engine::                      The inner interpreter and the primitives
1.13      pazsan    129: * Cross Compiler::              The Cross Compiler
1.1       anton     130: * Bugs::                        How to report them
                    131: * Origin::                      Authors and ancestors of Gforth
1.21      crook     132: * Forth-related information::   Books and places to look on the WWW
1.113     anton     133: * Licenses::                    
1.1       anton     134: * Word Index::                  An item for each Forth word
                    135: * Concept Index::               A menu covering many topics
1.12      anton     136: 
1.91      anton     137: @detailmenu
                    138:  --- The Detailed Node Listing ---
1.12      anton     139: 
1.29      crook     140: Gforth Environment
                    141: 
1.32      anton     142: * Invoking Gforth::             Getting in
                    143: * Leaving Gforth::              Getting out
                    144: * Command-line editing::        
1.48      anton     145: * Environment variables::       that affect how Gforth starts up
1.32      anton     146: * Gforth Files::                What gets installed and where
1.112     anton     147: * Gforth in pipes::             
1.48      anton     148: * Startup speed::               When 35ms is not fast enough ...
                    149: 
                    150: Forth Tutorial
                    151: 
                    152: * Starting Gforth Tutorial::    
                    153: * Syntax Tutorial::             
                    154: * Crash Course Tutorial::       
                    155: * Stack Tutorial::              
                    156: * Arithmetics Tutorial::        
                    157: * Stack Manipulation Tutorial::  
                    158: * Using files for Forth code Tutorial::  
                    159: * Comments Tutorial::           
                    160: * Colon Definitions Tutorial::  
                    161: * Decompilation Tutorial::      
                    162: * Stack-Effect Comments Tutorial::  
                    163: * Types Tutorial::              
                    164: * Factoring Tutorial::          
                    165: * Designing the stack effect Tutorial::  
                    166: * Local Variables Tutorial::    
                    167: * Conditional execution Tutorial::  
                    168: * Flags and Comparisons Tutorial::  
                    169: * General Loops Tutorial::      
                    170: * Counted loops Tutorial::      
                    171: * Recursion Tutorial::          
                    172: * Leaving definitions or loops Tutorial::  
                    173: * Return Stack Tutorial::       
                    174: * Memory Tutorial::             
                    175: * Characters and Strings Tutorial::  
                    176: * Alignment Tutorial::          
1.190     anton     177: * Floating Point Tutorial::     
1.87      anton     178: * Files Tutorial::              
1.48      anton     179: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                    180: * Execution Tokens Tutorial::   
                    181: * Exceptions Tutorial::         
                    182: * Defining Words Tutorial::     
                    183: * Arrays and Records Tutorial::  
                    184: * POSTPONE Tutorial::           
                    185: * Literal Tutorial::            
                    186: * Advanced macros Tutorial::    
                    187: * Compilation Tokens Tutorial::  
                    188: * Wordlists and Search Order Tutorial::  
1.29      crook     189: 
1.24      anton     190: An Introduction to ANS Forth
                    191: 
1.67      anton     192: * Introducing the Text Interpreter::  
                    193: * Stacks and Postfix notation::  
                    194: * Your first definition::       
                    195: * How does that work?::         
                    196: * Forth is written in Forth::   
                    197: * Review - elements of a Forth system::  
                    198: * Where to go next::            
                    199: * Exercises::                   
1.24      anton     200: 
1.12      anton     201: Forth Words
                    202: 
                    203: * Notation::                    
1.65      anton     204: * Case insensitivity::          
                    205: * Comments::                    
                    206: * Boolean Flags::               
1.12      anton     207: * Arithmetic::                  
                    208: * Stack Manipulation::          
                    209: * Memory::                      
                    210: * Control Structures::          
                    211: * Defining Words::              
1.65      anton     212: * Interpretation and Compilation Semantics::  
1.47      crook     213: * Tokens for Words::            
1.81      anton     214: * Compiling words::             
1.65      anton     215: * The Text Interpreter::        
1.111     anton     216: * The Input Stream::            
1.65      anton     217: * Word Lists::                  
                    218: * Environmental Queries::       
1.12      anton     219: * Files::                       
                    220: * Blocks::                      
                    221: * Other I/O::                   
1.121     anton     222: * OS command line arguments::   
1.78      anton     223: * Locals::                      
                    224: * Structures::                  
                    225: * Object-oriented Forth::       
1.12      anton     226: * Programming Tools::           
1.150     anton     227: * C Interface::                 
1.12      anton     228: * Assembler and Code Words::    
                    229: * Threading Words::             
1.65      anton     230: * Passing Commands to the OS::  
                    231: * Keeping track of Time::       
                    232: * Miscellaneous Words::         
1.12      anton     233: 
                    234: Arithmetic
                    235: 
                    236: * Single precision::            
1.67      anton     237: * Double precision::            Double-cell integer arithmetic
1.12      anton     238: * Bitwise operations::          
1.67      anton     239: * Numeric comparison::          
1.32      anton     240: * Mixed precision::             Operations with single and double-cell integers
1.12      anton     241: * Floating Point::              
                    242: 
                    243: Stack Manipulation
                    244: 
                    245: * Data stack::                  
                    246: * Floating point stack::        
                    247: * Return stack::                
                    248: * Locals stack::                
                    249: * Stack pointer manipulation::  
                    250: 
                    251: Memory
                    252: 
1.32      anton     253: * Memory model::                
                    254: * Dictionary allocation::       
                    255: * Heap Allocation::             
                    256: * Memory Access::               
                    257: * Address arithmetic::          
                    258: * Memory Blocks::               
1.12      anton     259: 
                    260: Control Structures
                    261: 
1.41      anton     262: * Selection::                   IF ... ELSE ... ENDIF
                    263: * Simple Loops::                BEGIN ...
1.32      anton     264: * Counted Loops::               DO
1.67      anton     265: * Arbitrary control structures::  
                    266: * Calls and returns::           
1.12      anton     267: * Exception Handling::          
                    268: 
                    269: Defining Words
                    270: 
1.67      anton     271: * CREATE::                      
1.44      crook     272: * Variables::                   Variables and user variables
1.67      anton     273: * Constants::                   
1.44      crook     274: * Values::                      Initialised variables
1.67      anton     275: * Colon Definitions::           
1.44      crook     276: * Anonymous Definitions::       Definitions without names
1.71      anton     277: * Supplying names::             Passing definition names as strings
1.67      anton     278: * User-defined Defining Words::  
1.170     pazsan    279: * Deferred Words::              Allow forward references
1.67      anton     280: * Aliases::                     
1.47      crook     281: 
1.63      anton     282: User-defined Defining Words
                    283: 
                    284: * CREATE..DOES> applications::  
                    285: * CREATE..DOES> details::       
                    286: * Advanced does> usage example::  
1.155     anton     287: * Const-does>::                 
1.63      anton     288: 
1.47      crook     289: Interpretation and Compilation Semantics
                    290: 
1.67      anton     291: * Combined words::              
1.12      anton     292: 
1.71      anton     293: Tokens for Words
                    294: 
                    295: * Execution token::             represents execution/interpretation semantics
                    296: * Compilation token::           represents compilation semantics
                    297: * Name token::                  represents named words
                    298: 
1.82      anton     299: Compiling words
                    300: 
                    301: * Literals::                    Compiling data values
                    302: * Macros::                      Compiling words
                    303: 
1.21      crook     304: The Text Interpreter
                    305: 
1.67      anton     306: * Input Sources::               
                    307: * Number Conversion::           
                    308: * Interpret/Compile states::    
                    309: * Interpreter Directives::      
1.21      crook     310: 
1.26      crook     311: Word Lists
                    312: 
1.75      anton     313: * Vocabularies::                
1.67      anton     314: * Why use word lists?::         
1.75      anton     315: * Word list example::           
1.26      crook     316: 
                    317: Files
                    318: 
1.48      anton     319: * Forth source files::          
                    320: * General files::               
1.167     anton     321: * Redirection::                 
1.48      anton     322: * Search Paths::                
                    323: 
                    324: Search Paths
                    325: 
1.75      anton     326: * Source Search Paths::         
1.26      crook     327: * General Search Paths::        
                    328: 
                    329: Other I/O
                    330: 
1.32      anton     331: * Simple numeric output::       Predefined formats
                    332: * Formatted numeric output::    Formatted (pictured) output
                    333: * String Formats::              How Forth stores strings in memory
1.67      anton     334: * Displaying characters and strings::  Other stuff
1.178     anton     335: * Terminal output::             Cursor positioning etc.
1.181     anton     336: * Single-key input::            
                    337: * Line input and conversion::   
1.112     anton     338: * Pipes::                       How to create your own pipes
1.149     pazsan    339: * Xchars and Unicode::          Non-ASCII characters
1.26      crook     340: 
                    341: Locals
                    342: 
                    343: * Gforth locals::               
                    344: * ANS Forth locals::            
                    345: 
                    346: Gforth locals
                    347: 
                    348: * Where are locals visible by name?::  
                    349: * How long do locals live?::    
1.78      anton     350: * Locals programming style::    
                    351: * Locals implementation::       
1.26      crook     352: 
1.12      anton     353: Structures
                    354: 
                    355: * Why explicit structure support?::  
                    356: * Structure Usage::             
                    357: * Structure Naming Convention::  
                    358: * Structure Implementation::    
                    359: * Structure Glossary::          
1.183     anton     360: * Forth200x Structures::        
1.12      anton     361: 
                    362: Object-oriented Forth
                    363: 
1.48      anton     364: * Why object-oriented programming?::  
                    365: * Object-Oriented Terminology::  
                    366: * Objects::                     
                    367: * OOF::                         
                    368: * Mini-OOF::                    
1.23      crook     369: * Comparison with other object models::  
1.12      anton     370: 
1.24      anton     371: The @file{objects.fs} model
1.12      anton     372: 
                    373: * Properties of the Objects model::  
                    374: * Basic Objects Usage::         
1.41      anton     375: * The Objects base class::      
1.12      anton     376: * Creating objects::            
                    377: * Object-Oriented Programming Style::  
                    378: * Class Binding::               
                    379: * Method conveniences::         
                    380: * Classes and Scoping::         
1.41      anton     381: * Dividing classes::            
1.12      anton     382: * Object Interfaces::           
                    383: * Objects Implementation::      
                    384: * Objects Glossary::            
                    385: 
1.24      anton     386: The @file{oof.fs} model
1.12      anton     387: 
1.67      anton     388: * Properties of the OOF model::  
                    389: * Basic OOF Usage::             
                    390: * The OOF base class::          
                    391: * Class Declaration::           
                    392: * Class Implementation::        
1.12      anton     393: 
1.24      anton     394: The @file{mini-oof.fs} model
1.23      crook     395: 
1.48      anton     396: * Basic Mini-OOF Usage::        
                    397: * Mini-OOF Example::            
                    398: * Mini-OOF Implementation::     
1.23      crook     399: 
1.78      anton     400: Programming Tools
                    401: 
1.150     anton     402: * Examining::                   Data and Code.
                    403: * Forgetting words::            Usually before reloading.
1.78      anton     404: * Debugging::                   Simple and quick.
                    405: * Assertions::                  Making your programs self-checking.
                    406: * Singlestep Debugger::         Executing your program word by word.
                    407: 
1.155     anton     408: C Interface
                    409: 
                    410: * Calling C Functions::         
                    411: * Declaring C Functions::       
1.180     anton     412: * Calling C function pointers::  
1.196   ! anton     413: * Defining library interfaces::  
        !           414: * Declaring OS-level libraries::  
1.155     anton     415: * Callbacks::                   
1.178     anton     416: * C interface internals::       
1.155     anton     417: * Low-Level C Interface Words::  
                    418: 
1.78      anton     419: Assembler and Code Words
                    420: 
                    421: * Code and ;code::              
                    422: * Common Assembler::            Assembler Syntax
                    423: * Common Disassembler::         
                    424: * 386 Assembler::               Deviations and special cases
                    425: * Alpha Assembler::             Deviations and special cases
                    426: * MIPS assembler::              Deviations and special cases
1.167     anton     427: * PowerPC assembler::           Deviations and special cases
1.193     dvdkhlng  428: * ARM Assembler::               Deviations and special cases
1.78      anton     429: * Other assemblers::            How to write them
                    430: 
1.12      anton     431: Tools
                    432: 
                    433: * ANS Report::                  Report the words used, sorted by wordset.
1.127     anton     434: * Stack depth changes::         Where does this stack item come from?
1.12      anton     435: 
                    436: ANS conformance
                    437: 
                    438: * The Core Words::              
                    439: * The optional Block word set::  
                    440: * The optional Double Number word set::  
                    441: * The optional Exception word set::  
                    442: * The optional Facility word set::  
                    443: * The optional File-Access word set::  
                    444: * The optional Floating-Point word set::  
                    445: * The optional Locals word set::  
                    446: * The optional Memory-Allocation word set::  
                    447: * The optional Programming-Tools word set::  
                    448: * The optional Search-Order word set::  
                    449: 
                    450: The Core Words
                    451: 
                    452: * core-idef::                   Implementation Defined Options                   
                    453: * core-ambcond::                Ambiguous Conditions                
                    454: * core-other::                  Other System Documentation                  
                    455: 
                    456: The optional Block word set
                    457: 
                    458: * block-idef::                  Implementation Defined Options
                    459: * block-ambcond::               Ambiguous Conditions               
                    460: * block-other::                 Other System Documentation                 
                    461: 
                    462: The optional Double Number word set
                    463: 
                    464: * double-ambcond::              Ambiguous Conditions              
                    465: 
                    466: The optional Exception word set
                    467: 
                    468: * exception-idef::              Implementation Defined Options              
                    469: 
                    470: The optional Facility word set
                    471: 
                    472: * facility-idef::               Implementation Defined Options               
                    473: * facility-ambcond::            Ambiguous Conditions            
                    474: 
                    475: The optional File-Access word set
                    476: 
                    477: * file-idef::                   Implementation Defined Options
                    478: * file-ambcond::                Ambiguous Conditions                
                    479: 
                    480: The optional Floating-Point word set
                    481: 
                    482: * floating-idef::               Implementation Defined Options
                    483: * floating-ambcond::            Ambiguous Conditions            
                    484: 
                    485: The optional Locals word set
                    486: 
                    487: * locals-idef::                 Implementation Defined Options                 
                    488: * locals-ambcond::              Ambiguous Conditions              
                    489: 
                    490: The optional Memory-Allocation word set
                    491: 
                    492: * memory-idef::                 Implementation Defined Options                 
                    493: 
                    494: The optional Programming-Tools word set
                    495: 
                    496: * programming-idef::            Implementation Defined Options            
                    497: * programming-ambcond::         Ambiguous Conditions         
                    498: 
                    499: The optional Search-Order word set
                    500: 
                    501: * search-idef::                 Implementation Defined Options                 
                    502: * search-ambcond::              Ambiguous Conditions              
                    503: 
1.109     anton     504: Emacs and Gforth
                    505: 
                    506: * Installing gforth.el::        Making Emacs aware of Forth.
                    507: * Emacs Tags::                  Viewing the source of a word in Emacs.
                    508: * Hilighting::                  Making Forth code look prettier.
                    509: * Auto-Indentation::            Customizing auto-indentation.
                    510: * Blocks Files::                Reading and writing blocks files.
                    511: 
1.12      anton     512: Image Files
                    513: 
1.24      anton     514: * Image Licensing Issues::      Distribution terms for images.
                    515: * Image File Background::       Why have image files?
1.67      anton     516: * Non-Relocatable Image Files::  don't always work.
1.24      anton     517: * Data-Relocatable Image Files::  are better.
1.67      anton     518: * Fully Relocatable Image Files::  better yet.
1.24      anton     519: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.32      anton     520: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.24      anton     521: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     522: 
                    523: Fully Relocatable Image Files
                    524: 
1.27      crook     525: * gforthmi::                    The normal way
1.12      anton     526: * cross.fs::                    The hard way
                    527: 
                    528: Engine
                    529: 
                    530: * Portability::                 
                    531: * Threading::                   
                    532: * Primitives::                  
                    533: * Performance::                 
                    534: 
                    535: Threading
                    536: 
                    537: * Scheduling::                  
                    538: * Direct or Indirect Threaded?::  
1.109     anton     539: * Dynamic Superinstructions::   
1.12      anton     540: * DOES>::                       
                    541: 
                    542: Primitives
                    543: 
                    544: * Automatic Generation::        
                    545: * TOS Optimization::            
                    546: * Produced code::               
1.13      pazsan    547: 
                    548: Cross Compiler
                    549: 
1.67      anton     550: * Using the Cross Compiler::    
                    551: * How the Cross Compiler Works::  
1.13      pazsan    552: 
1.113     anton     553: Licenses
                    554: 
                    555: * GNU Free Documentation License::  License for copying this manual.
1.192     anton     556: * Copying::                     GPL (for copying this software).
1.113     anton     557: 
1.24      anton     558: @end detailmenu
1.1       anton     559: @end menu
                    560: 
1.113     anton     561: @c ----------------------------------------------------------
1.1       anton     562: @iftex
                    563: @unnumbered Preface
                    564: @cindex Preface
1.21      crook     565: This manual documents Gforth. Some introductory material is provided for
                    566: readers who are unfamiliar with Forth or who are migrating to Gforth
                    567: from other Forth compilers. However, this manual is primarily a
                    568: reference manual.
1.1       anton     569: @end iftex
                    570: 
1.28      crook     571: @comment TODO much more blurb here.
1.26      crook     572: 
                    573: @c ******************************************************************
1.113     anton     574: @node Goals, Gforth Environment, Top, Top
1.26      crook     575: @comment node-name,     next,           previous, up
                    576: @chapter Goals of Gforth
                    577: @cindex goals of the Gforth project
                    578: The goal of the Gforth Project is to develop a standard model for
                    579: ANS Forth. This can be split into several subgoals:
                    580: 
                    581: @itemize @bullet
                    582: @item
                    583: Gforth should conform to the ANS Forth Standard.
                    584: @item
                    585: It should be a model, i.e. it should define all the
                    586: implementation-dependent things.
                    587: @item
                    588: It should become standard, i.e. widely accepted and used. This goal
                    589: is the most difficult one.
                    590: @end itemize
                    591: 
                    592: To achieve these goals Gforth should be
                    593: @itemize @bullet
                    594: @item
                    595: Similar to previous models (fig-Forth, F83)
                    596: @item
                    597: Powerful. It should provide for all the things that are considered
                    598: necessary today and even some that are not yet considered necessary.
                    599: @item
                    600: Efficient. It should not get the reputation of being exceptionally
                    601: slow.
                    602: @item
                    603: Free.
                    604: @item
                    605: Available on many machines/easy to port.
                    606: @end itemize
                    607: 
                    608: Have we achieved these goals? Gforth conforms to the ANS Forth
                    609: standard. It may be considered a model, but we have not yet documented
                    610: which parts of the model are stable and which parts we are likely to
                    611: change. It certainly has not yet become a de facto standard, but it
                    612: appears to be quite popular. It has some similarities to and some
                    613: differences from previous models. It has some powerful features, but not
                    614: yet everything that we envisioned. We certainly have achieved our
1.65      anton     615: execution speed goals (@pxref{Performance})@footnote{However, in 1998
                    616: the bar was raised when the major commercial Forth vendors switched to
                    617: native code compilers.}.  It is free and available on many machines.
1.29      crook     618: 
1.26      crook     619: @c ******************************************************************
1.48      anton     620: @node Gforth Environment, Tutorial, Goals, Top
1.29      crook     621: @chapter Gforth Environment
                    622: @cindex Gforth environment
1.21      crook     623: 
1.45      crook     624: Note: ultimately, the Gforth man page will be auto-generated from the
1.29      crook     625: material in this chapter.
1.21      crook     626: 
                    627: @menu
1.29      crook     628: * Invoking Gforth::             Getting in
                    629: * Leaving Gforth::              Getting out
                    630: * Command-line editing::        
1.48      anton     631: * Environment variables::       that affect how Gforth starts up
1.29      crook     632: * Gforth Files::                What gets installed and where
1.112     anton     633: * Gforth in pipes::             
1.48      anton     634: * Startup speed::               When 35ms is not fast enough ...
1.21      crook     635: @end menu
                    636: 
1.49      anton     637: For related information about the creation of images see @ref{Image Files}.
1.29      crook     638: 
1.21      crook     639: @comment ----------------------------------------------
1.48      anton     640: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29      crook     641: @section Invoking Gforth
                    642: @cindex invoking Gforth
                    643: @cindex running Gforth
                    644: @cindex command-line options
                    645: @cindex options on the command line
                    646: @cindex flags on the command line
1.21      crook     647: 
1.30      anton     648: Gforth is made up of two parts; an executable ``engine'' (named
1.109     anton     649: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30      anton     650: will usually just say @code{gforth} -- this automatically loads the
                    651: default image file @file{gforth.fi}. In many other cases the default
                    652: Gforth image will be invoked like this:
1.21      crook     653: @example
1.30      anton     654: gforth [file | -e forth-code] ...
1.21      crook     655: @end example
1.29      crook     656: @noindent
                    657: This interprets the contents of the files and the Forth code in the order they
                    658: are given.
1.21      crook     659: 
1.109     anton     660: In addition to the @command{gforth} engine, there is also an engine
                    661: called @command{gforth-fast}, which is faster, but gives less
                    662: informative error messages (@pxref{Error messages}) and may catch some
1.166     anton     663: errors (in particular, stack underflows and integer division errors)
                    664: later or not at all.  You should use it for debugged,
1.109     anton     665: performance-critical programs.
                    666: 
                    667: Moreover, there is an engine called @command{gforth-itc}, which is
                    668: useful in some backwards-compatibility situations (@pxref{Direct or
                    669: Indirect Threaded?}).
1.30      anton     670: 
1.29      crook     671: In general, the command line looks like this:
1.21      crook     672: 
                    673: @example
1.30      anton     674: gforth[-fast] [engine options] [image options]
1.21      crook     675: @end example
                    676: 
1.30      anton     677: The engine options must come before the rest of the command
1.29      crook     678: line. They are:
1.26      crook     679: 
1.29      crook     680: @table @code
                    681: @cindex -i, command-line option
                    682: @cindex --image-file, command-line option
                    683: @item --image-file @i{file}
                    684: @itemx -i @i{file}
                    685: Loads the Forth image @i{file} instead of the default
                    686: @file{gforth.fi} (@pxref{Image Files}).
1.21      crook     687: 
1.39      anton     688: @cindex --appl-image, command-line option
                    689: @item --appl-image @i{file}
                    690: Loads the image @i{file} and leaves all further command-line arguments
1.65      anton     691: to the image (instead of processing them as engine options).  This is
                    692: useful for building executable application images on Unix, built with
1.39      anton     693: @code{gforthmi --application ...}.
                    694: 
1.29      crook     695: @cindex --path, command-line option
                    696: @cindex -p, command-line option
                    697: @item --path @i{path}
                    698: @itemx -p @i{path}
                    699: Uses @i{path} for searching the image file and Forth source code files
                    700: instead of the default in the environment variable @code{GFORTHPATH} or
                    701: the path specified at installation time (e.g.,
                    702: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                    703: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook     704: 
1.29      crook     705: @cindex --dictionary-size, command-line option
                    706: @cindex -m, command-line option
                    707: @cindex @i{size} parameters for command-line options
                    708: @cindex size of the dictionary and the stacks
                    709: @item --dictionary-size @i{size}
                    710: @itemx -m @i{size}
                    711: Allocate @i{size} space for the Forth dictionary space instead of
                    712: using the default specified in the image (typically 256K). The
                    713: @i{size} specification for this and subsequent options consists of
                    714: an integer and a unit (e.g.,
                    715: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
                    716: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                    717: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                    718: @code{e} is used.
1.21      crook     719: 
1.29      crook     720: @cindex --data-stack-size, command-line option
                    721: @cindex -d, command-line option
                    722: @item --data-stack-size @i{size}
                    723: @itemx -d @i{size}
                    724: Allocate @i{size} space for the data stack instead of using the
                    725: default specified in the image (typically 16K).
1.21      crook     726: 
1.29      crook     727: @cindex --return-stack-size, command-line option
                    728: @cindex -r, command-line option
                    729: @item --return-stack-size @i{size}
                    730: @itemx -r @i{size}
                    731: Allocate @i{size} space for the return stack instead of using the
                    732: default specified in the image (typically 15K).
1.21      crook     733: 
1.29      crook     734: @cindex --fp-stack-size, command-line option
                    735: @cindex -f, command-line option
                    736: @item --fp-stack-size @i{size}
                    737: @itemx -f @i{size}
                    738: Allocate @i{size} space for the floating point stack instead of
                    739: using the default specified in the image (typically 15.5K). In this case
                    740: the unit specifier @code{e} refers to floating point numbers.
1.21      crook     741: 
1.48      anton     742: @cindex --locals-stack-size, command-line option
                    743: @cindex -l, command-line option
                    744: @item --locals-stack-size @i{size}
                    745: @itemx -l @i{size}
                    746: Allocate @i{size} space for the locals stack instead of using the
                    747: default specified in the image (typically 14.5K).
                    748: 
1.176     anton     749: @cindex --vm-commit, command-line option
                    750: @cindex overcommit memory for dictionary and stacks
                    751: @cindex memory overcommit for dictionary and stacks
                    752: @item --vm-commit
                    753: Normally, Gforth tries to start up even if there is not enough virtual
                    754: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
                    755: on OSs that support it); so you can ask for a really big dictionary
                    756: and/or stacks, and as long as you don't use more virtual memory than
                    757: is available, everything will be fine (but if you use more, processes
                    758: get killed).  With this option you just use the default allocation
                    759: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
                    760: means that you cannot and should not ask for as big dictionary and
                    761: stacks, but once Gforth successfully starts up, out-of-memory won't
                    762: kill it.
                    763: 
1.48      anton     764: @cindex -h, command-line option
                    765: @cindex --help, command-line option
                    766: @item --help
                    767: @itemx -h
                    768: Print a message about the command-line options
                    769: 
                    770: @cindex -v, command-line option
                    771: @cindex --version, command-line option
                    772: @item --version
                    773: @itemx -v
                    774: Print version and exit
                    775: 
                    776: @cindex --debug, command-line option
                    777: @item --debug
                    778: Print some information useful for debugging on startup.
                    779: 
                    780: @cindex --offset-image, command-line option
                    781: @item --offset-image
                    782: Start the dictionary at a slightly different position than would be used
                    783: otherwise (useful for creating data-relocatable images,
                    784: @pxref{Data-Relocatable Image Files}).
                    785: 
                    786: @cindex --no-offset-im, command-line option
                    787: @item --no-offset-im
                    788: Start the dictionary at the normal position.
                    789: 
                    790: @cindex --clear-dictionary, command-line option
                    791: @item --clear-dictionary
                    792: Initialize all bytes in the dictionary to 0 before loading the image
                    793: (@pxref{Data-Relocatable Image Files}).
                    794: 
                    795: @cindex --die-on-signal, command-line-option
                    796: @item --die-on-signal
                    797: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                    798: or the segmentation violation SIGSEGV) by translating it into a Forth
                    799: @code{THROW}. With this option, Gforth exits if it receives such a
                    800: signal. This option is useful when the engine and/or the image might be
                    801: severely broken (such that it causes another signal before recovering
                    802: from the first); this option avoids endless loops in such cases.
1.109     anton     803: 
1.119     anton     804: @cindex --no-dynamic, command-line option
                    805: @cindex --dynamic, command-line option
1.109     anton     806: @item --no-dynamic
                    807: @item --dynamic
                    808: Disable or enable dynamic superinstructions with replication
                    809: (@pxref{Dynamic Superinstructions}).
                    810: 
1.119     anton     811: @cindex --no-super, command-line option
1.109     anton     812: @item --no-super
1.110     anton     813: Disable dynamic superinstructions, use just dynamic replication; this is
                    814: useful if you want to patch threaded code (@pxref{Dynamic
                    815: Superinstructions}).
1.119     anton     816: 
                    817: @cindex --ss-number, command-line option
                    818: @item --ss-number=@var{N}
                    819: Use only the first @var{N} static superinstructions compiled into the
                    820: engine (default: use them all; note that only @code{gforth-fast} has
                    821: any).  This option is useful for measuring the performance impact of
                    822: static superinstructions.
                    823: 
                    824: @cindex --ss-min-..., command-line options
                    825: @item --ss-min-codesize
                    826: @item --ss-min-ls
                    827: @item --ss-min-lsu
                    828: @item --ss-min-nexts
                    829: Use specified metric for determining the cost of a primitive or static
                    830: superinstruction for static superinstruction selection.  @code{Codesize}
                    831: is the native code size of the primive or static superinstruction,
                    832: @code{ls} is the number of loads and stores, @code{lsu} is the number of
                    833: loads, stores, and updates, and @code{nexts} is the number of dispatches
                    834: (not taking dynamic superinstructions into account), i.e. every
                    835: primitive or static superinstruction has cost 1. Default:
                    836: @code{codesize} if you use dynamic code generation, otherwise
                    837: @code{nexts}.
                    838: 
                    839: @cindex --ss-greedy, command-line option
                    840: @item --ss-greedy
                    841: This option is useful for measuring the performance impact of static
                    842: superinstructions.  By default, an optimal shortest-path algorithm is
                    843: used for selecting static superinstructions.  With @option{--ss-greedy}
                    844: this algorithm is modified to assume that anything after the static
                    845: superinstruction currently under consideration is not combined into
                    846: static superinstructions.  With @option{--ss-min-nexts} this produces
                    847: the same result as a greedy algorithm that always selects the longest
                    848: superinstruction available at the moment.  E.g., if there are
                    849: superinstructions AB and BCD, then for the sequence A B C D the optimal
                    850: algorithm will select A BCD and the greedy algorithm will select AB C D.
                    851: 
                    852: @cindex --print-metrics, command-line option
                    853: @item --print-metrics
                    854: Prints some metrics used during static superinstruction selection:
                    855: @code{code size} is the actual size of the dynamically generated code.
                    856: @code{Metric codesize} is the sum of the codesize metrics as seen by
                    857: static superinstruction selection; there is a difference from @code{code
                    858: size}, because not all primitives and static superinstructions are
                    859: compiled into dynamically generated code, and because of markers.  The
                    860: other metrics correspond to the @option{ss-min-...} options.  This
                    861: option is useful for evaluating the effects of the @option{--ss-...}
                    862: options.
1.109     anton     863: 
1.48      anton     864: @end table
                    865: 
                    866: @cindex loading files at startup
                    867: @cindex executing code on startup
                    868: @cindex batch processing with Gforth
                    869: As explained above, the image-specific command-line arguments for the
                    870: default image @file{gforth.fi} consist of a sequence of filenames and
                    871: @code{-e @var{forth-code}} options that are interpreted in the sequence
                    872: in which they are given. The @code{-e @var{forth-code}} or
1.121     anton     873: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
                    874: option takes only one argument; if you want to evaluate more Forth
                    875: words, you have to quote them or use @code{-e} several times. To exit
1.48      anton     876: after processing the command line (instead of entering interactive mode)
1.121     anton     877: append @code{-e bye} to the command line.  You can also process the
                    878: command-line arguments with a Forth program (@pxref{OS command line
                    879: arguments}).
1.48      anton     880: 
                    881: @cindex versions, invoking other versions of Gforth
                    882: If you have several versions of Gforth installed, @code{gforth} will
                    883: invoke the version that was installed last. @code{gforth-@i{version}}
                    884: invokes a specific version. If your environment contains the variable
                    885: @code{GFORTHPATH}, you may want to override it by using the
                    886: @code{--path} option.
                    887: 
                    888: Not yet implemented:
                    889: On startup the system first executes the system initialization file
                    890: (unless the option @code{--no-init-file} is given; note that the system
                    891: resulting from using this option may not be ANS Forth conformant). Then
                    892: the user initialization file @file{.gforth.fs} is executed, unless the
1.62      crook     893: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48      anton     894: then in @file{~}, then in the normal path (see above).
                    895: 
                    896: 
                    897: 
                    898: @comment ----------------------------------------------
                    899: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
                    900: @section Leaving Gforth
                    901: @cindex Gforth - leaving
                    902: @cindex leaving Gforth
                    903: 
                    904: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
                    905: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
                    906: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49      anton     907: data are discarded.  For ways of saving the state of the system before
                    908: leaving Gforth see @ref{Image Files}.
1.48      anton     909: 
                    910: doc-bye
                    911: 
                    912: 
                    913: @comment ----------------------------------------------
1.65      anton     914: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48      anton     915: @section Command-line editing
                    916: @cindex command-line editing
                    917: 
                    918: Gforth maintains a history file that records every line that you type to
                    919: the text interpreter. This file is preserved between sessions, and is
                    920: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
                    921: repeatedly you can recall successively older commands from this (or
                    922: previous) session(s). The full list of command-line editing facilities is:
                    923: 
                    924: @itemize @bullet
                    925: @item
                    926: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
                    927: commands from the history buffer.
                    928: @item
                    929: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
                    930: from the history buffer.
                    931: @item
                    932: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
                    933: @item
                    934: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
                    935: @item
                    936: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
                    937: closing up the line.
                    938: @item
                    939: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
                    940: @item
                    941: @kbd{Ctrl-a} to move the cursor to the start of the line.
                    942: @item
                    943: @kbd{Ctrl-e} to move the cursor to the end of the line.
                    944: @item
                    945: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
                    946: line.
                    947: @item
                    948: @key{TAB} to step through all possible full-word completions of the word
                    949: currently being typed.
                    950: @item
1.65      anton     951: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
                    952: using @code{bye}). 
                    953: @item
                    954: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
                    955: character under the cursor.
1.48      anton     956: @end itemize
                    957: 
                    958: When editing, displayable characters are inserted to the left of the
                    959: cursor position; the line is always in ``insert'' (as opposed to
                    960: ``overstrike'') mode.
                    961: 
                    962: @cindex history file
                    963: @cindex @file{.gforth-history}
                    964: On Unix systems, the history file is @file{~/.gforth-history} by
                    965: default@footnote{i.e. it is stored in the user's home directory.}. You
                    966: can find out the name and location of your history file using:
                    967: 
                    968: @example 
                    969: history-file type \ Unix-class systems
                    970: 
                    971: history-file type \ Other systems
                    972: history-dir  type
                    973: @end example
                    974: 
                    975: If you enter long definitions by hand, you can use a text editor to
                    976: paste them out of the history file into a Forth source file for reuse at
                    977: a later time.
                    978: 
                    979: Gforth never trims the size of the history file, so you should do this
                    980: periodically, if necessary.
                    981: 
                    982: @comment this is all defined in history.fs
                    983: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
                    984: @comment chosen?
                    985: 
                    986: 
                    987: @comment ----------------------------------------------
1.65      anton     988: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48      anton     989: @section Environment variables
                    990: @cindex environment variables
                    991: 
                    992: Gforth uses these environment variables:
                    993: 
                    994: @itemize @bullet
                    995: @item
                    996: @cindex @code{GFORTHHIST} -- environment variable
                    997: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
                    998: open/create the history file, @file{.gforth-history}. Default:
                    999: @code{$HOME}.
                   1000: 
                   1001: @item
                   1002: @cindex @code{GFORTHPATH} -- environment variable
                   1003: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
                   1004: for Forth source-code files.
                   1005: 
                   1006: @item
1.147     anton    1007: @cindex @code{LANG} -- environment variable
                   1008: @code{LANG} -- see @code{LC_CTYPE}
                   1009: 
                   1010: @item
                   1011: @cindex @code{LC_ALL} -- environment variable
                   1012: @code{LC_ALL} -- see @code{LC_CTYPE}
                   1013: 
                   1014: @item
                   1015: @cindex @code{LC_CTYPE} -- environment variable
                   1016: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
                   1017: startup, Gforth uses the UTF-8 encoding for strings internally and
                   1018: expects its input and produces its output in UTF-8 encoding, otherwise
                   1019: the encoding is 8bit (see @pxref{Xchars and Unicode}).  If this
                   1020: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
                   1021: that is unset, in @code{LANG}.
                   1022: 
                   1023: @item
1.129     anton    1024: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
                   1025: 
                   1026: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
                   1027: of @code{system} before passing it to C's @code{system()}.  Default:
1.130     anton    1028: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs.  The prefix
1.129     anton    1029: and the command are directly concatenated, so if a space between them is
                   1030: necessary, append it to the prefix.
                   1031: 
                   1032: @item
1.48      anton    1033: @cindex @code{GFORTH} -- environment variable
1.49      anton    1034: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1035: 
                   1036: @item
                   1037: @cindex @code{GFORTHD} -- environment variable
1.62      crook    1038: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1039: 
                   1040: @item
                   1041: @cindex @code{TMP}, @code{TEMP} - environment variable
                   1042: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
                   1043: location for the history file.
                   1044: @end itemize
                   1045: 
                   1046: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
                   1047: @comment mentioning these.
                   1048: 
                   1049: All the Gforth environment variables default to sensible values if they
                   1050: are not set.
                   1051: 
                   1052: 
                   1053: @comment ----------------------------------------------
1.112     anton    1054: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48      anton    1055: @section Gforth files
                   1056: @cindex Gforth files
                   1057: 
                   1058: When you install Gforth on a Unix system, it installs files in these
                   1059: locations by default:
                   1060: 
                   1061: @itemize @bullet
                   1062: @item
                   1063: @file{/usr/local/bin/gforth}
                   1064: @item
                   1065: @file{/usr/local/bin/gforthmi}
                   1066: @item
                   1067: @file{/usr/local/man/man1/gforth.1} - man page.
                   1068: @item
                   1069: @file{/usr/local/info} - the Info version of this manual.
                   1070: @item
                   1071: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
                   1072: @item
                   1073: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
                   1074: @item
                   1075: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
                   1076: @item
                   1077: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
                   1078: @end itemize
                   1079: 
                   1080: You can select different places for installation by using
                   1081: @code{configure} options (listed with @code{configure --help}).
                   1082: 
                   1083: @comment ----------------------------------------------
1.112     anton    1084: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
                   1085: @section Gforth in pipes
                   1086: @cindex pipes, Gforth as part of
                   1087: 
                   1088: Gforth can be used in pipes created elsewhere (described here).  It can
                   1089: also create pipes on its own (@pxref{Pipes}).
                   1090: 
                   1091: @cindex input from pipes
                   1092: If you pipe into Gforth, your program should read with @code{read-file}
                   1093: or @code{read-line} from @code{stdin} (@pxref{General files}).
                   1094: @code{Key} does not recognize the end of input.  Words like
                   1095: @code{accept} echo the input and are therefore usually not useful for
                   1096: reading from a pipe.  You have to invoke the Forth program with an OS
                   1097: command-line option, as you have no chance to use the Forth command line
                   1098: (the text interpreter would try to interpret the pipe input).
                   1099: 
                   1100: @cindex output in pipes
                   1101: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
                   1102: 
                   1103: @cindex silent exiting from Gforth
                   1104: When you write to a pipe that has been closed at the other end, Gforth
                   1105: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
                   1106: into the exception @code{broken-pipe-error}.  If your application does
                   1107: not catch that exception, the system catches it and exits, usually
                   1108: silently (unless you were working on the Forth command line; then it
                   1109: prints an error message and exits).  This is usually the desired
                   1110: behaviour.
                   1111: 
                   1112: If you do not like this behaviour, you have to catch the exception
                   1113: yourself, and react to it.
                   1114: 
                   1115: Here's an example of an invocation of Gforth that is usable in a pipe:
                   1116: 
                   1117: @example
                   1118: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
                   1119:  type repeat ; foo bye"
                   1120: @end example
                   1121: 
                   1122: This example just copies the input verbatim to the output.  A very
                   1123: simple pipe containing this example looks like this:
                   1124: 
                   1125: @example
                   1126: cat startup.fs |
                   1127: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
                   1128:  type repeat ; foo bye"|
                   1129: head
                   1130: @end example
                   1131: 
                   1132: @cindex stderr and pipes
                   1133: Pipes involving Gforth's @code{stderr} output do not work.
                   1134: 
                   1135: @comment ----------------------------------------------
                   1136: @node Startup speed,  , Gforth in pipes, Gforth Environment
1.48      anton    1137: @section Startup speed
                   1138: @cindex Startup speed
                   1139: @cindex speed, startup
                   1140: 
                   1141: If Gforth is used for CGI scripts or in shell scripts, its startup
                   1142: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
                   1143: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
                   1144: system time.
                   1145: 
                   1146: If startup speed is a problem, you may consider the following ways to
                   1147: improve it; or you may consider ways to reduce the number of startups
1.62      crook    1148: (for example, by using Fast-CGI).
1.48      anton    1149: 
1.112     anton    1150: An easy step that influences Gforth startup speed is the use of the
                   1151: @option{--no-dynamic} option; this decreases image loading speed, but
                   1152: increases compile-time and run-time.
                   1153: 
                   1154: Another step to improve startup speed is to statically link Gforth, by
1.48      anton    1155: building it with @code{XLDFLAGS=-static}.  This requires more memory for
                   1156: the code and will therefore slow down the first invocation, but
                   1157: subsequent invocations avoid the dynamic linking overhead.  Another
                   1158: disadvantage is that Gforth won't profit from library upgrades.  As a
                   1159: result, @code{gforth-static -e bye} takes about 17.1ms user and
                   1160: 8.2ms system time.
                   1161: 
                   1162: The next step to improve startup speed is to use a non-relocatable image
1.65      anton    1163: (@pxref{Non-Relocatable Image Files}).  You can create this image with
1.48      anton    1164: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
                   1165: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
                   1166: and a part of the copy-on-write overhead.  The disadvantage is that the
1.62      crook    1167: non-relocatable image does not work if the OS gives Gforth a different
1.48      anton    1168: address for the dictionary, for whatever reason; so you better provide a
                   1169: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
                   1170: bye} takes about 15.3ms user and 7.5ms system time.
                   1171: 
                   1172: The final step is to disable dictionary hashing in Gforth.  Gforth
                   1173: builds the hash table on startup, which takes much of the startup
                   1174: overhead. You can do this by commenting out the @code{include hash.fs}
                   1175: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
                   1176: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
                   1177: The disadvantages are that functionality like @code{table} and
                   1178: @code{ekey} is missing and that text interpretation (e.g., compiling)
                   1179: now takes much longer. So, you should only use this method if there is
                   1180: no significant text interpretation to perform (the script should be
1.62      crook    1181: compiled into the image, amongst other things).  @code{gforth-static -i
1.48      anton    1182: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
                   1183: 
                   1184: @c ******************************************************************
                   1185: @node Tutorial, Introduction, Gforth Environment, Top
                   1186: @chapter Forth Tutorial
                   1187: @cindex Tutorial
                   1188: @cindex Forth Tutorial
                   1189: 
1.67      anton    1190: @c Topics from nac's Introduction that could be mentioned:
                   1191: @c press <ret> after each line
                   1192: @c Prompt
                   1193: @c numbers vs. words in dictionary on text interpretation
                   1194: @c what happens on redefinition
                   1195: @c parsing words (in particular, defining words)
                   1196: 
1.83      anton    1197: The difference of this chapter from the Introduction
                   1198: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
                   1199: be used while sitting in front of a computer, and covers much more
                   1200: material, but does not explain how the Forth system works.
                   1201: 
1.62      crook    1202: This tutorial can be used with any ANS-compliant Forth; any
                   1203: Gforth-specific features are marked as such and you can skip them if you
                   1204: work with another Forth.  This tutorial does not explain all features of
                   1205: Forth, just enough to get you started and give you some ideas about the
                   1206: facilities available in Forth.  Read the rest of the manual and the
                   1207: standard when you are through this.
1.48      anton    1208: 
                   1209: The intended way to use this tutorial is that you work through it while
                   1210: sitting in front of the console, take a look at the examples and predict
                   1211: what they will do, then try them out; if the outcome is not as expected,
                   1212: find out why (e.g., by trying out variations of the example), so you
                   1213: understand what's going on.  There are also some assignments that you
                   1214: should solve.
                   1215: 
                   1216: This tutorial assumes that you have programmed before and know what,
                   1217: e.g., a loop is.
                   1218: 
                   1219: @c !! explain compat library
                   1220: 
                   1221: @menu
                   1222: * Starting Gforth Tutorial::    
                   1223: * Syntax Tutorial::             
                   1224: * Crash Course Tutorial::       
                   1225: * Stack Tutorial::              
                   1226: * Arithmetics Tutorial::        
                   1227: * Stack Manipulation Tutorial::  
                   1228: * Using files for Forth code Tutorial::  
                   1229: * Comments Tutorial::           
                   1230: * Colon Definitions Tutorial::  
                   1231: * Decompilation Tutorial::      
                   1232: * Stack-Effect Comments Tutorial::  
                   1233: * Types Tutorial::              
                   1234: * Factoring Tutorial::          
                   1235: * Designing the stack effect Tutorial::  
                   1236: * Local Variables Tutorial::    
                   1237: * Conditional execution Tutorial::  
                   1238: * Flags and Comparisons Tutorial::  
                   1239: * General Loops Tutorial::      
                   1240: * Counted loops Tutorial::      
                   1241: * Recursion Tutorial::          
                   1242: * Leaving definitions or loops Tutorial::  
                   1243: * Return Stack Tutorial::       
                   1244: * Memory Tutorial::             
                   1245: * Characters and Strings Tutorial::  
                   1246: * Alignment Tutorial::          
1.190     anton    1247: * Floating Point Tutorial::     
1.87      anton    1248: * Files Tutorial::              
1.48      anton    1249: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                   1250: * Execution Tokens Tutorial::   
                   1251: * Exceptions Tutorial::         
                   1252: * Defining Words Tutorial::     
                   1253: * Arrays and Records Tutorial::  
                   1254: * POSTPONE Tutorial::           
                   1255: * Literal Tutorial::            
                   1256: * Advanced macros Tutorial::    
                   1257: * Compilation Tokens Tutorial::  
                   1258: * Wordlists and Search Order Tutorial::  
                   1259: @end menu
                   1260: 
                   1261: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
                   1262: @section Starting Gforth
1.66      anton    1263: @cindex starting Gforth tutorial
1.48      anton    1264: You can start Gforth by typing its name:
                   1265: 
                   1266: @example
                   1267: gforth
                   1268: @end example
                   1269: 
                   1270: That puts you into interactive mode; you can leave Gforth by typing
                   1271: @code{bye}.  While in Gforth, you can edit the command line and access
                   1272: the command line history with cursor keys, similar to bash.
                   1273: 
                   1274: 
                   1275: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
                   1276: @section Syntax
1.66      anton    1277: @cindex syntax tutorial
1.48      anton    1278: 
1.171     anton    1279: A @dfn{word} is a sequence of arbitrary characters (except white
1.48      anton    1280: space).  Words are separated by white space.  E.g., each of the
                   1281: following lines contains exactly one word:
                   1282: 
                   1283: @example
                   1284: word
                   1285: !@@#$%^&*()
                   1286: 1234567890
                   1287: 5!a
                   1288: @end example
                   1289: 
                   1290: A frequent beginner's error is to leave away necessary white space,
                   1291: resulting in an error like @samp{Undefined word}; so if you see such an
                   1292: error, check if you have put spaces wherever necessary.
                   1293: 
                   1294: @example
                   1295: ." hello, world" \ correct
                   1296: ."hello, world"  \ gives an "Undefined word" error
                   1297: @end example
                   1298: 
1.65      anton    1299: Gforth and most other Forth systems ignore differences in case (they are
1.48      anton    1300: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
                   1301: your system is case-sensitive, you may have to type all the examples
                   1302: given here in upper case.
                   1303: 
                   1304: 
                   1305: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
                   1306: @section Crash Course
                   1307: 
                   1308: Type
                   1309: 
                   1310: @example
                   1311: 0 0 !
                   1312: here execute
                   1313: ' catch >body 20 erase abort
                   1314: ' (quit) >body 20 erase
                   1315: @end example
                   1316: 
                   1317: The last two examples are guaranteed to destroy parts of Gforth (and
                   1318: most other systems), so you better leave Gforth afterwards (if it has
                   1319: not finished by itself).  On some systems you may have to kill gforth
                   1320: from outside (e.g., in Unix with @code{kill}).
                   1321: 
                   1322: Now that you know how to produce crashes (and that there's not much to
                   1323: them), let's learn how to produce meaningful programs.
                   1324: 
                   1325: 
                   1326: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
                   1327: @section Stack
1.66      anton    1328: @cindex stack tutorial
1.48      anton    1329: 
                   1330: The most obvious feature of Forth is the stack.  When you type in a
                   1331: number, it is pushed on the stack.  You can display the content of the
                   1332: stack with @code{.s}.
                   1333: 
                   1334: @example
                   1335: 1 2 .s
                   1336: 3 .s
                   1337: @end example
                   1338: 
                   1339: @code{.s} displays the top-of-stack to the right, i.e., the numbers
                   1340: appear in @code{.s} output as they appeared in the input.
                   1341: 
                   1342: You can print the top of stack element with @code{.}.
                   1343: 
                   1344: @example
                   1345: 1 2 3 . . .
                   1346: @end example
                   1347: 
                   1348: In general, words consume their stack arguments (@code{.s} is an
                   1349: exception).
                   1350: 
1.141     anton    1351: @quotation Assignment
1.48      anton    1352: What does the stack contain after @code{5 6 7 .}?
1.141     anton    1353: @end quotation
1.48      anton    1354: 
                   1355: 
                   1356: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
                   1357: @section Arithmetics
1.66      anton    1358: @cindex arithmetics tutorial
1.48      anton    1359: 
                   1360: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
                   1361: operate on the top two stack items:
                   1362: 
                   1363: @example
1.67      anton    1364: 2 2 .s
                   1365: + .s
                   1366: .
1.48      anton    1367: 2 1 - .
                   1368: 7 3 mod .
                   1369: @end example
                   1370: 
                   1371: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
                   1372: as in the corresponding infix expression (this is generally the case in
                   1373: Forth).
                   1374: 
                   1375: Parentheses are superfluous (and not available), because the order of
                   1376: the words unambiguously determines the order of evaluation and the
                   1377: operands:
                   1378: 
                   1379: @example
                   1380: 3 4 + 5 * .
                   1381: 3 4 5 * + .
                   1382: @end example
                   1383: 
1.141     anton    1384: @quotation Assignment
1.48      anton    1385: What are the infix expressions corresponding to the Forth code above?
                   1386: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
                   1387: known as Postfix or RPN (Reverse Polish Notation).}.
1.141     anton    1388: @end quotation
1.48      anton    1389: 
                   1390: To change the sign, use @code{negate}:
                   1391: 
                   1392: @example
                   1393: 2 negate .
                   1394: @end example
                   1395: 
1.141     anton    1396: @quotation Assignment
1.48      anton    1397: Convert -(-3)*4-5 to Forth.
1.141     anton    1398: @end quotation
1.48      anton    1399: 
                   1400: @code{/mod} performs both @code{/} and @code{mod}.
                   1401: 
                   1402: @example
                   1403: 7 3 /mod . .
                   1404: @end example
                   1405: 
1.66      anton    1406: Reference: @ref{Arithmetic}.
                   1407: 
                   1408: 
1.48      anton    1409: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
                   1410: @section Stack Manipulation
1.66      anton    1411: @cindex stack manipulation tutorial
1.48      anton    1412: 
                   1413: Stack manipulation words rearrange the data on the stack.
                   1414: 
                   1415: @example
                   1416: 1 .s drop .s
                   1417: 1 .s dup .s drop drop .s
                   1418: 1 2 .s over .s drop drop drop
                   1419: 1 2 .s swap .s drop drop
                   1420: 1 2 3 .s rot .s drop drop drop
                   1421: @end example
                   1422: 
                   1423: These are the most important stack manipulation words.  There are also
                   1424: variants that manipulate twice as many stack items:
                   1425: 
                   1426: @example
                   1427: 1 2 3 4 .s 2swap .s 2drop 2drop
                   1428: @end example
                   1429: 
                   1430: Two more stack manipulation words are:
                   1431: 
                   1432: @example
                   1433: 1 2 .s nip .s drop
                   1434: 1 2 .s tuck .s 2drop drop
                   1435: @end example
                   1436: 
1.141     anton    1437: @quotation Assignment
1.48      anton    1438: Replace @code{nip} and @code{tuck} with combinations of other stack
                   1439: manipulation words.
                   1440: 
                   1441: @example
                   1442: Given:          How do you get:
                   1443: 1 2 3           3 2 1           
                   1444: 1 2 3           1 2 3 2                 
                   1445: 1 2 3           1 2 3 3                 
                   1446: 1 2 3           1 3 3           
                   1447: 1 2 3           2 1 3           
                   1448: 1 2 3 4         4 3 2 1         
                   1449: 1 2 3           1 2 3 1 2 3             
                   1450: 1 2 3 4         1 2 3 4 1 2             
                   1451: 1 2 3
                   1452: 1 2 3           1 2 3 4                 
                   1453: 1 2 3           1 3             
                   1454: @end example
1.141     anton    1455: @end quotation
1.48      anton    1456: 
                   1457: @example
                   1458: 5 dup * .
                   1459: @end example
                   1460: 
1.141     anton    1461: @quotation Assignment
1.48      anton    1462: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
                   1463: Write a piece of Forth code that expects two numbers on the stack
                   1464: (@var{a} and @var{b}, with @var{b} on top) and computes
                   1465: @code{(a-b)(a+1)}.
1.141     anton    1466: @end quotation
1.48      anton    1467: 
1.66      anton    1468: Reference: @ref{Stack Manipulation}.
                   1469: 
                   1470: 
1.48      anton    1471: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
                   1472: @section Using files for Forth code
1.66      anton    1473: @cindex loading Forth code, tutorial
                   1474: @cindex files containing Forth code, tutorial
1.48      anton    1475: 
                   1476: While working at the Forth command line is convenient for one-line
                   1477: examples and short one-off code, you probably want to store your source
                   1478: code in files for convenient editing and persistence.  You can use your
                   1479: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102     anton    1480: Gforth}) to create @var{file.fs} and use
1.48      anton    1481: 
                   1482: @example
1.102     anton    1483: s" @var{file.fs}" included
1.48      anton    1484: @end example
                   1485: 
                   1486: to load it into your Forth system.  The file name extension I use for
                   1487: Forth files is @samp{.fs}.
                   1488: 
                   1489: You can easily start Gforth with some files loaded like this:
                   1490: 
                   1491: @example
1.102     anton    1492: gforth @var{file1.fs} @var{file2.fs}
1.48      anton    1493: @end example
                   1494: 
                   1495: If an error occurs during loading these files, Gforth terminates,
                   1496: whereas an error during @code{INCLUDED} within Gforth usually gives you
                   1497: a Gforth command line.  Starting the Forth system every time gives you a
                   1498: clean start every time, without interference from the results of earlier
                   1499: tries.
                   1500: 
                   1501: I often put all the tests in a file, then load the code and run the
                   1502: tests with
                   1503: 
                   1504: @example
1.102     anton    1505: gforth @var{code.fs} @var{tests.fs} -e bye
1.48      anton    1506: @end example
                   1507: 
                   1508: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
                   1509: @code{-e bye} ensures that Gforth terminates afterwards so that I can
                   1510: restart this command without ado.
                   1511: 
                   1512: The advantage of this approach is that the tests can be repeated easily
                   1513: every time the program ist changed, making it easy to catch bugs
                   1514: introduced by the change.
                   1515: 
1.66      anton    1516: Reference: @ref{Forth source files}.
                   1517: 
1.48      anton    1518: 
                   1519: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
                   1520: @section Comments
1.66      anton    1521: @cindex comments tutorial
1.48      anton    1522: 
                   1523: @example
                   1524: \ That's a comment; it ends at the end of the line
                   1525: ( Another comment; it ends here: )  .s
                   1526: @end example
                   1527: 
                   1528: @code{\} and @code{(} are ordinary Forth words and therefore have to be
                   1529: separated with white space from the following text.
                   1530: 
                   1531: @example
                   1532: \This gives an "Undefined word" error
                   1533: @end example
                   1534: 
                   1535: The first @code{)} ends a comment started with @code{(}, so you cannot
                   1536: nest @code{(}-comments; and you cannot comment out text containing a
                   1537: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
                   1538: avoid @code{)} in word names.}.
                   1539: 
                   1540: I use @code{\}-comments for descriptive text and for commenting out code
                   1541: of one or more line; I use @code{(}-comments for describing the stack
                   1542: effect, the stack contents, or for commenting out sub-line pieces of
                   1543: code.
                   1544: 
                   1545: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
                   1546: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
                   1547: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
                   1548: with @kbd{M-q}.
                   1549: 
1.66      anton    1550: Reference: @ref{Comments}.
                   1551: 
1.48      anton    1552: 
                   1553: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
                   1554: @section Colon Definitions
1.66      anton    1555: @cindex colon definitions, tutorial
                   1556: @cindex definitions, tutorial
                   1557: @cindex procedures, tutorial
                   1558: @cindex functions, tutorial
1.48      anton    1559: 
                   1560: are similar to procedures and functions in other programming languages.
                   1561: 
                   1562: @example
                   1563: : squared ( n -- n^2 )
                   1564:    dup * ;
                   1565: 5 squared .
                   1566: 7 squared .
                   1567: @end example
                   1568: 
                   1569: @code{:} starts the colon definition; its name is @code{squared}.  The
                   1570: following comment describes its stack effect.  The words @code{dup *}
                   1571: are not executed, but compiled into the definition.  @code{;} ends the
                   1572: colon definition.
                   1573: 
                   1574: The newly-defined word can be used like any other word, including using
                   1575: it in other definitions:
                   1576: 
                   1577: @example
                   1578: : cubed ( n -- n^3 )
                   1579:    dup squared * ;
                   1580: -5 cubed .
                   1581: : fourth-power ( n -- n^4 )
                   1582:    squared squared ;
                   1583: 3 fourth-power .
                   1584: @end example
                   1585: 
1.141     anton    1586: @quotation Assignment
1.48      anton    1587: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
                   1588: @code{/mod} in terms of other Forth words, and check if they work (hint:
                   1589: test your tests on the originals first).  Don't let the
                   1590: @samp{redefined}-Messages spook you, they are just warnings.
1.141     anton    1591: @end quotation
1.48      anton    1592: 
1.66      anton    1593: Reference: @ref{Colon Definitions}.
                   1594: 
1.48      anton    1595: 
                   1596: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
                   1597: @section Decompilation
1.66      anton    1598: @cindex decompilation tutorial
                   1599: @cindex see tutorial
1.48      anton    1600: 
                   1601: You can decompile colon definitions with @code{see}:
                   1602: 
                   1603: @example
                   1604: see squared
                   1605: see cubed
                   1606: @end example
                   1607: 
                   1608: In Gforth @code{see} shows you a reconstruction of the source code from
                   1609: the executable code.  Informations that were present in the source, but
                   1610: not in the executable code, are lost (e.g., comments).
                   1611: 
1.65      anton    1612: You can also decompile the predefined words:
                   1613: 
                   1614: @example
                   1615: see .
                   1616: see +
                   1617: @end example
                   1618: 
                   1619: 
1.48      anton    1620: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
                   1621: @section Stack-Effect Comments
1.66      anton    1622: @cindex stack-effect comments, tutorial
                   1623: @cindex --, tutorial
1.48      anton    1624: By convention the comment after the name of a definition describes the
1.171     anton    1625: stack effect: The part in front of the @samp{--} describes the state of
1.48      anton    1626: the stack before the execution of the definition, i.e., the parameters
                   1627: that are passed into the colon definition; the part behind the @samp{--}
                   1628: is the state of the stack after the execution of the definition, i.e.,
                   1629: the results of the definition.  The stack comment only shows the top
                   1630: stack items that the definition accesses and/or changes.
                   1631: 
                   1632: You should put a correct stack effect on every definition, even if it is
                   1633: just @code{( -- )}.  You should also add some descriptive comment to
                   1634: more complicated words (I usually do this in the lines following
                   1635: @code{:}).  If you don't do this, your code becomes unreadable (because
1.117     anton    1636: you have to work through every definition before you can understand
1.48      anton    1637: any).
                   1638: 
1.141     anton    1639: @quotation Assignment
1.48      anton    1640: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
                   1641: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
                   1642: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
1.65      anton    1643: are done, you can compare your stack effects to those in this manual
1.48      anton    1644: (@pxref{Word Index}).
1.141     anton    1645: @end quotation
1.48      anton    1646: 
                   1647: Sometimes programmers put comments at various places in colon
                   1648: definitions that describe the contents of the stack at that place (stack
                   1649: comments); i.e., they are like the first part of a stack-effect
                   1650: comment. E.g.,
                   1651: 
                   1652: @example
                   1653: : cubed ( n -- n^3 )
                   1654:    dup squared  ( n n^2 ) * ;
                   1655: @end example
                   1656: 
                   1657: In this case the stack comment is pretty superfluous, because the word
                   1658: is simple enough.  If you think it would be a good idea to add such a
                   1659: comment to increase readability, you should also consider factoring the
                   1660: word into several simpler words (@pxref{Factoring Tutorial,,
1.60      anton    1661: Factoring}), which typically eliminates the need for the stack comment;
1.48      anton    1662: however, if you decide not to refactor it, then having such a comment is
                   1663: better than not having it.
                   1664: 
                   1665: The names of the stack items in stack-effect and stack comments in the
                   1666: standard, in this manual, and in many programs specify the type through
                   1667: a type prefix, similar to Fortran and Hungarian notation.  The most
                   1668: frequent prefixes are:
                   1669: 
                   1670: @table @code
                   1671: @item n
                   1672: signed integer
                   1673: @item u
                   1674: unsigned integer
                   1675: @item c
                   1676: character
                   1677: @item f
                   1678: Boolean flags, i.e. @code{false} or @code{true}.
                   1679: @item a-addr,a-
                   1680: Cell-aligned address
                   1681: @item c-addr,c-
                   1682: Char-aligned address (note that a Char may have two bytes in Windows NT)
                   1683: @item xt
                   1684: Execution token, same size as Cell
                   1685: @item w,x
                   1686: Cell, can contain an integer or an address.  It usually takes 32, 64 or
                   1687: 16 bits (depending on your platform and Forth system). A cell is more
                   1688: commonly known as machine word, but the term @emph{word} already means
                   1689: something different in Forth.
                   1690: @item d
                   1691: signed double-cell integer
                   1692: @item ud
                   1693: unsigned double-cell integer
                   1694: @item r
                   1695: Float (on the FP stack)
                   1696: @end table
                   1697: 
                   1698: You can find a more complete list in @ref{Notation}.
                   1699: 
1.141     anton    1700: @quotation Assignment
1.48      anton    1701: Write stack-effect comments for all definitions you have written up to
                   1702: now.
1.141     anton    1703: @end quotation
1.48      anton    1704: 
                   1705: 
                   1706: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
                   1707: @section Types
1.66      anton    1708: @cindex types tutorial
1.48      anton    1709: 
                   1710: In Forth the names of the operations are not overloaded; so similar
                   1711: operations on different types need different names; e.g., @code{+} adds
                   1712: integers, and you have to use @code{f+} to add floating-point numbers.
                   1713: The following prefixes are often used for related operations on
                   1714: different types:
                   1715: 
                   1716: @table @code
                   1717: @item (none)
                   1718: signed integer
                   1719: @item u
                   1720: unsigned integer
                   1721: @item c
                   1722: character
                   1723: @item d
                   1724: signed double-cell integer
                   1725: @item ud, du
                   1726: unsigned double-cell integer
                   1727: @item 2
                   1728: two cells (not-necessarily double-cell numbers)
                   1729: @item m, um
                   1730: mixed single-cell and double-cell operations
                   1731: @item f
                   1732: floating-point (note that in stack comments @samp{f} represents flags,
1.66      anton    1733: and @samp{r} represents FP numbers).
1.48      anton    1734: @end table
                   1735: 
                   1736: If there are no differences between the signed and the unsigned variant
                   1737: (e.g., for @code{+}), there is only the prefix-less variant.
                   1738: 
                   1739: Forth does not perform type checking, neither at compile time, nor at
                   1740: run time.  If you use the wrong oeration, the data are interpreted
                   1741: incorrectly:
                   1742: 
                   1743: @example
                   1744: -1 u.
                   1745: @end example
                   1746: 
                   1747: If you have only experience with type-checked languages until now, and
                   1748: have heard how important type-checking is, don't panic!  In my
                   1749: experience (and that of other Forthers), type errors in Forth code are
                   1750: usually easy to find (once you get used to it), the increased vigilance
                   1751: of the programmer tends to catch some harder errors in addition to most
                   1752: type errors, and you never have to work around the type system, so in
                   1753: most situations the lack of type-checking seems to be a win (projects to
                   1754: add type checking to Forth have not caught on).
                   1755: 
                   1756: 
                   1757: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
                   1758: @section Factoring
1.66      anton    1759: @cindex factoring tutorial
1.48      anton    1760: 
                   1761: If you try to write longer definitions, you will soon find it hard to
                   1762: keep track of the stack contents.  Therefore, good Forth programmers
                   1763: tend to write only short definitions (e.g., three lines).  The art of
                   1764: finding meaningful short definitions is known as factoring (as in
                   1765: factoring polynomials).
                   1766: 
                   1767: Well-factored programs offer additional advantages: smaller, more
                   1768: general words, are easier to test and debug and can be reused more and
                   1769: better than larger, specialized words.
                   1770: 
                   1771: So, if you run into difficulties with stack management, when writing
                   1772: code, try to define meaningful factors for the word, and define the word
                   1773: in terms of those.  Even if a factor contains only two words, it is
                   1774: often helpful.
                   1775: 
1.65      anton    1776: Good factoring is not easy, and it takes some practice to get the knack
                   1777: for it; but even experienced Forth programmers often don't find the
                   1778: right solution right away, but only when rewriting the program.  So, if
                   1779: you don't come up with a good solution immediately, keep trying, don't
                   1780: despair.
1.48      anton    1781: 
                   1782: @c example !!
                   1783: 
                   1784: 
                   1785: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
                   1786: @section Designing the stack effect
1.66      anton    1787: @cindex Stack effect design, tutorial
                   1788: @cindex design of stack effects, tutorial
1.48      anton    1789: 
                   1790: In other languages you can use an arbitrary order of parameters for a
1.65      anton    1791: function; and since there is only one result, you don't have to deal with
1.48      anton    1792: the order of results, either.
                   1793: 
1.117     anton    1794: In Forth (and other stack-based languages, e.g., PostScript) the
1.48      anton    1795: parameter and result order of a definition is important and should be
                   1796: designed well.  The general guideline is to design the stack effect such
                   1797: that the word is simple to use in most cases, even if that complicates
                   1798: the implementation of the word.  Some concrete rules are:
                   1799: 
                   1800: @itemize @bullet
                   1801: 
                   1802: @item
                   1803: Words consume all of their parameters (e.g., @code{.}).
                   1804: 
                   1805: @item
                   1806: If there is a convention on the order of parameters (e.g., from
                   1807: mathematics or another programming language), stick with it (e.g.,
                   1808: @code{-}).
                   1809: 
                   1810: @item
                   1811: If one parameter usually requires only a short computation (e.g., it is
                   1812: a constant), pass it on the top of the stack.  Conversely, parameters
                   1813: that usually require a long sequence of code to compute should be passed
                   1814: as the bottom (i.e., first) parameter.  This makes the code easier to
1.171     anton    1815: read, because the reader does not need to keep track of the bottom item
1.48      anton    1816: through a long sequence of code (or, alternatively, through stack
1.49      anton    1817: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48      anton    1818: address on top of the stack because it is usually simpler to compute
                   1819: than the stored value (often the address is just a variable).
                   1820: 
                   1821: @item
                   1822: Similarly, results that are usually consumed quickly should be returned
                   1823: on the top of stack, whereas a result that is often used in long
                   1824: computations should be passed as bottom result.  E.g., the file words
                   1825: like @code{open-file} return the error code on the top of stack, because
                   1826: it is usually consumed quickly by @code{throw}; moreover, the error code
                   1827: has to be checked before doing anything with the other results.
                   1828: 
                   1829: @end itemize
                   1830: 
                   1831: These rules are just general guidelines, don't lose sight of the overall
                   1832: goal to make the words easy to use.  E.g., if the convention rule
                   1833: conflicts with the computation-length rule, you might decide in favour
                   1834: of the convention if the word will be used rarely, and in favour of the
                   1835: computation-length rule if the word will be used frequently (because
                   1836: with frequent use the cost of breaking the computation-length rule would
                   1837: be quite high, and frequent use makes it easier to remember an
                   1838: unconventional order).
                   1839: 
                   1840: @c example !! structure package
                   1841: 
1.65      anton    1842: 
1.48      anton    1843: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
                   1844: @section Local Variables
1.66      anton    1845: @cindex local variables, tutorial
1.48      anton    1846: 
                   1847: You can define local variables (@emph{locals}) in a colon definition:
                   1848: 
                   1849: @example
                   1850: : swap @{ a b -- b a @}
                   1851:   b a ;
                   1852: 1 2 swap .s 2drop
                   1853: @end example
                   1854: 
                   1855: (If your Forth system does not support this syntax, include
1.187     anton    1856: @file{compat/anslocal.fs} first).
1.48      anton    1857: 
                   1858: In this example @code{@{ a b -- b a @}} is the locals definition; it
                   1859: takes two cells from the stack, puts the top of stack in @code{b} and
                   1860: the next stack element in @code{a}.  @code{--} starts a comment ending
                   1861: with @code{@}}.  After the locals definition, using the name of the
                   1862: local will push its value on the stack.  You can leave the comment
                   1863: part (@code{-- b a}) away:
                   1864: 
                   1865: @example
                   1866: : swap ( x1 x2 -- x2 x1 )
                   1867:   @{ a b @} b a ;
                   1868: @end example
                   1869: 
                   1870: In Gforth you can have several locals definitions, anywhere in a colon
                   1871: definition; in contrast, in a standard program you can have only one
                   1872: locals definition per colon definition, and that locals definition must
1.163     anton    1873: be outside any control structure.
1.48      anton    1874: 
                   1875: With locals you can write slightly longer definitions without running
                   1876: into stack trouble.  However, I recommend trying to write colon
                   1877: definitions without locals for exercise purposes to help you gain the
                   1878: essential factoring skills.
                   1879: 
1.141     anton    1880: @quotation Assignment
1.48      anton    1881: Rewrite your definitions until now with locals
1.141     anton    1882: @end quotation
1.48      anton    1883: 
1.66      anton    1884: Reference: @ref{Locals}.
                   1885: 
1.48      anton    1886: 
                   1887: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
                   1888: @section Conditional execution
1.66      anton    1889: @cindex conditionals, tutorial
                   1890: @cindex if, tutorial
1.48      anton    1891: 
                   1892: In Forth you can use control structures only inside colon definitions.
                   1893: An @code{if}-structure looks like this:
                   1894: 
                   1895: @example
                   1896: : abs ( n1 -- +n2 )
                   1897:     dup 0 < if
                   1898:         negate
                   1899:     endif ;
                   1900: 5 abs .
                   1901: -5 abs .
                   1902: @end example
                   1903: 
                   1904: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
                   1905: the following code is performed, otherwise execution continues after the
1.51      pazsan   1906: @code{endif} (or @code{else}).  @code{<} compares the top two stack
1.171     anton    1907: elements and produces a flag:
1.48      anton    1908: 
                   1909: @example
                   1910: 1 2 < .
                   1911: 2 1 < .
                   1912: 1 1 < .
                   1913: @end example
                   1914: 
                   1915: Actually the standard name for @code{endif} is @code{then}.  This
                   1916: tutorial presents the examples using @code{endif}, because this is often
                   1917: less confusing for people familiar with other programming languages
                   1918: where @code{then} has a different meaning.  If your system does not have
                   1919: @code{endif}, define it with
                   1920: 
                   1921: @example
                   1922: : endif postpone then ; immediate
                   1923: @end example
                   1924: 
                   1925: You can optionally use an @code{else}-part:
                   1926: 
                   1927: @example
                   1928: : min ( n1 n2 -- n )
                   1929:   2dup < if
                   1930:     drop
                   1931:   else
                   1932:     nip
                   1933:   endif ;
                   1934: 2 3 min .
                   1935: 3 2 min .
                   1936: @end example
                   1937: 
1.141     anton    1938: @quotation Assignment
1.48      anton    1939: Write @code{min} without @code{else}-part (hint: what's the definition
                   1940: of @code{nip}?).
1.141     anton    1941: @end quotation
1.48      anton    1942: 
1.66      anton    1943: Reference: @ref{Selection}.
                   1944: 
1.48      anton    1945: 
                   1946: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
                   1947: @section Flags and Comparisons
1.66      anton    1948: @cindex flags tutorial
                   1949: @cindex comparison tutorial
1.48      anton    1950: 
                   1951: In a false-flag all bits are clear (0 when interpreted as integer).  In
                   1952: a canonical true-flag all bits are set (-1 as a twos-complement signed
                   1953: integer); in many contexts (e.g., @code{if}) any non-zero value is
                   1954: treated as true flag.
                   1955: 
                   1956: @example
                   1957: false .
                   1958: true .
                   1959: true hex u. decimal
                   1960: @end example
                   1961: 
                   1962: Comparison words produce canonical flags:
                   1963: 
                   1964: @example
                   1965: 1 1 = .
                   1966: 1 0= .
                   1967: 0 1 < .
                   1968: 0 0 < .
                   1969: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
                   1970: -1 1 < .
                   1971: @end example
                   1972: 
1.66      anton    1973: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
                   1974: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
                   1975: these combinations are standard (for details see the standard,
                   1976: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48      anton    1977: 
1.171     anton    1978: You can use @code{and or xor invert} as operations on canonical flags.
                   1979: Actually they are bitwise operations:
1.48      anton    1980: 
                   1981: @example
                   1982: 1 2 and .
                   1983: 1 2 or .
                   1984: 1 3 xor .
                   1985: 1 invert .
                   1986: @end example
                   1987: 
                   1988: You can convert a zero/non-zero flag into a canonical flag with
                   1989: @code{0<>} (and complement it on the way with @code{0=}).
                   1990: 
                   1991: @example
                   1992: 1 0= .
                   1993: 1 0<> .
                   1994: @end example
                   1995: 
1.65      anton    1996: You can use the all-bits-set feature of canonical flags and the bitwise
1.48      anton    1997: operation of the Boolean operations to avoid @code{if}s:
                   1998: 
                   1999: @example
                   2000: : foo ( n1 -- n2 )
                   2001:   0= if
                   2002:     14
                   2003:   else
                   2004:     0
                   2005:   endif ;
                   2006: 0 foo .
                   2007: 1 foo .
                   2008: 
                   2009: : foo ( n1 -- n2 )
                   2010:   0= 14 and ;
                   2011: 0 foo .
                   2012: 1 foo .
                   2013: @end example
                   2014: 
1.141     anton    2015: @quotation Assignment
1.48      anton    2016: Write @code{min} without @code{if}.
1.141     anton    2017: @end quotation
1.48      anton    2018: 
1.66      anton    2019: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
                   2020: @ref{Bitwise operations}.
                   2021: 
1.48      anton    2022: 
                   2023: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
                   2024: @section General Loops
1.66      anton    2025: @cindex loops, indefinite, tutorial
1.48      anton    2026: 
                   2027: The endless loop is the most simple one:
                   2028: 
                   2029: @example
                   2030: : endless ( -- )
                   2031:   0 begin
                   2032:     dup . 1+
                   2033:   again ;
                   2034: endless
                   2035: @end example
                   2036: 
                   2037: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
                   2038: does nothing at run-time, @code{again} jumps back to @code{begin}.
                   2039: 
                   2040: A loop with one exit at any place looks like this:
                   2041: 
                   2042: @example
                   2043: : log2 ( +n1 -- n2 )
                   2044: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2045:   assert( dup 0> )
                   2046:   2/ 0 begin
                   2047:     over 0> while
                   2048:       1+ swap 2/ swap
                   2049:   repeat
                   2050:   nip ;
                   2051: 7 log2 .
                   2052: 8 log2 .
                   2053: @end example
                   2054: 
                   2055: At run-time @code{while} consumes a flag; if it is 0, execution
1.51      pazsan   2056: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48      anton    2057: continues behind the @code{while}.  @code{Repeat} jumps back to
                   2058: @code{begin}, just like @code{again}.
                   2059: 
                   2060: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90      anton    2061: However, @code{2/} is not one of them; it shifts its argument right by
1.48      anton    2062: one bit (arithmetic shift right):
                   2063: 
                   2064: @example
                   2065: -5 2 / .
                   2066: -5 2/ .
                   2067: @end example
                   2068: 
                   2069: @code{assert(} is no standard word, but you can get it on systems other
                   2070: then Gforth by including @file{compat/assert.fs}.  You can see what it
                   2071: does by trying
                   2072: 
                   2073: @example
                   2074: 0 log2 .
                   2075: @end example
                   2076: 
                   2077: Here's a loop with an exit at the end:
                   2078: 
                   2079: @example
                   2080: : log2 ( +n1 -- n2 )
                   2081: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2082:   assert( dup 0 > )
                   2083:   -1 begin
                   2084:     1+ swap 2/ swap
                   2085:     over 0 <=
                   2086:   until
                   2087:   nip ;
                   2088: @end example
                   2089: 
                   2090: @code{Until} consumes a flag; if it is non-zero, execution continues at
                   2091: the @code{begin}, otherwise after the @code{until}.
                   2092: 
1.141     anton    2093: @quotation Assignment
1.48      anton    2094: Write a definition for computing the greatest common divisor.
1.141     anton    2095: @end quotation
1.48      anton    2096: 
1.66      anton    2097: Reference: @ref{Simple Loops}.
                   2098: 
1.48      anton    2099: 
                   2100: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
                   2101: @section Counted loops
1.66      anton    2102: @cindex loops, counted, tutorial
1.48      anton    2103: 
                   2104: @example
                   2105: : ^ ( n1 u -- n )
1.171     anton    2106: \ n = the uth power of n1
1.48      anton    2107:   1 swap 0 u+do
                   2108:     over *
                   2109:   loop
                   2110:   nip ;
                   2111: 3 2 ^ .
                   2112: 4 3 ^ .
                   2113: @end example
                   2114: 
                   2115: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
                   2116: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
                   2117: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
                   2118: times (or not at all, if @code{u3-u4<0}).
                   2119: 
                   2120: You can see the stack effect design rules at work in the stack effect of
                   2121: the loop start words: Since the start value of the loop is more
                   2122: frequently constant than the end value, the start value is passed on
                   2123: the top-of-stack.
                   2124: 
                   2125: You can access the counter of a counted loop with @code{i}:
                   2126: 
                   2127: @example
                   2128: : fac ( u -- u! )
                   2129:   1 swap 1+ 1 u+do
                   2130:     i *
                   2131:   loop ;
                   2132: 5 fac .
                   2133: 7 fac .
                   2134: @end example
                   2135: 
                   2136: There is also @code{+do}, which expects signed numbers (important for
                   2137: deciding whether to enter the loop).
                   2138: 
1.141     anton    2139: @quotation Assignment
1.48      anton    2140: Write a definition for computing the nth Fibonacci number.
1.141     anton    2141: @end quotation
1.48      anton    2142: 
1.65      anton    2143: You can also use increments other than 1:
                   2144: 
                   2145: @example
                   2146: : up2 ( n1 n2 -- )
                   2147:   +do
                   2148:     i .
                   2149:   2 +loop ;
                   2150: 10 0 up2
                   2151: 
                   2152: : down2 ( n1 n2 -- )
                   2153:   -do
                   2154:     i .
                   2155:   2 -loop ;
                   2156: 0 10 down2
                   2157: @end example
1.48      anton    2158: 
1.66      anton    2159: Reference: @ref{Counted Loops}.
                   2160: 
1.48      anton    2161: 
                   2162: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
                   2163: @section Recursion
1.66      anton    2164: @cindex recursion tutorial
1.48      anton    2165: 
                   2166: Usually the name of a definition is not visible in the definition; but
                   2167: earlier definitions are usually visible:
                   2168: 
                   2169: @example
1.166     anton    2170: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
1.48      anton    2171: : / ( n1 n2 -- n )
                   2172:   dup 0= if
                   2173:     -10 throw \ report division by zero
                   2174:   endif
                   2175:   /           \ old version
                   2176: ;
                   2177: 1 0 /
                   2178: @end example
                   2179: 
                   2180: For recursive definitions you can use @code{recursive} (non-standard) or
                   2181: @code{recurse}:
                   2182: 
                   2183: @example
                   2184: : fac1 ( n -- n! ) recursive
                   2185:  dup 0> if
                   2186:    dup 1- fac1 *
                   2187:  else
                   2188:    drop 1
                   2189:  endif ;
                   2190: 7 fac1 .
                   2191: 
                   2192: : fac2 ( n -- n! )
                   2193:  dup 0> if
                   2194:    dup 1- recurse *
                   2195:  else
                   2196:    drop 1
                   2197:  endif ;
                   2198: 8 fac2 .
                   2199: @end example
                   2200: 
1.141     anton    2201: @quotation Assignment
1.48      anton    2202: Write a recursive definition for computing the nth Fibonacci number.
1.141     anton    2203: @end quotation
1.48      anton    2204: 
1.66      anton    2205: Reference (including indirect recursion): @xref{Calls and returns}.
                   2206: 
1.48      anton    2207: 
                   2208: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
                   2209: @section Leaving definitions or loops
1.66      anton    2210: @cindex leaving definitions, tutorial
                   2211: @cindex leaving loops, tutorial
1.48      anton    2212: 
                   2213: @code{EXIT} exits the current definition right away.  For every counted
                   2214: loop that is left in this way, an @code{UNLOOP} has to be performed
                   2215: before the @code{EXIT}:
                   2216: 
                   2217: @c !! real examples
                   2218: @example
                   2219: : ...
                   2220:  ... u+do
                   2221:    ... if
                   2222:      ... unloop exit
                   2223:    endif
                   2224:    ...
                   2225:  loop
                   2226:  ... ;
                   2227: @end example
                   2228: 
                   2229: @code{LEAVE} leaves the innermost counted loop right away:
                   2230: 
                   2231: @example
                   2232: : ...
                   2233:  ... u+do
                   2234:    ... if
                   2235:      ... leave
                   2236:    endif
                   2237:    ...
                   2238:  loop
                   2239:  ... ;
                   2240: @end example
                   2241: 
1.65      anton    2242: @c !! example
1.48      anton    2243: 
1.66      anton    2244: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
                   2245: 
                   2246: 
1.48      anton    2247: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
                   2248: @section Return Stack
1.66      anton    2249: @cindex return stack tutorial
1.48      anton    2250: 
                   2251: In addition to the data stack Forth also has a second stack, the return
                   2252: stack; most Forth systems store the return addresses of procedure calls
                   2253: there (thus its name).  Programmers can also use this stack:
                   2254: 
                   2255: @example
                   2256: : foo ( n1 n2 -- )
                   2257:  .s
                   2258:  >r .s
1.50      anton    2259:  r@@ .
1.48      anton    2260:  >r .s
1.50      anton    2261:  r@@ .
1.48      anton    2262:  r> .
1.50      anton    2263:  r@@ .
1.48      anton    2264:  r> . ;
                   2265: 1 2 foo
                   2266: @end example
                   2267: 
                   2268: @code{>r} takes an element from the data stack and pushes it onto the
                   2269: return stack; conversely, @code{r>} moves an elementm from the return to
                   2270: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148     anton    2271: on the data stack.
1.48      anton    2272: 
                   2273: Forth programmers usually use the return stack for storing data
                   2274: temporarily, if using the data stack alone would be too complex, and
                   2275: factoring and locals are not an option:
                   2276: 
                   2277: @example
                   2278: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
                   2279:  rot >r rot r> ;
                   2280: @end example
                   2281: 
                   2282: The return address of the definition and the loop control parameters of
                   2283: counted loops usually reside on the return stack, so you have to take
                   2284: all items, that you have pushed on the return stack in a colon
                   2285: definition or counted loop, from the return stack before the definition
                   2286: or loop ends.  You cannot access items that you pushed on the return
                   2287: stack outside some definition or loop within the definition of loop.
                   2288: 
                   2289: If you miscount the return stack items, this usually ends in a crash:
                   2290: 
                   2291: @example
                   2292: : crash ( n -- )
                   2293:   >r ;
                   2294: 5 crash
                   2295: @end example
                   2296: 
                   2297: You cannot mix using locals and using the return stack (according to the
                   2298: standard; Gforth has no problem).  However, they solve the same
                   2299: problems, so this shouldn't be an issue.
                   2300: 
1.141     anton    2301: @quotation Assignment
1.48      anton    2302: Can you rewrite any of the definitions you wrote until now in a better
                   2303: way using the return stack?
1.141     anton    2304: @end quotation
1.48      anton    2305: 
1.66      anton    2306: Reference: @ref{Return stack}.
                   2307: 
1.48      anton    2308: 
                   2309: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
                   2310: @section Memory
1.66      anton    2311: @cindex memory access/allocation tutorial
1.48      anton    2312: 
                   2313: You can create a global variable @code{v} with
                   2314: 
                   2315: @example
                   2316: variable v ( -- addr )
                   2317: @end example
                   2318: 
                   2319: @code{v} pushes the address of a cell in memory on the stack.  This cell
                   2320: was reserved by @code{variable}.  You can use @code{!} (store) to store
                   2321: values into this cell and @code{@@} (fetch) to load the value from the
                   2322: stack into memory:
                   2323: 
                   2324: @example
                   2325: v .
                   2326: 5 v ! .s
1.50      anton    2327: v @@ .
1.48      anton    2328: @end example
                   2329: 
1.65      anton    2330: You can see a raw dump of memory with @code{dump}:
                   2331: 
                   2332: @example
                   2333: v 1 cells .s dump
                   2334: @end example
                   2335: 
                   2336: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
                   2337: generally, address units (aus)) that @code{n1 cells} occupy.  You can
                   2338: also reserve more memory:
1.48      anton    2339: 
                   2340: @example
                   2341: create v2 20 cells allot
1.65      anton    2342: v2 20 cells dump
1.48      anton    2343: @end example
                   2344: 
1.65      anton    2345: creates a word @code{v2} and reserves 20 uninitialized cells; the
                   2346: address pushed by @code{v2} points to the start of these 20 cells.  You
                   2347: can use address arithmetic to access these cells:
1.48      anton    2348: 
                   2349: @example
                   2350: 3 v2 5 cells + !
1.65      anton    2351: v2 20 cells dump
1.48      anton    2352: @end example
                   2353: 
                   2354: You can reserve and initialize memory with @code{,}:
                   2355: 
                   2356: @example
                   2357: create v3
                   2358:   5 , 4 , 3 , 2 , 1 ,
1.50      anton    2359: v3 @@ .
                   2360: v3 cell+ @@ .
                   2361: v3 2 cells + @@ .
1.65      anton    2362: v3 5 cells dump
1.48      anton    2363: @end example
                   2364: 
1.141     anton    2365: @quotation Assignment
1.48      anton    2366: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
                   2367: @code{u} cells, with the first of these cells at @code{addr}, the next
                   2368: one at @code{addr cell+} etc.
1.141     anton    2369: @end quotation
1.48      anton    2370: 
                   2371: You can also reserve memory without creating a new word:
                   2372: 
                   2373: @example
1.60      anton    2374: here 10 cells allot .
                   2375: here .
1.48      anton    2376: @end example
                   2377: 
                   2378: @code{Here} pushes the start address of the memory area.  You should
                   2379: store it somewhere, or you will have a hard time finding the memory area
                   2380: again.
                   2381: 
                   2382: @code{Allot} manages dictionary memory.  The dictionary memory contains
                   2383: the system's data structures for words etc. on Gforth and most other
                   2384: Forth systems.  It is managed like a stack: You can free the memory that
                   2385: you have just @code{allot}ed with
                   2386: 
                   2387: @example
                   2388: -10 cells allot
1.60      anton    2389: here .
1.48      anton    2390: @end example
                   2391: 
                   2392: Note that you cannot do this if you have created a new word in the
                   2393: meantime (because then your @code{allot}ed memory is no longer on the
                   2394: top of the dictionary ``stack'').
                   2395: 
                   2396: Alternatively, you can use @code{allocate} and @code{free} which allow
                   2397: freeing memory in any order:
                   2398: 
                   2399: @example
                   2400: 10 cells allocate throw .s
                   2401: 20 cells allocate throw .s
                   2402: swap
                   2403: free throw
                   2404: free throw
                   2405: @end example
                   2406: 
                   2407: The @code{throw}s deal with errors (e.g., out of memory).
                   2408: 
1.65      anton    2409: And there is also a
                   2410: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   2411: garbage collector}, which eliminates the need to @code{free} memory
                   2412: explicitly.
1.48      anton    2413: 
1.66      anton    2414: Reference: @ref{Memory}.
                   2415: 
1.48      anton    2416: 
                   2417: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
                   2418: @section Characters and Strings
1.66      anton    2419: @cindex strings tutorial
                   2420: @cindex characters tutorial
1.48      anton    2421: 
                   2422: On the stack characters take up a cell, like numbers.  In memory they
                   2423: have their own size (one 8-bit byte on most systems), and therefore
                   2424: require their own words for memory access:
                   2425: 
                   2426: @example
                   2427: create v4 
                   2428:   104 c, 97 c, 108 c, 108 c, 111 c,
1.50      anton    2429: v4 4 chars + c@@ .
1.65      anton    2430: v4 5 chars dump
1.48      anton    2431: @end example
                   2432: 
                   2433: The preferred representation of strings on the stack is @code{addr
                   2434: u-count}, where @code{addr} is the address of the first character and
                   2435: @code{u-count} is the number of characters in the string.
                   2436: 
                   2437: @example
                   2438: v4 5 type
                   2439: @end example
                   2440: 
                   2441: You get a string constant with
                   2442: 
                   2443: @example
                   2444: s" hello, world" .s
                   2445: type
                   2446: @end example
                   2447: 
                   2448: Make sure you have a space between @code{s"} and the string; @code{s"}
                   2449: is a normal Forth word and must be delimited with white space (try what
                   2450: happens when you remove the space).
                   2451: 
                   2452: However, this interpretive use of @code{s"} is quite restricted: the
                   2453: string exists only until the next call of @code{s"} (some Forth systems
                   2454: keep more than one of these strings, but usually they still have a
1.62      crook    2455: limited lifetime).
1.48      anton    2456: 
                   2457: @example
                   2458: s" hello," s" world" .s
                   2459: type
                   2460: type
                   2461: @end example
                   2462: 
1.62      crook    2463: You can also use @code{s"} in a definition, and the resulting
                   2464: strings then live forever (well, for as long as the definition):
1.48      anton    2465: 
                   2466: @example
                   2467: : foo s" hello," s" world" ;
                   2468: foo .s
                   2469: type
                   2470: type
                   2471: @end example
                   2472: 
1.141     anton    2473: @quotation Assignment
1.48      anton    2474: @code{Emit ( c -- )} types @code{c} as character (not a number).
                   2475: Implement @code{type ( addr u -- )}.
1.141     anton    2476: @end quotation
1.48      anton    2477: 
1.66      anton    2478: Reference: @ref{Memory Blocks}.
                   2479: 
                   2480: 
1.190     anton    2481: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
1.48      anton    2482: @section Alignment
1.66      anton    2483: @cindex alignment tutorial
                   2484: @cindex memory alignment tutorial
1.48      anton    2485: 
                   2486: On many processors cells have to be aligned in memory, if you want to
                   2487: access them with @code{@@} and @code{!} (and even if the processor does
1.62      crook    2488: not require alignment, access to aligned cells is faster).
1.48      anton    2489: 
                   2490: @code{Create} aligns @code{here} (i.e., the place where the next
                   2491: allocation will occur, and that the @code{create}d word points to).
                   2492: Likewise, the memory produced by @code{allocate} starts at an aligned
                   2493: address.  Adding a number of @code{cells} to an aligned address produces
                   2494: another aligned address.
                   2495: 
                   2496: However, address arithmetic involving @code{char+} and @code{chars} can
                   2497: create an address that is not cell-aligned.  @code{Aligned ( addr --
                   2498: a-addr )} produces the next aligned address:
                   2499: 
                   2500: @example
1.50      anton    2501: v3 char+ aligned .s @@ .
                   2502: v3 char+ .s @@ .
1.48      anton    2503: @end example
                   2504: 
                   2505: Similarly, @code{align} advances @code{here} to the next aligned
                   2506: address:
                   2507: 
                   2508: @example
                   2509: create v5 97 c,
                   2510: here .
                   2511: align here .
                   2512: 1000 ,
                   2513: @end example
                   2514: 
                   2515: Note that you should use aligned addresses even if your processor does
                   2516: not require them, if you want your program to be portable.
                   2517: 
1.66      anton    2518: Reference: @ref{Address arithmetic}.
                   2519: 
1.190     anton    2520: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
                   2521: @section Floating Point
                   2522: @cindex floating point tutorial
                   2523: @cindex FP tutorial
                   2524: 
                   2525: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
                   2526: might expect, but there are a few things worth noting:
                   2527: 
                   2528: The first point is not specific to Forth, but so important and yet not
                   2529: universally known that I mention it here: FP numbers are not reals.
                   2530: Many properties (e.g., arithmetic laws) that reals have and that one
                   2531: expects of all kinds of numbers do not hold for FP numbers.  If you
                   2532: want to use FP computations, you should learn about their problems and
                   2533: how to avoid them; a good starting point is @cite{David Goldberg,
                   2534: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
                   2535: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
                   2536: Computing Surveys 23(1):5@minus{}48, March 1991}.
                   2537: 
                   2538: In Forth source code literal FP numbers need an exponent, e.g.,
                   2539: @code{1e0}; this can also be written shorter as @code{1e},
                   2540: @code{+1.0e+0}, and many variations in between.  The reason for this
                   2541: is that, for historical reasons, Forth interprets a decimal point
                   2542: alone (e.g., @code{1.}) as indicating a double-cell integer.  Another
                   2543: requirement for literal FP numbers is that the current base is
                   2544: decimal; with a hex base @code{1e} is interpreted as an integer.
                   2545: 
                   2546: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
                   2547: ANS Forth system may implement the FP stack on the data stack, but
                   2548: virtually all systems implement a separate FP stack; and programming
                   2549: in a way that accommodates all models is so cumbersome that nobody
                   2550: does it.}  One advantage of this model is that cells are not in the
                   2551: way when accessing FP values, and vice versa.  Forth has a set of
                   2552: words for manipulating the FP stack: @code{fdup fswap fdrop fover
                   2553: frot} and (non-standard) @code{fnip ftuck fpick}.
                   2554: 
                   2555: FP arithmetic words are prefixed with @code{F}.  There is the usual
                   2556: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
                   2557: other functions, e.g., @code{fsqrt fsin fln fmin}.  One word that you
                   2558: might expect is @code{f=}; but @code{f=} is non-standard, because FP
                   2559: computation results are usually inaccurate, so exact comparison is
                   2560: usually a mistake, and one should use approximate comparison.
                   2561: Unfortunately, @code{f~}, the standard word for that purpose, is not
                   2562: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
                   2563: well.
                   2564: 
                   2565: And of course there are words for accessing FP numbers in memory
                   2566: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
                   2567: faligned}).  There are also variants of these words with an @code{sf}
                   2568: and @code{df} prefix for accessing IEEE format single-precision and
                   2569: double-precision numbers in memory; their main purpose is for
                   2570: accessing external FP data (e.g., that has been read from or will be
                   2571: written to a file).
                   2572: 
                   2573: Here is an example of a dot-product word and its use:
                   2574: 
                   2575: @example
                   2576: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   2577:   >r swap 2swap swap 0e r> 0 ?DO
                   2578:     dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
                   2579:   LOOP
                   2580:   2drop 2drop ;
1.48      anton    2581: 
1.190     anton    2582: create v 1.23e f, 4.56e f, 7.89e f,
                   2583: 
                   2584: v 1 floats  v 1 floats  3  v* f.
                   2585: @end example
                   2586: 
                   2587: @quotation Assignment
                   2588: Write a program to solve a quadratic equation.  Then read @cite{Henry
                   2589: G. Baker,
                   2590: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
                   2591: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
                   2592: 33(1):30@minus{}39, January 1998}, and see if you can improve your
                   2593: program.  Finally, find a test case where the original and the
                   2594: improved version produce different results.
                   2595: @end quotation
                   2596: 
                   2597: Reference: @ref{Floating Point}; @ref{Floating point stack};
                   2598: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
                   2599: arithmetic}.
                   2600: 
                   2601: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
1.84      pazsan   2602: @section Files
                   2603: @cindex files tutorial
                   2604: 
                   2605: This section gives a short introduction into how to use files inside
                   2606: Forth. It's broken up into five easy steps:
                   2607: 
                   2608: @enumerate 1
                   2609: @item Opened an ASCII text file for input
                   2610: @item Opened a file for output
                   2611: @item Read input file until string matched (or some other condition matched)
                   2612: @item Wrote some lines from input ( modified or not) to output
                   2613: @item Closed the files.
                   2614: @end enumerate
                   2615: 
1.153     anton    2616: Reference: @ref{General files}.
                   2617: 
1.84      pazsan   2618: @subsection Open file for input
                   2619: 
                   2620: @example
                   2621: s" foo.in"  r/o open-file throw Value fd-in
                   2622: @end example
                   2623: 
                   2624: @subsection Create file for output
                   2625: 
                   2626: @example
                   2627: s" foo.out" w/o create-file throw Value fd-out
                   2628: @end example
                   2629: 
                   2630: The available file modes are r/o for read-only access, r/w for
                   2631: read-write access, and w/o for write-only access. You could open both
                   2632: files with r/w, too, if you like. All file words return error codes; for
                   2633: most applications, it's best to pass there error codes with @code{throw}
                   2634: to the outer error handler.
                   2635: 
                   2636: If you want words for opening and assigning, define them as follows:
                   2637: 
                   2638: @example
                   2639: 0 Value fd-in
                   2640: 0 Value fd-out
                   2641: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
                   2642: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
                   2643: @end example
                   2644: 
                   2645: Usage example:
                   2646: 
                   2647: @example
                   2648: s" foo.in" open-input
                   2649: s" foo.out" open-output
                   2650: @end example
                   2651: 
                   2652: @subsection Scan file for a particular line
                   2653: 
                   2654: @example
                   2655: 256 Constant max-line
                   2656: Create line-buffer  max-line 2 + allot
                   2657: 
                   2658: : scan-file ( addr u -- )
                   2659:   begin
                   2660:       line-buffer max-line fd-in read-line throw
                   2661:   while
                   2662:          >r 2dup line-buffer r> compare 0=
                   2663:      until
                   2664:   else
                   2665:      drop
                   2666:   then
                   2667:   2drop ;
                   2668: @end example
                   2669: 
                   2670: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94      anton    2671: the buffer at addr, and returns the number of bytes read, a flag that is
                   2672: false when the end of file is reached, and an error code.
1.84      pazsan   2673: 
                   2674: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
                   2675: returns zero if both strings are equal. It returns a positive number if
                   2676: the first string is lexically greater, a negative if the second string
                   2677: is lexically greater.
                   2678: 
                   2679: We haven't seen this loop here; it has two exits. Since the @code{while}
                   2680: exits with the number of bytes read on the stack, we have to clean up
                   2681: that separately; that's after the @code{else}.
                   2682: 
                   2683: Usage example:
                   2684: 
                   2685: @example
                   2686: s" The text I search is here" scan-file
                   2687: @end example
                   2688: 
                   2689: @subsection Copy input to output
                   2690: 
                   2691: @example
                   2692: : copy-file ( -- )
                   2693:   begin
                   2694:       line-buffer max-line fd-in read-line throw
                   2695:   while
1.194     anton    2696:       line-buffer swap fd-out write-line throw
1.84      pazsan   2697:   repeat ;
                   2698: @end example
1.194     anton    2699: @c !! does not handle long lines, no newline at end of file
1.84      pazsan   2700: 
                   2701: @subsection Close files
                   2702: 
                   2703: @example
                   2704: fd-in close-file throw
                   2705: fd-out close-file throw
                   2706: @end example
                   2707: 
                   2708: Likewise, you can put that into definitions, too:
                   2709: 
                   2710: @example
                   2711: : close-input ( -- )  fd-in close-file throw ;
                   2712: : close-output ( -- )  fd-out close-file throw ;
                   2713: @end example
                   2714: 
1.141     anton    2715: @quotation Assignment
1.84      pazsan   2716: How could you modify @code{copy-file} so that it copies until a second line is
                   2717: matched? Can you write a program that extracts a section of a text file,
                   2718: given the line that starts and the line that terminates that section?
1.141     anton    2719: @end quotation
1.84      pazsan   2720: 
                   2721: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48      anton    2722: @section Interpretation and Compilation Semantics and Immediacy
1.66      anton    2723: @cindex semantics tutorial
                   2724: @cindex interpretation semantics tutorial
                   2725: @cindex compilation semantics tutorial
                   2726: @cindex immediate, tutorial
1.48      anton    2727: 
                   2728: When a word is compiled, it behaves differently from being interpreted.
                   2729: E.g., consider @code{+}:
                   2730: 
                   2731: @example
                   2732: 1 2 + .
                   2733: : foo + ;
                   2734: @end example
                   2735: 
                   2736: These two behaviours are known as compilation and interpretation
                   2737: semantics.  For normal words (e.g., @code{+}), the compilation semantics
                   2738: is to append the interpretation semantics to the currently defined word
                   2739: (@code{foo} in the example above).  I.e., when @code{foo} is executed
                   2740: later, the interpretation semantics of @code{+} (i.e., adding two
                   2741: numbers) will be performed.
                   2742: 
                   2743: However, there are words with non-default compilation semantics, e.g.,
                   2744: the control-flow words like @code{if}.  You can use @code{immediate} to
                   2745: change the compilation semantics of the last defined word to be equal to
                   2746: the interpretation semantics:
                   2747: 
                   2748: @example
                   2749: : [FOO] ( -- )
                   2750:  5 . ; immediate
                   2751: 
                   2752: [FOO]
                   2753: : bar ( -- )
                   2754:   [FOO] ;
                   2755: bar
                   2756: see bar
                   2757: @end example
                   2758: 
                   2759: Two conventions to mark words with non-default compilation semnatics are
                   2760: names with brackets (more frequently used) and to write them all in
                   2761: upper case (less frequently used).
                   2762: 
                   2763: In Gforth (and many other systems) you can also remove the
                   2764: interpretation semantics with @code{compile-only} (the compilation
                   2765: semantics is derived from the original interpretation semantics):
                   2766: 
                   2767: @example
                   2768: : flip ( -- )
                   2769:  6 . ; compile-only \ but not immediate
                   2770: flip
                   2771: 
                   2772: : flop ( -- )
                   2773:  flip ;
                   2774: flop
                   2775: @end example
                   2776: 
                   2777: In this example the interpretation semantics of @code{flop} is equal to
                   2778: the original interpretation semantics of @code{flip}.
                   2779: 
                   2780: The text interpreter has two states: in interpret state, it performs the
                   2781: interpretation semantics of words it encounters; in compile state, it
                   2782: performs the compilation semantics of these words.
                   2783: 
                   2784: Among other things, @code{:} switches into compile state, and @code{;}
                   2785: switches back to interpret state.  They contain the factors @code{]}
                   2786: (switch to compile state) and @code{[} (switch to interpret state), that
                   2787: do nothing but switch the state.
                   2788: 
                   2789: @example
                   2790: : xxx ( -- )
                   2791:   [ 5 . ]
                   2792: ;
                   2793: 
                   2794: xxx
                   2795: see xxx
                   2796: @end example
                   2797: 
                   2798: These brackets are also the source of the naming convention mentioned
                   2799: above.
                   2800: 
1.66      anton    2801: Reference: @ref{Interpretation and Compilation Semantics}.
                   2802: 
1.48      anton    2803: 
                   2804: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
                   2805: @section Execution Tokens
1.66      anton    2806: @cindex execution tokens tutorial
                   2807: @cindex XT tutorial
1.48      anton    2808: 
                   2809: @code{' word} gives you the execution token (XT) of a word.  The XT is a
                   2810: cell representing the interpretation semantics of a word.  You can
                   2811: execute this semantics with @code{execute}:
                   2812: 
                   2813: @example
                   2814: ' + .s
                   2815: 1 2 rot execute .
                   2816: @end example
                   2817: 
                   2818: The XT is similar to a function pointer in C.  However, parameter
                   2819: passing through the stack makes it a little more flexible:
                   2820: 
                   2821: @example
                   2822: : map-array ( ... addr u xt -- ... )
1.50      anton    2823: \ executes xt ( ... x -- ... ) for every element of the array starting
                   2824: \ at addr and containing u elements
1.48      anton    2825:   @{ xt @}
                   2826:   cells over + swap ?do
1.50      anton    2827:     i @@ xt execute
1.48      anton    2828:   1 cells +loop ;
                   2829: 
                   2830: create a 3 , 4 , 2 , -1 , 4 ,
                   2831: a 5 ' . map-array .s
                   2832: 0 a 5 ' + map-array .
                   2833: s" max-n" environment? drop .s
                   2834: a 5 ' min map-array .
                   2835: @end example
                   2836: 
                   2837: You can use map-array with the XTs of words that consume one element
                   2838: more than they produce.  In theory you can also use it with other XTs,
                   2839: but the stack effect then depends on the size of the array, which is
                   2840: hard to understand.
                   2841: 
1.51      pazsan   2842: Since XTs are cell-sized, you can store them in memory and manipulate
                   2843: them on the stack like other cells.  You can also compile the XT into a
1.48      anton    2844: word with @code{compile,}:
                   2845: 
                   2846: @example
                   2847: : foo1 ( n1 n2 -- n )
                   2848:    [ ' + compile, ] ;
                   2849: see foo
                   2850: @end example
                   2851: 
                   2852: This is non-standard, because @code{compile,} has no compilation
                   2853: semantics in the standard, but it works in good Forth systems.  For the
                   2854: broken ones, use
                   2855: 
                   2856: @example
                   2857: : [compile,] compile, ; immediate
                   2858: 
                   2859: : foo1 ( n1 n2 -- n )
                   2860:    [ ' + ] [compile,] ;
                   2861: see foo
                   2862: @end example
                   2863: 
                   2864: @code{'} is a word with default compilation semantics; it parses the
                   2865: next word when its interpretation semantics are executed, not during
                   2866: compilation:
                   2867: 
                   2868: @example
                   2869: : foo ( -- xt )
                   2870:   ' ;
                   2871: see foo
                   2872: : bar ( ... "word" -- ... )
                   2873:   ' execute ;
                   2874: see bar
1.60      anton    2875: 1 2 bar + .
1.48      anton    2876: @end example
                   2877: 
                   2878: You often want to parse a word during compilation and compile its XT so
                   2879: it will be pushed on the stack at run-time.  @code{[']} does this:
                   2880: 
                   2881: @example
                   2882: : xt-+ ( -- xt )
                   2883:   ['] + ;
                   2884: see xt-+
                   2885: 1 2 xt-+ execute .
                   2886: @end example
                   2887: 
                   2888: Many programmers tend to see @code{'} and the word it parses as one
                   2889: unit, and expect it to behave like @code{[']} when compiled, and are
                   2890: confused by the actual behaviour.  If you are, just remember that the
                   2891: Forth system just takes @code{'} as one unit and has no idea that it is
                   2892: a parsing word (attempts to convenience programmers in this issue have
                   2893: usually resulted in even worse pitfalls, see
1.66      anton    2894: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
                   2895: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48      anton    2896: 
                   2897: Note that the state of the interpreter does not come into play when
1.51      pazsan   2898: creating and executing XTs.  I.e., even when you execute @code{'} in
1.48      anton    2899: compile state, it still gives you the interpretation semantics.  And
                   2900: whatever that state is, @code{execute} performs the semantics
1.66      anton    2901: represented by the XT (i.e., for XTs produced with @code{'} the
                   2902: interpretation semantics).
                   2903: 
                   2904: Reference: @ref{Tokens for Words}.
1.48      anton    2905: 
                   2906: 
                   2907: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
                   2908: @section Exceptions
1.66      anton    2909: @cindex exceptions tutorial
1.48      anton    2910: 
                   2911: @code{throw ( n -- )} causes an exception unless n is zero.
                   2912: 
                   2913: @example
                   2914: 100 throw .s
                   2915: 0 throw .s
                   2916: @end example
                   2917: 
                   2918: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
                   2919: it catches exceptions and pushes the number of the exception on the
                   2920: stack (or 0, if the xt executed without exception).  If there was an
                   2921: exception, the stacks have the same depth as when entering @code{catch}:
                   2922: 
                   2923: @example
                   2924: .s
                   2925: 3 0 ' / catch .s
                   2926: 3 2 ' / catch .s
                   2927: @end example
                   2928: 
1.141     anton    2929: @quotation Assignment
1.48      anton    2930: Try the same with @code{execute} instead of @code{catch}.
1.141     anton    2931: @end quotation
1.48      anton    2932: 
                   2933: @code{Throw} always jumps to the dynamically next enclosing
                   2934: @code{catch}, even if it has to leave several call levels to achieve
                   2935: this:
                   2936: 
                   2937: @example
                   2938: : foo 100 throw ;
                   2939: : foo1 foo ." after foo" ;
1.51      pazsan   2940: : bar ['] foo1 catch ;
1.60      anton    2941: bar .
1.48      anton    2942: @end example
                   2943: 
                   2944: It is often important to restore a value upon leaving a definition, even
                   2945: if the definition is left through an exception.  You can ensure this
                   2946: like this:
                   2947: 
                   2948: @example
                   2949: : ...
                   2950:    save-x
1.51      pazsan   2951:    ['] word-changing-x catch ( ... n )
1.48      anton    2952:    restore-x
                   2953:    ( ... n ) throw ;
                   2954: @end example
                   2955: 
1.172     anton    2956: However, this is still not safe against, e.g., the user pressing
                   2957: @kbd{Ctrl-C} when execution is between the @code{catch} and
                   2958: @code{restore-x}.
                   2959: 
                   2960: Gforth provides an alternative exception handling syntax that is safe
                   2961: against such cases: @code{try ... restore ... endtry}.  If the code
                   2962: between @code{try} and @code{endtry} has an exception, the stack
                   2963: depths are restored, the exception number is pushed on the stack, and
                   2964: the execution continues right after @code{restore}.
1.48      anton    2965: 
1.172     anton    2966: The safer equivalent to the restoration code above is
1.48      anton    2967: 
                   2968: @example
                   2969: : ...
                   2970:   save-x
                   2971:   try
1.92      anton    2972:     word-changing-x 0
1.172     anton    2973:   restore
                   2974:     restore-x
                   2975:   endtry
1.48      anton    2976:   throw ;
                   2977: @end example
                   2978: 
1.66      anton    2979: Reference: @ref{Exception Handling}.
                   2980: 
1.48      anton    2981: 
                   2982: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
                   2983: @section Defining Words
1.66      anton    2984: @cindex defining words tutorial
                   2985: @cindex does> tutorial
                   2986: @cindex create...does> tutorial
                   2987: 
                   2988: @c before semantics?
1.48      anton    2989: 
                   2990: @code{:}, @code{create}, and @code{variable} are definition words: They
                   2991: define other words.  @code{Constant} is another definition word:
                   2992: 
                   2993: @example
                   2994: 5 constant foo
                   2995: foo .
                   2996: @end example
                   2997: 
                   2998: You can also use the prefixes @code{2} (double-cell) and @code{f}
                   2999: (floating point) with @code{variable} and @code{constant}.
                   3000: 
                   3001: You can also define your own defining words.  E.g.:
                   3002: 
                   3003: @example
                   3004: : variable ( "name" -- )
                   3005:   create 0 , ;
                   3006: @end example
                   3007: 
                   3008: You can also define defining words that create words that do something
                   3009: other than just producing their address:
                   3010: 
                   3011: @example
                   3012: : constant ( n "name" -- )
                   3013:   create ,
                   3014: does> ( -- n )
1.50      anton    3015:   ( addr ) @@ ;
1.48      anton    3016: 
                   3017: 5 constant foo
                   3018: foo .
                   3019: @end example
                   3020: 
                   3021: The definition of @code{constant} above ends at the @code{does>}; i.e.,
                   3022: @code{does>} replaces @code{;}, but it also does something else: It
                   3023: changes the last defined word such that it pushes the address of the
                   3024: body of the word and then performs the code after the @code{does>}
                   3025: whenever it is called.
                   3026: 
                   3027: In the example above, @code{constant} uses @code{,} to store 5 into the
                   3028: body of @code{foo}.  When @code{foo} executes, it pushes the address of
                   3029: the body onto the stack, then (in the code after the @code{does>})
                   3030: fetches the 5 from there.
                   3031: 
                   3032: The stack comment near the @code{does>} reflects the stack effect of the
                   3033: defined word, not the stack effect of the code after the @code{does>}
                   3034: (the difference is that the code expects the address of the body that
                   3035: the stack comment does not show).
                   3036: 
                   3037: You can use these definition words to do factoring in cases that involve
                   3038: (other) definition words.  E.g., a field offset is always added to an
                   3039: address.  Instead of defining
                   3040: 
                   3041: @example
                   3042: 2 cells constant offset-field1
                   3043: @end example
                   3044: 
                   3045: and using this like
                   3046: 
                   3047: @example
                   3048: ( addr ) offset-field1 +
                   3049: @end example
                   3050: 
                   3051: you can define a definition word
                   3052: 
                   3053: @example
                   3054: : simple-field ( n "name" -- )
                   3055:   create ,
                   3056: does> ( n1 -- n1+n )
1.50      anton    3057:   ( addr ) @@ + ;
1.48      anton    3058: @end example
1.21      crook    3059: 
1.48      anton    3060: Definition and use of field offsets now look like this:
1.21      crook    3061: 
1.48      anton    3062: @example
                   3063: 2 cells simple-field field1
1.60      anton    3064: create mystruct 4 cells allot
                   3065: mystruct .s field1 .s drop
1.48      anton    3066: @end example
1.21      crook    3067: 
1.48      anton    3068: If you want to do something with the word without performing the code
                   3069: after the @code{does>}, you can access the body of a @code{create}d word
                   3070: with @code{>body ( xt -- addr )}:
1.21      crook    3071: 
1.48      anton    3072: @example
                   3073: : value ( n "name" -- )
                   3074:   create ,
                   3075: does> ( -- n1 )
1.50      anton    3076:   @@ ;
1.48      anton    3077: : to ( n "name" -- )
                   3078:   ' >body ! ;
1.21      crook    3079: 
1.48      anton    3080: 5 value foo
                   3081: foo .
                   3082: 7 to foo
                   3083: foo .
                   3084: @end example
1.21      crook    3085: 
1.141     anton    3086: @quotation Assignment
1.48      anton    3087: Define @code{defer ( "name" -- )}, which creates a word that stores an
                   3088: XT (at the start the XT of @code{abort}), and upon execution
                   3089: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
                   3090: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
                   3091: recursion is one application of @code{defer}.
1.141     anton    3092: @end quotation
1.29      crook    3093: 
1.66      anton    3094: Reference: @ref{User-defined Defining Words}.
                   3095: 
                   3096: 
1.48      anton    3097: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
                   3098: @section Arrays and Records
1.66      anton    3099: @cindex arrays tutorial
                   3100: @cindex records tutorial
                   3101: @cindex structs tutorial
1.29      crook    3102: 
1.48      anton    3103: Forth has no standard words for defining data structures such as arrays
                   3104: and records (structs in C terminology), but you can build them yourself
                   3105: based on address arithmetic.  You can also define words for defining
                   3106: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29      crook    3107: 
1.48      anton    3108: One of the first projects a Forth newcomer sets out upon when learning
                   3109: about defining words is an array defining word (possibly for
                   3110: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
                   3111: learn something from it.  However, don't be disappointed when you later
                   3112: learn that you have little use for these words (inappropriate use would
                   3113: be even worse).  I have not yet found a set of useful array words yet;
                   3114: the needs are just too diverse, and named, global arrays (the result of
                   3115: naive use of defining words) are often not flexible enough (e.g.,
1.66      anton    3116: consider how to pass them as parameters).  Another such project is a set
                   3117: of words to help dealing with strings.
1.29      crook    3118: 
1.48      anton    3119: On the other hand, there is a useful set of record words, and it has
                   3120: been defined in @file{compat/struct.fs}; these words are predefined in
                   3121: Gforth.  They are explained in depth elsewhere in this manual (see
                   3122: @pxref{Structures}).  The @code{simple-field} example above is
                   3123: simplified variant of fields in this package.
1.21      crook    3124: 
                   3125: 
1.48      anton    3126: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
                   3127: @section @code{POSTPONE}
1.66      anton    3128: @cindex postpone tutorial
1.21      crook    3129: 
1.48      anton    3130: You can compile the compilation semantics (instead of compiling the
                   3131: interpretation semantics) of a word with @code{POSTPONE}:
1.21      crook    3132: 
1.48      anton    3133: @example
                   3134: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51      pazsan   3135:  POSTPONE + ; immediate
1.48      anton    3136: : foo ( n1 n2 -- n )
                   3137:  MY-+ ;
                   3138: 1 2 foo .
                   3139: see foo
                   3140: @end example
1.21      crook    3141: 
1.48      anton    3142: During the definition of @code{foo} the text interpreter performs the
                   3143: compilation semantics of @code{MY-+}, which performs the compilation
                   3144: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
                   3145: 
                   3146: This example also displays separate stack comments for the compilation
                   3147: semantics and for the stack effect of the compiled code.  For words with
                   3148: default compilation semantics these stack effects are usually not
                   3149: displayed; the stack effect of the compilation semantics is always
                   3150: @code{( -- )} for these words, the stack effect for the compiled code is
                   3151: the stack effect of the interpretation semantics.
                   3152: 
                   3153: Note that the state of the interpreter does not come into play when
                   3154: performing the compilation semantics in this way.  You can also perform
                   3155: it interpretively, e.g.:
                   3156: 
                   3157: @example
                   3158: : foo2 ( n1 n2 -- n )
                   3159:  [ MY-+ ] ;
                   3160: 1 2 foo .
                   3161: see foo
                   3162: @end example
1.21      crook    3163: 
1.48      anton    3164: However, there are some broken Forth systems where this does not always
1.62      crook    3165: work, and therefore this practice was been declared non-standard in
1.48      anton    3166: 1999.
                   3167: @c !! repair.fs
                   3168: 
                   3169: Here is another example for using @code{POSTPONE}:
1.44      crook    3170: 
1.48      anton    3171: @example
                   3172: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
                   3173:  POSTPONE negate POSTPONE + ; immediate compile-only
                   3174: : bar ( n1 n2 -- n )
                   3175:   MY-- ;
                   3176: 2 1 bar .
                   3177: see bar
                   3178: @end example
1.21      crook    3179: 
1.48      anton    3180: You can define @code{ENDIF} in this way:
1.21      crook    3181: 
1.48      anton    3182: @example
                   3183: : ENDIF ( Compilation: orig -- )
                   3184:   POSTPONE then ; immediate
                   3185: @end example
1.21      crook    3186: 
1.141     anton    3187: @quotation Assignment
1.48      anton    3188: Write @code{MY-2DUP} that has compilation semantics equivalent to
                   3189: @code{2dup}, but compiles @code{over over}.
1.141     anton    3190: @end quotation
1.29      crook    3191: 
1.66      anton    3192: @c !! @xref{Macros} for reference
                   3193: 
                   3194: 
1.48      anton    3195: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
                   3196: @section @code{Literal}
1.66      anton    3197: @cindex literal tutorial
1.29      crook    3198: 
1.48      anton    3199: You cannot @code{POSTPONE} numbers:
1.21      crook    3200: 
1.48      anton    3201: @example
                   3202: : [FOO] POSTPONE 500 ; immediate
1.21      crook    3203: @end example
                   3204: 
1.48      anton    3205: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29      crook    3206: 
1.48      anton    3207: @example
                   3208: : [FOO] ( compilation: --; run-time: -- n )
                   3209:   500 POSTPONE literal ; immediate
1.29      crook    3210: 
1.60      anton    3211: : flip [FOO] ;
1.48      anton    3212: flip .
                   3213: see flip
                   3214: @end example
1.29      crook    3215: 
1.48      anton    3216: @code{LITERAL} consumes a number at compile-time (when it's compilation
                   3217: semantics are executed) and pushes it at run-time (when the code it
                   3218: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
                   3219: number computed at compile time into the current word:
1.29      crook    3220: 
1.48      anton    3221: @example
                   3222: : bar ( -- n )
                   3223:   [ 2 2 + ] literal ;
                   3224: see bar
                   3225: @end example
1.29      crook    3226: 
1.141     anton    3227: @quotation Assignment
1.48      anton    3228: Write @code{]L} which allows writing the example above as @code{: bar (
                   3229: -- n ) [ 2 2 + ]L ;}
1.141     anton    3230: @end quotation
1.48      anton    3231: 
1.66      anton    3232: @c !! @xref{Macros} for reference
                   3233: 
1.48      anton    3234: 
                   3235: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
                   3236: @section Advanced macros
1.66      anton    3237: @cindex macros, advanced tutorial
                   3238: @cindex run-time code generation, tutorial
1.48      anton    3239: 
1.66      anton    3240: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
                   3241: Execution Tokens}.  It frequently performs @code{execute}, a relatively
                   3242: expensive operation in some Forth implementations.  You can use
1.48      anton    3243: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
                   3244: and produce a word that contains the word to be performed directly:
                   3245: 
                   3246: @c use ]] ... [[
                   3247: @example
                   3248: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
                   3249: \ at run-time, execute xt ( ... x -- ... ) for each element of the
                   3250: \ array beginning at addr and containing u elements
                   3251:   @{ xt @}
                   3252:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50      anton    3253:     POSTPONE i POSTPONE @@ xt compile,
1.48      anton    3254:   1 cells POSTPONE literal POSTPONE +loop ;
                   3255: 
                   3256: : sum-array ( addr u -- n )
                   3257:  0 rot rot [ ' + compile-map-array ] ;
                   3258: see sum-array
                   3259: a 5 sum-array .
                   3260: @end example
                   3261: 
                   3262: You can use the full power of Forth for generating the code; here's an
                   3263: example where the code is generated in a loop:
                   3264: 
                   3265: @example
                   3266: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
                   3267: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50      anton    3268:   POSTPONE tuck POSTPONE @@
1.48      anton    3269:   POSTPONE literal POSTPONE * POSTPONE +
                   3270:   POSTPONE swap POSTPONE cell+ ;
                   3271: 
                   3272: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51      pazsan   3273: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48      anton    3274:   0 postpone literal postpone swap
                   3275:   [ ' compile-vmul-step compile-map-array ]
                   3276:   postpone drop ;
                   3277: see compile-vmul
                   3278: 
                   3279: : a-vmul ( addr -- n )
1.51      pazsan   3280: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48      anton    3281:  [ a 5 compile-vmul ] ;
                   3282: see a-vmul
                   3283: a a-vmul .
                   3284: @end example
                   3285: 
                   3286: This example uses @code{compile-map-array} to show off, but you could
1.66      anton    3287: also use @code{map-array} instead (try it now!).
1.48      anton    3288: 
                   3289: You can use this technique for efficient multiplication of large
                   3290: matrices.  In matrix multiplication, you multiply every line of one
                   3291: matrix with every column of the other matrix.  You can generate the code
                   3292: for one line once, and use it for every column.  The only downside of
                   3293: this technique is that it is cumbersome to recover the memory consumed
                   3294: by the generated code when you are done (and in more complicated cases
                   3295: it is not possible portably).
                   3296: 
1.66      anton    3297: @c !! @xref{Macros} for reference
                   3298: 
                   3299: 
1.48      anton    3300: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
                   3301: @section Compilation Tokens
1.66      anton    3302: @cindex compilation tokens, tutorial
                   3303: @cindex CT, tutorial
1.48      anton    3304: 
                   3305: This section is Gforth-specific.  You can skip it.
                   3306: 
                   3307: @code{' word compile,} compiles the interpretation semantics.  For words
                   3308: with default compilation semantics this is the same as performing the
                   3309: compilation semantics.  To represent the compilation semantics of other
                   3310: words (e.g., words like @code{if} that have no interpretation
                   3311: semantics), Gforth has the concept of a compilation token (CT,
                   3312: consisting of two cells), and words @code{comp'} and @code{[comp']}.
                   3313: You can perform the compilation semantics represented by a CT with
                   3314: @code{execute}:
1.29      crook    3315: 
1.48      anton    3316: @example
                   3317: : foo2 ( n1 n2 -- n )
                   3318:    [ comp' + execute ] ;
                   3319: see foo
                   3320: @end example
1.29      crook    3321: 
1.48      anton    3322: You can compile the compilation semantics represented by a CT with
                   3323: @code{postpone,}:
1.30      anton    3324: 
1.48      anton    3325: @example
                   3326: : foo3 ( -- )
                   3327:   [ comp' + postpone, ] ;
                   3328: see foo3
                   3329: @end example
1.30      anton    3330: 
1.51      pazsan   3331: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48      anton    3332: @code{comp'} is particularly useful for words that have no
                   3333: interpretation semantics:
1.29      crook    3334: 
1.30      anton    3335: @example
1.48      anton    3336: ' if
1.60      anton    3337: comp' if .s 2drop
1.30      anton    3338: @end example
                   3339: 
1.66      anton    3340: Reference: @ref{Tokens for Words}.
                   3341: 
1.29      crook    3342: 
1.48      anton    3343: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
                   3344: @section Wordlists and Search Order
1.66      anton    3345: @cindex wordlists tutorial
                   3346: @cindex search order, tutorial
1.48      anton    3347: 
                   3348: The dictionary is not just a memory area that allows you to allocate
                   3349: memory with @code{allot}, it also contains the Forth words, arranged in
                   3350: several wordlists.  When searching for a word in a wordlist,
                   3351: conceptually you start searching at the youngest and proceed towards
                   3352: older words (in reality most systems nowadays use hash-tables); i.e., if
                   3353: you define a word with the same name as an older word, the new word
                   3354: shadows the older word.
                   3355: 
                   3356: Which wordlists are searched in which order is determined by the search
                   3357: order.  You can display the search order with @code{order}.  It displays
                   3358: first the search order, starting with the wordlist searched first, then
                   3359: it displays the wordlist that will contain newly defined words.
1.21      crook    3360: 
1.48      anton    3361: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21      crook    3362: 
1.48      anton    3363: @example
                   3364: wordlist constant mywords
                   3365: @end example
1.21      crook    3366: 
1.48      anton    3367: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
                   3368: defined words (the @emph{current} wordlist):
1.21      crook    3369: 
1.48      anton    3370: @example
                   3371: mywords set-current
                   3372: order
                   3373: @end example
1.26      crook    3374: 
1.48      anton    3375: Gforth does not display a name for the wordlist in @code{mywords}
                   3376: because this wordlist was created anonymously with @code{wordlist}.
1.21      crook    3377: 
1.48      anton    3378: You can get the current wordlist with @code{get-current ( -- wid)}.  If
                   3379: you want to put something into a specific wordlist without overall
                   3380: effect on the current wordlist, this typically looks like this:
1.21      crook    3381: 
1.48      anton    3382: @example
                   3383: get-current mywords set-current ( wid )
                   3384: create someword
                   3385: ( wid ) set-current
                   3386: @end example
1.21      crook    3387: 
1.48      anton    3388: You can write the search order with @code{set-order ( wid1 .. widn n --
                   3389: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
                   3390: searched wordlist is topmost.
1.21      crook    3391: 
1.48      anton    3392: @example
                   3393: get-order mywords swap 1+ set-order
                   3394: order
                   3395: @end example
1.21      crook    3396: 
1.48      anton    3397: Yes, the order of wordlists in the output of @code{order} is reversed
                   3398: from stack comments and the output of @code{.s} and thus unintuitive.
1.21      crook    3399: 
1.141     anton    3400: @quotation Assignment
1.48      anton    3401: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
                   3402: wordlist to the search order.  Define @code{previous ( -- )}, which
                   3403: removes the first searched wordlist from the search order.  Experiment
                   3404: with boundary conditions (you will see some crashes or situations that
                   3405: are hard or impossible to leave).
1.141     anton    3406: @end quotation
1.21      crook    3407: 
1.48      anton    3408: The search order is a powerful foundation for providing features similar
                   3409: to Modula-2 modules and C++ namespaces.  However, trying to modularize
                   3410: programs in this way has disadvantages for debugging and reuse/factoring
                   3411: that overcome the advantages in my experience (I don't do huge projects,
1.55      anton    3412: though).  These disadvantages are not so clear in other
1.82      anton    3413: languages/programming environments, because these languages are not so
1.48      anton    3414: strong in debugging and reuse.
1.21      crook    3415: 
1.66      anton    3416: @c !! example
                   3417: 
                   3418: Reference: @ref{Word Lists}.
1.21      crook    3419: 
1.29      crook    3420: @c ******************************************************************
1.48      anton    3421: @node Introduction, Words, Tutorial, Top
1.29      crook    3422: @comment node-name,     next,           previous, up
                   3423: @chapter An Introduction to ANS Forth
                   3424: @cindex Forth - an introduction
1.21      crook    3425: 
1.83      anton    3426: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
                   3427: that it is slower-paced in its examples, but uses them to dive deep into
                   3428: explaining Forth internals (not covered by the Tutorial).  Apart from
                   3429: that, this chapter covers far less material.  It is suitable for reading
                   3430: without using a computer.
                   3431: 
1.29      crook    3432: The primary purpose of this manual is to document Gforth. However, since
                   3433: Forth is not a widely-known language and there is a lack of up-to-date
                   3434: teaching material, it seems worthwhile to provide some introductory
1.49      anton    3435: material.  For other sources of Forth-related
                   3436: information, see @ref{Forth-related information}.
1.21      crook    3437: 
1.29      crook    3438: The examples in this section should work on any ANS Forth; the
                   3439: output shown was produced using Gforth. Each example attempts to
                   3440: reproduce the exact output that Gforth produces. If you try out the
                   3441: examples (and you should), what you should type is shown @kbd{like this}
                   3442: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    3443: that, where the example shows @key{RET} it means that you should
1.29      crook    3444: press the ``carriage return'' key. Unfortunately, some output formats for
                   3445: this manual cannot show the difference between @kbd{this} and
                   3446: @code{this} which will make trying out the examples harder (but not
                   3447: impossible).
1.21      crook    3448: 
1.29      crook    3449: Forth is an unusual language. It provides an interactive development
                   3450: environment which includes both an interpreter and compiler. Forth
                   3451: programming style encourages you to break a problem down into many
                   3452: @cindex factoring
                   3453: small fragments (@dfn{factoring}), and then to develop and test each
                   3454: fragment interactively. Forth advocates assert that breaking the
                   3455: edit-compile-test cycle used by conventional programming languages can
                   3456: lead to great productivity improvements.
1.21      crook    3457: 
1.29      crook    3458: @menu
1.67      anton    3459: * Introducing the Text Interpreter::  
                   3460: * Stacks and Postfix notation::  
                   3461: * Your first definition::       
                   3462: * How does that work?::         
                   3463: * Forth is written in Forth::   
                   3464: * Review - elements of a Forth system::  
                   3465: * Where to go next::            
                   3466: * Exercises::                   
1.29      crook    3467: @end menu
1.21      crook    3468: 
1.29      crook    3469: @comment ----------------------------------------------
                   3470: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   3471: @section Introducing the Text Interpreter
                   3472: @cindex text interpreter
                   3473: @cindex outer interpreter
1.21      crook    3474: 
1.30      anton    3475: @c IMO this is too detailed and the pace is too slow for
                   3476: @c an introduction.  If you know German, take a look at
                   3477: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   3478: @c to see how I do it - anton 
                   3479: 
1.44      crook    3480: @c nac-> Where I have accepted your comments 100% and modified the text
                   3481: @c accordingly, I have deleted your comments. Elsewhere I have added a
                   3482: @c response like this to attempt to rationalise what I have done. Of
                   3483: @c course, this is a very clumsy mechanism for something that would be
                   3484: @c done far more efficiently over a beer. Please delete any dialogue
                   3485: @c you consider closed.
                   3486: 
1.29      crook    3487: When you invoke the Forth image, you will see a startup banner printed
                   3488: and nothing else (if you have Gforth installed on your system, try
1.30      anton    3489: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    3490: its command line interpreter, which is called the @dfn{Text Interpreter}
                   3491: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.49      anton    3492: about the text interpreter as you read through this chapter, for more
                   3493: detail @pxref{The Text Interpreter}).
1.21      crook    3494: 
1.29      crook    3495: Although it's not obvious, Forth is actually waiting for your
1.30      anton    3496: input. Type a number and press the @key{RET} key:
1.21      crook    3497: 
1.26      crook    3498: @example
1.30      anton    3499: @kbd{45@key{RET}}  ok
1.26      crook    3500: @end example
1.21      crook    3501: 
1.29      crook    3502: Rather than give you a prompt to invite you to input something, the text
                   3503: interpreter prints a status message @i{after} it has processed a line
                   3504: of input. The status message in this case (``@code{ ok}'' followed by
                   3505: carriage-return) indicates that the text interpreter was able to process
                   3506: all of your input successfully. Now type something illegal:
                   3507: 
                   3508: @example
1.30      anton    3509: @kbd{qwer341@key{RET}}
1.134     anton    3510: *the terminal*:2: Undefined word
                   3511: >>>qwer341<<<
                   3512: Backtrace:
                   3513: $2A95B42A20 throw 
                   3514: $2A95B57FB8 no.extensions 
1.29      crook    3515: @end example
1.23      crook    3516: 
1.134     anton    3517: The exact text, other than the ``Undefined word'' may differ slightly
                   3518: on your system, but the effect is the same; when the text interpreter
1.29      crook    3519: detects an error, it discards any remaining text on a line, resets
1.134     anton    3520: certain internal state and prints an error message. For a detailed
                   3521: description of error messages see @ref{Error messages}.
1.23      crook    3522: 
1.29      crook    3523: The text interpreter waits for you to press carriage-return, and then
                   3524: processes your input line. Starting at the beginning of the line, it
                   3525: breaks the line into groups of characters separated by spaces. For each
                   3526: group of characters in turn, it makes two attempts to do something:
1.23      crook    3527: 
1.29      crook    3528: @itemize @bullet
                   3529: @item
1.44      crook    3530: @cindex name dictionary
1.29      crook    3531: It tries to treat it as a command. It does this by searching a @dfn{name
                   3532: dictionary}. If the group of characters matches an entry in the name
                   3533: dictionary, the name dictionary provides the text interpreter with
                   3534: information that allows the text interpreter perform some actions. In
                   3535: Forth jargon, we say that the group
                   3536: @cindex word
                   3537: @cindex definition
                   3538: @cindex execution token
                   3539: @cindex xt
                   3540: of characters names a @dfn{word}, that the dictionary search returns an
                   3541: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   3542: word, and that the text interpreter executes the xt. Often, the terms
                   3543: @dfn{word} and @dfn{definition} are used interchangeably.
                   3544: @item
                   3545: If the text interpreter fails to find a match in the name dictionary, it
                   3546: tries to treat the group of characters as a number in the current number
                   3547: base (when you start up Forth, the current number base is base 10). If
                   3548: the group of characters legitimately represents a number, the text
                   3549: interpreter pushes the number onto a stack (we'll learn more about that
                   3550: in the next section).
                   3551: @end itemize
1.23      crook    3552: 
1.29      crook    3553: If the text interpreter is unable to do either of these things with any
                   3554: group of characters, it discards the group of characters and the rest of
                   3555: the line, then prints an error message. If the text interpreter reaches
                   3556: the end of the line without error, it prints the status message ``@code{ ok}''
                   3557: followed by carriage-return.
1.21      crook    3558: 
1.29      crook    3559: This is the simplest command we can give to the text interpreter:
1.23      crook    3560: 
                   3561: @example
1.30      anton    3562: @key{RET}  ok
1.23      crook    3563: @end example
1.21      crook    3564: 
1.29      crook    3565: The text interpreter did everything we asked it to do (nothing) without
                   3566: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   3567: command:
1.21      crook    3568: 
1.23      crook    3569: @example
1.30      anton    3570: @kbd{12 dup fred dup@key{RET}}
1.134     anton    3571: *the terminal*:3: Undefined word
                   3572: 12 dup >>>fred<<< dup
                   3573: Backtrace:
                   3574: $2A95B42A20 throw 
                   3575: $2A95B57FB8 no.extensions 
1.23      crook    3576: @end example
1.21      crook    3577: 
1.29      crook    3578: When you press the carriage-return key, the text interpreter starts to
                   3579: work its way along the line:
1.21      crook    3580: 
1.29      crook    3581: @itemize @bullet
                   3582: @item
                   3583: When it gets to the space after the @code{2}, it takes the group of
                   3584: characters @code{12} and looks them up in the name
                   3585: dictionary@footnote{We can't tell if it found them or not, but assume
                   3586: for now that it did not}. There is no match for this group of characters
                   3587: in the name dictionary, so it tries to treat them as a number. It is
                   3588: able to do this successfully, so it puts the number, 12, ``on the stack''
                   3589: (whatever that means).
                   3590: @item
                   3591: The text interpreter resumes scanning the line and gets the next group
                   3592: of characters, @code{dup}. It looks it up in the name dictionary and
                   3593: (you'll have to take my word for this) finds it, and executes the word
                   3594: @code{dup} (whatever that means).
                   3595: @item
                   3596: Once again, the text interpreter resumes scanning the line and gets the
                   3597: group of characters @code{fred}. It looks them up in the name
                   3598: dictionary, but can't find them. It tries to treat them as a number, but
                   3599: they don't represent any legal number.
                   3600: @end itemize
1.21      crook    3601: 
1.29      crook    3602: At this point, the text interpreter gives up and prints an error
                   3603: message. The error message shows exactly how far the text interpreter
                   3604: got in processing the line. In particular, it shows that the text
                   3605: interpreter made no attempt to do anything with the final character
                   3606: group, @code{dup}, even though we have good reason to believe that the
                   3607: text interpreter would have no problem looking that word up and
                   3608: executing it a second time.
1.21      crook    3609: 
                   3610: 
1.29      crook    3611: @comment ----------------------------------------------
                   3612: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   3613: @section Stacks, postfix notation and parameter passing
                   3614: @cindex text interpreter
                   3615: @cindex outer interpreter
1.21      crook    3616: 
1.29      crook    3617: In procedural programming languages (like C and Pascal), the
                   3618: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   3619: functions or procedures are called with @dfn{explicit parameters}. For
                   3620: example, in C we might write:
1.21      crook    3621: 
1.23      crook    3622: @example
1.29      crook    3623: total = total + new_volume(length,height,depth);
1.23      crook    3624: @end example
1.21      crook    3625: 
1.23      crook    3626: @noindent
1.29      crook    3627: where new_volume is a function-call to another piece of code, and total,
                   3628: length, height and depth are all variables. length, height and depth are
                   3629: parameters to the function-call.
1.21      crook    3630: 
1.29      crook    3631: In Forth, the equivalent of the function or procedure is the
                   3632: @dfn{definition} and parameters are implicitly passed between
                   3633: definitions using a shared stack that is visible to the
                   3634: programmer. Although Forth does support variables, the existence of the
                   3635: stack means that they are used far less often than in most other
                   3636: programming languages. When the text interpreter encounters a number, it
                   3637: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    3638: actual number is implementation-dependent ...) and the particular stack
1.29      crook    3639: used for any operation is implied unambiguously by the operation being
                   3640: performed. The stack used for all integer operations is called the @dfn{data
                   3641: stack} and, since this is the stack used most commonly, references to
                   3642: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    3643: 
1.29      crook    3644: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    3645: 
1.23      crook    3646: @example
1.30      anton    3647: @kbd{1 2 3@key{RET}}  ok
1.23      crook    3648: @end example
1.21      crook    3649: 
1.29      crook    3650: Then this instructs the text interpreter to placed three numbers on the
                   3651: (data) stack. An analogy for the behaviour of the stack is to take a
                   3652: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   3653: the table. The 3 was the last card onto the pile (``last-in'') and if
                   3654: you take a card off the pile then, unless you're prepared to fiddle a
                   3655: bit, the card that you take off will be the 3 (``first-out''). The
                   3656: number that will be first-out of the stack is called the @dfn{top of
                   3657: stack}, which
                   3658: @cindex TOS definition
                   3659: is often abbreviated to @dfn{TOS}.
1.21      crook    3660: 
1.29      crook    3661: To understand how parameters are passed in Forth, consider the
                   3662: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   3663: be surprised to learn that this definition performs addition. More
                   3664: precisely, it adds two number together and produces a result. Where does
                   3665: it get the two numbers from? It takes the top two numbers off the
                   3666: stack. Where does it place the result? On the stack. You can act-out the
                   3667: behaviour of @code{+} with your playing cards like this:
1.21      crook    3668: 
                   3669: @itemize @bullet
                   3670: @item
1.29      crook    3671: Pick up two cards from the stack on the table
1.21      crook    3672: @item
1.29      crook    3673: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   3674: numbers''
1.21      crook    3675: @item
1.29      crook    3676: Decide that the answer is 5
1.21      crook    3677: @item
1.29      crook    3678: Shuffle the two cards back into the pack and find a 5
1.21      crook    3679: @item
1.29      crook    3680: Put a 5 on the remaining ace that's on the table.
1.21      crook    3681: @end itemize
                   3682: 
1.29      crook    3683: If you don't have a pack of cards handy but you do have Forth running,
                   3684: you can use the definition @code{.s} to show the current state of the stack,
                   3685: without affecting the stack. Type:
1.21      crook    3686: 
                   3687: @example
1.124     anton    3688: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30      anton    3689: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    3690: @end example
                   3691: 
1.124     anton    3692: The text interpreter looks up the word @code{clearstacks} and executes
                   3693: it; it tidies up the stacks and removes any entries that may have been
1.29      crook    3694: left on it by earlier examples. The text interpreter pushes each of the
                   3695: three numbers in turn onto the stack. Finally, the text interpreter
                   3696: looks up the word @code{.s} and executes it. The effect of executing
                   3697: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   3698: followed by a list of all the items on the stack; the item on the far
                   3699: right-hand side is the TOS.
1.21      crook    3700: 
1.29      crook    3701: You can now type:
1.21      crook    3702: 
1.29      crook    3703: @example
1.30      anton    3704: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    3705: @end example
1.21      crook    3706: 
1.29      crook    3707: @noindent
                   3708: which is correct; there are now 2 items on the stack and the result of
                   3709: the addition is 5.
1.23      crook    3710: 
1.29      crook    3711: If you're playing with cards, try doing a second addition: pick up the
                   3712: two cards, work out that their sum is 6, shuffle them into the pack,
                   3713: look for a 6 and place that on the table. You now have just one item on
                   3714: the stack. What happens if you try to do a third addition? Pick up the
                   3715: first card, pick up the second card -- ah! There is no second card. This
                   3716: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95      anton    3717: do the same thing with Forth it often reports an error (probably a Stack
1.29      crook    3718: Underflow or an Invalid Memory Address error).
1.23      crook    3719: 
1.29      crook    3720: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   3721: which simply accepts that there is a finite amount of storage space
                   3722: reserved for the stack. To stretch the playing card analogy, if you had
                   3723: enough packs of cards and you piled the cards up on the table, you would
                   3724: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   3725: allows you to set the maximum size of the stacks. In general, the only
                   3726: time that you will get a stack overflow is because a definition has a
                   3727: bug in it and is generating data on the stack uncontrollably.
1.23      crook    3728: 
1.29      crook    3729: There's one final use for the playing card analogy. If you model your
                   3730: stack using a pack of playing cards, the maximum number of items on
                   3731: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   3732: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   3733: possible numbers are positive integer numbers 1 through 13; you can't
                   3734: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   3735: think about some of the cards, you can accommodate different
                   3736: numbers. For example, you could think of the Jack as representing 0,
                   3737: the Queen as representing -1 and the King as representing -2. Your
1.45      crook    3738: @i{range} remains unchanged (you can still only represent a total of 13
1.29      crook    3739: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    3740: 
1.29      crook    3741: In that analogy, the limit was the amount of information that a single
                   3742: stack entry could hold, and Forth has a similar limit. In Forth, the
                   3743: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   3744: implementation dependent and affects the maximum value that a stack
                   3745: entry can hold. A Standard Forth provides a cell size of at least
                   3746: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    3747: 
1.29      crook    3748: Forth does not do any type checking for you, so you are free to
                   3749: manipulate and combine stack items in any way you wish. A convenient way
                   3750: of treating stack items is as 2's complement signed integers, and that
                   3751: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    3752: 
1.29      crook    3753: @example
1.30      anton    3754: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    3755: @end example
1.21      crook    3756: 
1.29      crook    3757: If you use numbers and definitions like @code{+} in order to turn Forth
                   3758: into a great big pocket calculator, you will realise that it's rather
                   3759: different from a normal calculator. Rather than typing 2 + 3 = you had
                   3760: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   3761: result). The terminology used to describe this difference is to say that
                   3762: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   3763: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   3764: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    3765: 
1.29      crook    3766: Whilst postfix notation might look confusing to begin with, it has
                   3767: several important advantages:
1.21      crook    3768: 
1.23      crook    3769: @itemize @bullet
                   3770: @item
1.29      crook    3771: it is unambiguous
1.23      crook    3772: @item
1.29      crook    3773: it is more concise
1.23      crook    3774: @item
1.29      crook    3775: it fits naturally with a stack-based system
1.23      crook    3776: @end itemize
1.21      crook    3777: 
1.29      crook    3778: To examine these claims in more detail, consider these sums:
1.21      crook    3779: 
1.29      crook    3780: @example
                   3781: 6 + 5 * 4 =
                   3782: 4 * 5 + 6 =
                   3783: @end example
1.21      crook    3784: 
1.29      crook    3785: If you're just learning maths or your maths is very rusty, you will
                   3786: probably come up with the answer 44 for the first and 26 for the
                   3787: second. If you are a bit of a whizz at maths you will remember the
                   3788: @i{convention} that multiplication takes precendence over addition, and
                   3789: you'd come up with the answer 26 both times. To explain the answer 26
                   3790: to someone who got the answer 44, you'd probably rewrite the first sum
                   3791: like this:
1.21      crook    3792: 
1.29      crook    3793: @example
                   3794: 6 + (5 * 4) =
                   3795: @end example
1.21      crook    3796: 
1.29      crook    3797: If what you really wanted was to perform the addition before the
                   3798: multiplication, you would have to use parentheses to force it.
1.21      crook    3799: 
1.29      crook    3800: If you did the first two sums on a pocket calculator you would probably
                   3801: get the right answers, unless you were very cautious and entered them using
                   3802: these keystroke sequences:
1.21      crook    3803: 
1.29      crook    3804: 6 + 5 = * 4 =
                   3805: 4 * 5 = + 6 =
1.21      crook    3806: 
1.29      crook    3807: Postfix notation is unambiguous because the order that the operators
                   3808: are applied is always explicit; that also means that parentheses are
                   3809: never required. The operators are @i{active} (the act of quoting the
                   3810: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    3811: 
1.29      crook    3812: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   3813: equivalent ways:
1.26      crook    3814: 
                   3815: @example
1.29      crook    3816: 6 5 4 * +      or:
                   3817: 5 4 * 6 +
1.26      crook    3818: @end example
1.23      crook    3819: 
1.29      crook    3820: An important thing that you should notice about this notation is that
                   3821: the @i{order} of the numbers does not change; if you want to subtract
                   3822: 2 from 10 you type @code{10 2 -}.
1.1       anton    3823: 
1.29      crook    3824: The reason that Forth uses postfix notation is very simple to explain: it
                   3825: makes the implementation extremely simple, and it follows naturally from
                   3826: using the stack as a mechanism for passing parameters. Another way of
                   3827: thinking about this is to realise that all Forth definitions are
                   3828: @i{active}; they execute as they are encountered by the text
                   3829: interpreter. The result of this is that the syntax of Forth is trivially
                   3830: simple.
1.1       anton    3831: 
                   3832: 
                   3833: 
1.29      crook    3834: @comment ----------------------------------------------
                   3835: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   3836: @section Your first Forth definition
                   3837: @cindex first definition
1.1       anton    3838: 
1.29      crook    3839: Until now, the examples we've seen have been trivial; we've just been
                   3840: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   3841: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   3842: again@footnote{That's not quite true. If you press the up-arrow key on
                   3843: your keyboard you should be able to scroll back to any earlier command,
                   3844: edit it and re-enter it.} In this section we'll see how to add new
                   3845: words to Forth's vocabulary.
1.1       anton    3846: 
1.29      crook    3847: The easiest way to create a new word is to use a @dfn{colon
                   3848: definition}. We'll define a few and try them out before worrying too
                   3849: much about how they work. Try typing in these examples; be careful to
                   3850: copy the spaces accurately:
1.1       anton    3851: 
1.29      crook    3852: @example
                   3853: : add-two 2 + . ;
                   3854: : greet ." Hello and welcome" ;
                   3855: : demo 5 add-two ;
                   3856: @end example
1.1       anton    3857: 
1.29      crook    3858: @noindent
                   3859: Now try them out:
1.1       anton    3860: 
1.29      crook    3861: @example
1.30      anton    3862: @kbd{greet@key{RET}} Hello and welcome  ok
                   3863: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   3864: @kbd{4 add-two@key{RET}} 6  ok
                   3865: @kbd{demo@key{RET}} 7  ok
                   3866: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    3867: @end example
1.1       anton    3868: 
1.29      crook    3869: The first new thing that we've introduced here is the pair of words
                   3870: @code{:} and @code{;}. These are used to start and terminate a new
                   3871: definition, respectively. The first word after the @code{:} is the name
                   3872: for the new definition.
1.1       anton    3873: 
1.29      crook    3874: As you can see from the examples, a definition is built up of words that
                   3875: have already been defined; Forth makes no distinction between
                   3876: definitions that existed when you started the system up, and those that
                   3877: you define yourself.
1.1       anton    3878: 
1.29      crook    3879: The examples also introduce the words @code{.} (dot), @code{."}
                   3880: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   3881: the stack and displays it. It's like @code{.s} except that it only
                   3882: displays the top item of the stack and it is destructive; after it has
                   3883: executed, the number is no longer on the stack. There is always one
                   3884: space printed after the number, and no spaces before it. Dot-quote
                   3885: defines a string (a sequence of characters) that will be printed when
                   3886: the word is executed. The string can contain any printable characters
                   3887: except @code{"}. A @code{"} has a special function; it is not a Forth
                   3888: word but it acts as a delimiter (the way that delimiters work is
                   3889: described in the next section). Finally, @code{dup} duplicates the value
                   3890: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    3891: 
1.29      crook    3892: We already know that the text interpreter searches through the
                   3893: dictionary to locate names. If you've followed the examples earlier, you
                   3894: will already have a definition called @code{add-two}. Lets try modifying
                   3895: it by typing in a new definition:
1.1       anton    3896: 
1.29      crook    3897: @example
1.30      anton    3898: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    3899: @end example
1.5       anton    3900: 
1.29      crook    3901: Forth recognised that we were defining a word that already exists, and
                   3902: printed a message to warn us of that fact. Let's try out the new
                   3903: definition:
1.5       anton    3904: 
1.29      crook    3905: @example
1.30      anton    3906: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    3907: @end example
1.1       anton    3908: 
1.29      crook    3909: @noindent
                   3910: All that we've actually done here, though, is to create a new
                   3911: definition, with a particular name. The fact that there was already a
                   3912: definition with the same name did not make any difference to the way
                   3913: that the new definition was created (except that Forth printed a warning
                   3914: message). The old definition of add-two still exists (try @code{demo}
                   3915: again to see that this is true). Any new definition will use the new
                   3916: definition of @code{add-two}, but old definitions continue to use the
                   3917: version that already existed at the time that they were @code{compiled}.
1.1       anton    3918: 
1.29      crook    3919: Before you go on to the next section, try defining and redefining some
                   3920: words of your own.
1.1       anton    3921: 
1.29      crook    3922: @comment ----------------------------------------------
                   3923: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   3924: @section How does that work?
                   3925: @cindex parsing words
1.1       anton    3926: 
1.30      anton    3927: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   3928: 
                   3929: @c Is it a good idea to talk about the interpretation semantics of a
                   3930: @c number? We don't have an xt to go along with it. - anton
                   3931: 
                   3932: @c Now that I have eliminated execution semantics, I wonder if it would not
                   3933: @c be better to keep them (or add run-time semantics), to make it easier to
                   3934: @c explain what compilation semantics usually does. - anton
                   3935: 
1.44      crook    3936: @c nac-> I removed the term ``default compilation sematics'' from the
                   3937: @c introductory chapter. Removing ``execution semantics'' was making
                   3938: @c everything simpler to explain, then I think the use of this term made
                   3939: @c everything more complex again. I replaced it with ``default
                   3940: @c semantics'' (which is used elsewhere in the manual) by which I mean
                   3941: @c ``a definition that has neither the immediate nor the compile-only
1.83      anton    3942: @c flag set''.
                   3943: 
                   3944: @c anton: I have eliminated default semantics (except in one place where it
                   3945: @c means "default interpretation and compilation semantics"), because it
                   3946: @c makes no sense in the presence of combined words.  I reverted to
                   3947: @c "execution semantics" where necessary.
                   3948: 
                   3949: @c nac-> I reworded big chunks of the ``how does that work''
1.44      crook    3950: @c section (and, unusually for me, I think I even made it shorter!).  See
                   3951: @c what you think -- I know I have not addressed your primary concern
                   3952: @c that it is too heavy-going for an introduction. From what I understood
                   3953: @c of your course notes it looks as though they might be a good framework. 
                   3954: @c Things that I've tried to capture here are some things that came as a
                   3955: @c great revelation here when I first understood them. Also, I like the
                   3956: @c fact that a very simple code example shows up almost all of the issues
                   3957: @c that you need to understand to see how Forth works. That's unique and
                   3958: @c worthwhile to emphasise.
                   3959: 
1.83      anton    3960: @c anton: I think it's a good idea to present the details, especially those
                   3961: @c that you found to be a revelation, and probably the tutorial tries to be
                   3962: @c too superficial and does not get some of the things across that make
                   3963: @c Forth special.  I do believe that most of the time these things should
                   3964: @c be discussed at the end of a section or in separate sections instead of
                   3965: @c in the middle of a section (e.g., the stuff you added in "User-defined
                   3966: @c defining words" leads in a completely different direction from the rest
                   3967: @c of the section).
                   3968: 
1.29      crook    3969: Now we're going to take another look at the definition of @code{add-two}
                   3970: from the previous section. From our knowledge of the way that the text
                   3971: interpreter works, we would have expected this result when we tried to
                   3972: define @code{add-two}:
1.21      crook    3973: 
1.29      crook    3974: @example
1.44      crook    3975: @kbd{: add-two 2 + . ;@key{RET}}
1.134     anton    3976: *the terminal*:4: Undefined word
                   3977: : >>>add-two<<< 2 + . ;
1.29      crook    3978: @end example
1.28      crook    3979: 
1.29      crook    3980: The reason that this didn't happen is bound up in the way that @code{:}
                   3981: works. The word @code{:} does two special things. The first special
                   3982: thing that it does prevents the text interpreter from ever seeing the
                   3983: characters @code{add-two}. The text interpreter uses a variable called
                   3984: @cindex modifying >IN
1.44      crook    3985: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29      crook    3986: input line. When it encounters the word @code{:} it behaves in exactly
                   3987: the same way as it does for any other word; it looks it up in the name
                   3988: dictionary, finds its xt and executes it. When @code{:} executes, it
                   3989: looks at the input buffer, finds the word @code{add-two} and advances the
                   3990: value of @code{>IN} to point past it. It then does some other stuff
                   3991: associated with creating the new definition (including creating an entry
                   3992: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   3993: completes, control returns to the text interpreter, which is oblivious
                   3994: to the fact that it has been tricked into ignoring part of the input
                   3995: line.
1.21      crook    3996: 
1.29      crook    3997: @cindex parsing words
                   3998: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   3999: prevent the text interpreter from acting on the whole of the input line
                   4000: -- are called @dfn{parsing words}.
1.21      crook    4001: 
1.29      crook    4002: @cindex @code{state} - effect on the text interpreter
                   4003: @cindex text interpreter - effect of state
                   4004: The second special thing that @code{:} does is change the value of a
                   4005: variable called @code{state}, which affects the way that the text
                   4006: interpreter behaves. When Gforth starts up, @code{state} has the value
                   4007: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   4008: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44      crook    4009: the text interpreter is said to be @dfn{compiling}.
                   4010: 
                   4011: In this example, the text interpreter is compiling when it processes the
                   4012: string ``@code{2 + . ;}''. It still breaks the string down into
                   4013: character sequences in the same way. However, instead of pushing the
                   4014: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
                   4015: into the definition of @code{add-two} that will make the number @code{2} get
                   4016: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
                   4017: the behaviours of @code{+} and @code{.} are also compiled into the
                   4018: definition.
                   4019: 
                   4020: One category of words don't get compiled. These so-called @dfn{immediate
                   4021: words} get executed (performed @i{now}) regardless of whether the text
                   4022: interpreter is interpreting or compiling. The word @code{;} is an
                   4023: immediate word. Rather than being compiled into the definition, it
                   4024: executes. Its effect is to terminate the current definition, which
                   4025: includes changing the value of @code{state} back to 0.
                   4026: 
                   4027: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
                   4028: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
                   4029: definition.
1.28      crook    4030: 
1.30      anton    4031: In Forth, every word or number can be described in terms of two
1.29      crook    4032: properties:
1.28      crook    4033: 
                   4034: @itemize @bullet
                   4035: @item
1.29      crook    4036: @cindex interpretation semantics
1.44      crook    4037: Its @dfn{interpretation semantics} describe how it will behave when the
                   4038: text interpreter encounters it in @dfn{interpret} state. The
                   4039: interpretation semantics of a word are represented by an @dfn{execution
                   4040: token}.
1.28      crook    4041: @item
1.29      crook    4042: @cindex compilation semantics
1.44      crook    4043: Its @dfn{compilation semantics} describe how it will behave when the
                   4044: text interpreter encounters it in @dfn{compile} state. The compilation
                   4045: semantics of a word are represented in an implementation-dependent way;
                   4046: Gforth uses a @dfn{compilation token}.
1.29      crook    4047: @end itemize
                   4048: 
                   4049: @noindent
                   4050: Numbers are always treated in a fixed way:
                   4051: 
                   4052: @itemize @bullet
1.28      crook    4053: @item
1.44      crook    4054: When the number is @dfn{interpreted}, its behaviour is to push the
                   4055: number onto the stack.
1.28      crook    4056: @item
1.30      anton    4057: When the number is @dfn{compiled}, a piece of code is appended to the
                   4058: current definition that pushes the number when it runs. (In other words,
                   4059: the compilation semantics of a number are to postpone its interpretation
                   4060: semantics until the run-time of the definition that it is being compiled
                   4061: into.)
1.29      crook    4062: @end itemize
                   4063: 
1.44      crook    4064: Words don't behave in such a regular way, but most have @i{default
                   4065: semantics} which means that they behave like this:
1.29      crook    4066: 
                   4067: @itemize @bullet
1.28      crook    4068: @item
1.30      anton    4069: The @dfn{interpretation semantics} of the word are to do something useful.
                   4070: @item
1.29      crook    4071: The @dfn{compilation semantics} of the word are to append its
1.30      anton    4072: @dfn{interpretation semantics} to the current definition (so that its
                   4073: run-time behaviour is to do something useful).
1.28      crook    4074: @end itemize
                   4075: 
1.30      anton    4076: @cindex immediate words
1.44      crook    4077: The actual behaviour of any particular word can be controlled by using
                   4078: the words @code{immediate} and @code{compile-only} when the word is
                   4079: defined. These words set flags in the name dictionary entry of the most
                   4080: recently defined word, and these flags are retrieved by the text
                   4081: interpreter when it finds the word in the name dictionary.
                   4082: 
                   4083: A word that is marked as @dfn{immediate} has compilation semantics that
                   4084: are identical to its interpretation semantics. In other words, it
                   4085: behaves like this:
1.29      crook    4086: 
                   4087: @itemize @bullet
                   4088: @item
1.30      anton    4089: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    4090: @item
1.30      anton    4091: The @dfn{compilation semantics} of the word are to do something useful
                   4092: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    4093: @end itemize
1.28      crook    4094: 
1.44      crook    4095: Marking a word as @dfn{compile-only} prohibits the text interpreter from
                   4096: performing the interpretation semantics of the word directly; an attempt
                   4097: to do so will generate an error. It is never necessary to use
                   4098: @code{compile-only} (and it is not even part of ANS Forth, though it is
                   4099: provided by many implementations) but it is good etiquette to apply it
                   4100: to a word that will not behave correctly (and might have unexpected
                   4101: side-effects) in interpret state. For example, it is only legal to use
                   4102: the conditional word @code{IF} within a definition. If you forget this
                   4103: and try to use it elsewhere, the fact that (in Gforth) it is marked as
                   4104: @code{compile-only} allows the text interpreter to generate a helpful
                   4105: error message rather than subjecting you to the consequences of your
                   4106: folly.
                   4107: 
1.29      crook    4108: This example shows the difference between an immediate and a
                   4109: non-immediate word:
1.28      crook    4110: 
1.29      crook    4111: @example
                   4112: : show-state state @@ . ;
                   4113: : show-state-now show-state ; immediate
                   4114: : word1 show-state ;
                   4115: : word2 show-state-now ;
1.28      crook    4116: @end example
1.23      crook    4117: 
1.29      crook    4118: The word @code{immediate} after the definition of @code{show-state-now}
                   4119: makes that word an immediate word. These definitions introduce a new
                   4120: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   4121: variable, and leaves it on the stack. Therefore, the behaviour of
                   4122: @code{show-state} is to print a number that represents the current value
                   4123: of @code{state}.
1.28      crook    4124: 
1.29      crook    4125: When you execute @code{word1}, it prints the number 0, indicating that
                   4126: the system is interpreting. When the text interpreter compiled the
                   4127: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    4128: compilation semantics are to append its interpretation semantics to the
1.29      crook    4129: current definition. When you execute @code{word1}, it performs the
1.30      anton    4130: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    4131: (and therefore @code{show-state}) are executed, the system is
                   4132: interpreting.
1.28      crook    4133: 
1.30      anton    4134: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    4135: you should have seen the number -1 printed, followed by ``@code{
                   4136: ok}''. When the text interpreter compiled the definition of
                   4137: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    4138: whose compilation semantics are therefore to perform its interpretation
1.29      crook    4139: semantics. It is executed straight away (even before the text
                   4140: interpreter has moved on to process another group of characters; the
                   4141: @code{;} in this example). The effect of executing it are to display the
                   4142: value of @code{state} @i{at the time that the definition of}
                   4143: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   4144: system is compiling at this time. If you execute @code{word2} it does
                   4145: nothing at all.
1.28      crook    4146: 
1.29      crook    4147: @cindex @code{."}, how it works
                   4148: Before leaving the subject of immediate words, consider the behaviour of
                   4149: @code{."} in the definition of @code{greet}, in the previous
                   4150: section. This word is both a parsing word and an immediate word. Notice
                   4151: that there is a space between @code{."} and the start of the text
                   4152: @code{Hello and welcome}, but that there is no space between the last
                   4153: letter of @code{welcome} and the @code{"} character. The reason for this
                   4154: is that @code{."} is a Forth word; it must have a space after it so that
                   4155: the text interpreter can identify it. The @code{"} is not a Forth word;
                   4156: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   4157: is displayed, there is neither a space before the @code{H} nor after the
                   4158: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   4159: that @code{greet} is defined. When it executes, its behaviour is to
                   4160: search forward in the input line looking for the delimiter. When it
                   4161: finds the delimiter, it updates @code{>IN} to point past the
                   4162: delimiter. It also compiles some magic code into the definition of
                   4163: @code{greet}; the xt of a run-time routine that prints a text string. It
                   4164: compiles the string @code{Hello and welcome} into memory so that it is
                   4165: available to be printed later. When the text interpreter gains control,
                   4166: the next word it finds in the input stream is @code{;} and so it
                   4167: terminates the definition of @code{greet}.
1.28      crook    4168: 
                   4169: 
                   4170: @comment ----------------------------------------------
1.29      crook    4171: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   4172: @section Forth is written in Forth
                   4173: @cindex structure of Forth programs
                   4174: 
                   4175: When you start up a Forth compiler, a large number of definitions
                   4176: already exist. In Forth, you develop a new application using bottom-up
                   4177: programming techniques to create new definitions that are defined in
                   4178: terms of existing definitions. As you create each definition you can
                   4179: test and debug it interactively.
                   4180: 
                   4181: If you have tried out the examples in this section, you will probably
                   4182: have typed them in by hand; when you leave Gforth, your definitions will
                   4183: be lost. You can avoid this by using a text editor to enter Forth source
                   4184: code into a file, and then loading code from the file using
1.49      anton    4185: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29      crook    4186: processed by the text interpreter, just as though you had typed it in by
                   4187: hand@footnote{Actually, there are some subtle differences -- see
                   4188: @ref{The Text Interpreter}.}.
                   4189: 
                   4190: Gforth also supports the traditional Forth alternative to using text
1.49      anton    4191: files for program entry (@pxref{Blocks}).
1.28      crook    4192: 
1.29      crook    4193: In common with many, if not most, Forth compilers, most of Gforth is
                   4194: actually written in Forth. All of the @file{.fs} files in the
                   4195: installation directory@footnote{For example,
1.30      anton    4196: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    4197: study to see examples of Forth programming.
1.28      crook    4198: 
1.29      crook    4199: Gforth maintains a history file that records every line that you type to
                   4200: the text interpreter. This file is preserved between sessions, and is
                   4201: used to provide a command-line recall facility. If you enter long
                   4202: definitions by hand, you can use a text editor to paste them out of the
                   4203: history file into a Forth source file for reuse at a later time
1.49      anton    4204: (for more information @pxref{Command-line editing}).
1.28      crook    4205: 
                   4206: 
                   4207: @comment ----------------------------------------------
1.29      crook    4208: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   4209: @section Review - elements of a Forth system
                   4210: @cindex elements of a Forth system
1.28      crook    4211: 
1.29      crook    4212: To summarise this chapter:
1.28      crook    4213: 
                   4214: @itemize @bullet
                   4215: @item
1.29      crook    4216: Forth programs use @dfn{factoring} to break a problem down into small
                   4217: fragments called @dfn{words} or @dfn{definitions}.
                   4218: @item
                   4219: Forth program development is an interactive process.
                   4220: @item
                   4221: The main command loop that accepts input, and controls both
                   4222: interpretation and compilation, is called the @dfn{text interpreter}
                   4223: (also known as the @dfn{outer interpreter}).
                   4224: @item
                   4225: Forth has a very simple syntax, consisting of words and numbers
                   4226: separated by spaces or carriage-return characters. Any additional syntax
                   4227: is imposed by @dfn{parsing words}.
                   4228: @item
                   4229: Forth uses a stack to pass parameters between words. As a result, it
                   4230: uses postfix notation.
                   4231: @item
                   4232: To use a word that has previously been defined, the text interpreter
                   4233: searches for the word in the @dfn{name dictionary}.
                   4234: @item
1.30      anton    4235: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    4236: @item
1.29      crook    4237: The text interpreter uses the value of @code{state} to select between
                   4238: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   4239: semantics} of a word that it encounters.
1.28      crook    4240: @item
1.30      anton    4241: The relationship between the @dfn{interpretation semantics} and
                   4242: @dfn{compilation semantics} for a word
1.29      crook    4243: depend upon the way in which the word was defined (for example, whether
                   4244: it is an @dfn{immediate} word).
1.28      crook    4245: @item
1.29      crook    4246: Forth definitions can be implemented in Forth (called @dfn{high-level
                   4247: definitions}) or in some other way (usually a lower-level language and
                   4248: as a result often called @dfn{low-level definitions}, @dfn{code
                   4249: definitions} or @dfn{primitives}).
1.28      crook    4250: @item
1.29      crook    4251: Many Forth systems are implemented mainly in Forth.
1.28      crook    4252: @end itemize
                   4253: 
                   4254: 
1.29      crook    4255: @comment ----------------------------------------------
1.48      anton    4256: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29      crook    4257: @section Where To Go Next
                   4258: @cindex where to go next
1.28      crook    4259: 
1.29      crook    4260: Amazing as it may seem, if you have read (and understood) this far, you
                   4261: know almost all the fundamentals about the inner workings of a Forth
                   4262: system. You certainly know enough to be able to read and understand the
                   4263: rest of this manual and the ANS Forth document, to learn more about the
                   4264: facilities that Forth in general and Gforth in particular provide. Even
                   4265: scarier, you know almost enough to implement your own Forth system.
1.30      anton    4266: However, that's not a good idea just yet... better to try writing some
1.29      crook    4267: programs in Gforth.
1.28      crook    4268: 
1.29      crook    4269: Forth has such a rich vocabulary that it can be hard to know where to
                   4270: start in learning it. This section suggests a few sets of words that are
                   4271: enough to write small but useful programs. Use the word index in this
                   4272: document to learn more about each word, then try it out and try to write
                   4273: small definitions using it. Start by experimenting with these words:
1.28      crook    4274: 
                   4275: @itemize @bullet
                   4276: @item
1.29      crook    4277: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   4278: @item
                   4279: Comparison: @code{MIN MAX =}
                   4280: @item
                   4281: Logic: @code{AND OR XOR NOT}
                   4282: @item
                   4283: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    4284: @item
1.29      crook    4285: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    4286: @item
1.29      crook    4287: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    4288: @item
1.29      crook    4289: Defining words: @code{: ; CREATE}
1.28      crook    4290: @item
1.29      crook    4291: Memory allocation words: @code{ALLOT ,}
1.28      crook    4292: @item
1.29      crook    4293: Tools: @code{SEE WORDS .S MARKER}
                   4294: @end itemize
                   4295: 
                   4296: When you have mastered those, go on to:
                   4297: 
                   4298: @itemize @bullet
1.28      crook    4299: @item
1.29      crook    4300: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    4301: @item
1.29      crook    4302: Memory access: @code{@@ !}
1.28      crook    4303: @end itemize
1.23      crook    4304: 
1.29      crook    4305: When you have mastered these, there's nothing for it but to read through
                   4306: the whole of this manual and find out what you've missed.
                   4307: 
                   4308: @comment ----------------------------------------------
1.48      anton    4309: @node Exercises,  , Where to go next, Introduction
1.29      crook    4310: @section Exercises
                   4311: @cindex exercises
                   4312: 
                   4313: TODO: provide a set of programming excercises linked into the stuff done
                   4314: already and into other sections of the manual. Provide solutions to all
                   4315: the exercises in a .fs file in the distribution.
                   4316: 
                   4317: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   4318: 
                   4319: @c excercises:
                   4320: @c 1. take inches and convert to feet and inches.
                   4321: @c 2. take temperature and convert from fahrenheight to celcius;
                   4322: @c    may need to care about symmetric vs floored??
                   4323: @c 3. take input line and do character substitution
                   4324: @c    to encipher or decipher
                   4325: @c 4. as above but work on a file for in and out
                   4326: @c 5. take input line and convert to pig-latin 
                   4327: @c
                   4328: @c thing of sets of things to exercise then come up with
                   4329: @c problems that need those things.
                   4330: 
                   4331: 
1.26      crook    4332: @c ******************************************************************
1.29      crook    4333: @node Words, Error messages, Introduction, Top
1.1       anton    4334: @chapter Forth Words
1.26      crook    4335: @cindex words
1.1       anton    4336: 
                   4337: @menu
                   4338: * Notation::                    
1.65      anton    4339: * Case insensitivity::          
                   4340: * Comments::                    
                   4341: * Boolean Flags::               
1.1       anton    4342: * Arithmetic::                  
                   4343: * Stack Manipulation::          
1.5       anton    4344: * Memory::                      
1.1       anton    4345: * Control Structures::          
                   4346: * Defining Words::              
1.65      anton    4347: * Interpretation and Compilation Semantics::  
1.47      crook    4348: * Tokens for Words::            
1.81      anton    4349: * Compiling words::             
1.65      anton    4350: * The Text Interpreter::        
1.111     anton    4351: * The Input Stream::            
1.65      anton    4352: * Word Lists::                  
                   4353: * Environmental Queries::       
1.12      anton    4354: * Files::                       
                   4355: * Blocks::                      
                   4356: * Other I/O::                   
1.121     anton    4357: * OS command line arguments::   
1.78      anton    4358: * Locals::                      
                   4359: * Structures::                  
                   4360: * Object-oriented Forth::       
1.12      anton    4361: * Programming Tools::           
1.150     anton    4362: * C Interface::                 
1.12      anton    4363: * Assembler and Code Words::    
                   4364: * Threading Words::             
1.65      anton    4365: * Passing Commands to the OS::  
                   4366: * Keeping track of Time::       
                   4367: * Miscellaneous Words::         
1.1       anton    4368: @end menu
                   4369: 
1.65      anton    4370: @node Notation, Case insensitivity, Words, Words
1.1       anton    4371: @section Notation
                   4372: @cindex notation of glossary entries
                   4373: @cindex format of glossary entries
                   4374: @cindex glossary notation format
                   4375: @cindex word glossary entry format
                   4376: 
                   4377: The Forth words are described in this section in the glossary notation
1.67      anton    4378: that has become a de-facto standard for Forth texts:
1.1       anton    4379: 
                   4380: @format
1.29      crook    4381: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    4382: @end format
1.29      crook    4383: @i{Description}
1.1       anton    4384: 
                   4385: @table @var
                   4386: @item word
1.28      crook    4387: The name of the word.
1.1       anton    4388: 
                   4389: @item Stack effect
                   4390: @cindex stack effect
1.29      crook    4391: The stack effect is written in the notation @code{@i{before} --
                   4392: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    4393: stack entries before and after the execution of the word. The rest of
                   4394: the stack is not touched by the word. The top of stack is rightmost,
                   4395: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   4396: uses a separate floating point stack, but a unified stack
1.29      crook    4397: notation. Also, return stack effects are not shown in @i{stack
                   4398: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    4399: the type and/or the function of the item. See below for a discussion of
                   4400: the types.
                   4401: 
                   4402: All words have two stack effects: A compile-time stack effect and a
                   4403: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    4404: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    4405: this standard behaviour, or the word does other unusual things at
                   4406: compile time, both stack effects are shown; otherwise only the run-time
                   4407: stack effect is shown.
                   4408: 
                   4409: @cindex pronounciation of words
                   4410: @item pronunciation
                   4411: How the word is pronounced.
                   4412: 
                   4413: @cindex wordset
1.67      anton    4414: @cindex environment wordset
1.1       anton    4415: @item wordset
1.21      crook    4416: The ANS Forth standard is divided into several word sets. A standard
                   4417: system need not support all of them. Therefore, in theory, the fewer
                   4418: word sets your program uses the more portable it will be. However, we
                   4419: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    4420: all word sets. Words that are not defined in ANS Forth have
1.21      crook    4421: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    4422: describes words that will work in future releases of Gforth;
                   4423: @code{gforth-internal} words are more volatile. Environmental query
                   4424: strings are also displayed like words; you can recognize them by the
1.21      crook    4425: @code{environment} in the word set field.
1.1       anton    4426: 
                   4427: @item Description
                   4428: A description of the behaviour of the word.
                   4429: @end table
                   4430: 
                   4431: @cindex types of stack items
                   4432: @cindex stack item types
                   4433: The type of a stack item is specified by the character(s) the name
                   4434: starts with:
                   4435: 
                   4436: @table @code
                   4437: @item f
                   4438: @cindex @code{f}, stack item type
                   4439: Boolean flags, i.e. @code{false} or @code{true}.
                   4440: @item c
                   4441: @cindex @code{c}, stack item type
                   4442: Char
                   4443: @item w
                   4444: @cindex @code{w}, stack item type
                   4445: Cell, can contain an integer or an address
                   4446: @item n
                   4447: @cindex @code{n}, stack item type
                   4448: signed integer
                   4449: @item u
                   4450: @cindex @code{u}, stack item type
                   4451: unsigned integer
                   4452: @item d
                   4453: @cindex @code{d}, stack item type
                   4454: double sized signed integer
                   4455: @item ud
                   4456: @cindex @code{ud}, stack item type
                   4457: double sized unsigned integer
                   4458: @item r
                   4459: @cindex @code{r}, stack item type
                   4460: Float (on the FP stack)
1.21      crook    4461: @item a-
1.1       anton    4462: @cindex @code{a_}, stack item type
                   4463: Cell-aligned address
1.21      crook    4464: @item c-
1.1       anton    4465: @cindex @code{c_}, stack item type
                   4466: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    4467: @item f-
1.1       anton    4468: @cindex @code{f_}, stack item type
                   4469: Float-aligned address
1.21      crook    4470: @item df-
1.1       anton    4471: @cindex @code{df_}, stack item type
                   4472: Address aligned for IEEE double precision float
1.21      crook    4473: @item sf-
1.1       anton    4474: @cindex @code{sf_}, stack item type
                   4475: Address aligned for IEEE single precision float
                   4476: @item xt
                   4477: @cindex @code{xt}, stack item type
                   4478: Execution token, same size as Cell
                   4479: @item wid
                   4480: @cindex @code{wid}, stack item type
1.21      crook    4481: Word list ID, same size as Cell
1.68      anton    4482: @item ior, wior
                   4483: @cindex ior type description
                   4484: @cindex wior type description
                   4485: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
1.1       anton    4486: @item f83name
                   4487: @cindex @code{f83name}, stack item type
                   4488: Pointer to a name structure
                   4489: @item "
                   4490: @cindex @code{"}, stack item type
1.12      anton    4491: string in the input stream (not on the stack). The terminating character
                   4492: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    4493: quotes.
                   4494: @end table
                   4495: 
1.65      anton    4496: @comment ----------------------------------------------
                   4497: @node Case insensitivity, Comments, Notation, Words
                   4498: @section Case insensitivity
                   4499: @cindex case sensitivity
                   4500: @cindex upper and lower case
                   4501: 
                   4502: Gforth is case-insensitive; you can enter definitions and invoke
                   4503: Standard words using upper, lower or mixed case (however,
                   4504: @pxref{core-idef, Implementation-defined options, Implementation-defined
                   4505: options}).
                   4506: 
                   4507: ANS Forth only @i{requires} implementations to recognise Standard words
                   4508: when they are typed entirely in upper case. Therefore, a Standard
                   4509: program must use upper case for all Standard words. You can use whatever
                   4510: case you like for words that you define, but in a Standard program you
                   4511: have to use the words in the same case that you defined them.
                   4512: 
                   4513: Gforth supports case sensitivity through @code{table}s (case-sensitive
                   4514: wordlists, @pxref{Word Lists}).
                   4515: 
                   4516: Two people have asked how to convert Gforth to be case-sensitive; while
                   4517: we think this is a bad idea, you can change all wordlists into tables
                   4518: like this:
                   4519: 
                   4520: @example
                   4521: ' table-find forth-wordlist wordlist-map @ !
                   4522: @end example
                   4523: 
                   4524: Note that you now have to type the predefined words in the same case
                   4525: that we defined them, which are varying.  You may want to convert them
                   4526: to your favourite case before doing this operation (I won't explain how,
                   4527: because if you are even contemplating doing this, you'd better have
                   4528: enough knowledge of Forth systems to know this already).
                   4529: 
                   4530: @node Comments, Boolean Flags, Case insensitivity, Words
1.21      crook    4531: @section Comments
1.26      crook    4532: @cindex comments
1.21      crook    4533: 
1.29      crook    4534: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   4535: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    4536: 
1.44      crook    4537: 
1.23      crook    4538: doc-(
1.21      crook    4539: doc-\
1.23      crook    4540: doc-\G
1.21      crook    4541: 
1.44      crook    4542: 
1.21      crook    4543: @node Boolean Flags, Arithmetic, Comments, Words
                   4544: @section Boolean Flags
1.26      crook    4545: @cindex Boolean flags
1.21      crook    4546: 
                   4547: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   4548: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    4549: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    4550: a cell that has @i{any} bit set as @code{true}.
1.67      anton    4551: @c on and off to Memory? 
                   4552: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44      crook    4553: 
1.21      crook    4554: doc-true
                   4555: doc-false
1.29      crook    4556: doc-on
                   4557: doc-off
1.21      crook    4558: 
1.44      crook    4559: 
1.21      crook    4560: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    4561: @section Arithmetic
                   4562: @cindex arithmetic words
                   4563: 
                   4564: @cindex division with potentially negative operands
                   4565: Forth arithmetic is not checked, i.e., you will not hear about integer
                   4566: overflow on addition or multiplication, you may hear about division by
                   4567: zero if you are lucky. The operator is written after the operands, but
                   4568: the operands are still in the original order. I.e., the infix @code{2-1}
                   4569: corresponds to @code{2 1 -}. Forth offers a variety of division
                   4570: operators. If you perform division with potentially negative operands,
                   4571: you do not want to use @code{/} or @code{/mod} with its undefined
                   4572: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   4573: former, @pxref{Mixed precision}).
1.26      crook    4574: @comment TODO discuss the different division forms and the std approach
1.1       anton    4575: 
                   4576: @menu
                   4577: * Single precision::            
1.67      anton    4578: * Double precision::            Double-cell integer arithmetic
1.1       anton    4579: * Bitwise operations::          
1.67      anton    4580: * Numeric comparison::          
1.29      crook    4581: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    4582: * Floating Point::              
                   4583: @end menu
                   4584: 
1.67      anton    4585: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1       anton    4586: @subsection Single precision
                   4587: @cindex single precision arithmetic words
                   4588: 
1.67      anton    4589: @c !! cell undefined
                   4590: 
                   4591: By default, numbers in Forth are single-precision integers that are one
1.26      crook    4592: cell in size. They can be signed or unsigned, depending upon how you
1.49      anton    4593: treat them. For the rules used by the text interpreter for recognising
                   4594: single-precision integers see @ref{Number Conversion}.
1.21      crook    4595: 
1.67      anton    4596: These words are all defined for signed operands, but some of them also
                   4597: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
                   4598: @code{*}.
1.44      crook    4599: 
1.1       anton    4600: doc-+
1.21      crook    4601: doc-1+
1.128     anton    4602: doc-under+
1.1       anton    4603: doc--
1.21      crook    4604: doc-1-
1.1       anton    4605: doc-*
                   4606: doc-/
                   4607: doc-mod
                   4608: doc-/mod
                   4609: doc-negate
                   4610: doc-abs
                   4611: doc-min
                   4612: doc-max
1.27      crook    4613: doc-floored
1.1       anton    4614: 
1.44      crook    4615: 
1.67      anton    4616: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21      crook    4617: @subsection Double precision
                   4618: @cindex double precision arithmetic words
                   4619: 
1.49      anton    4620: For the rules used by the text interpreter for
                   4621: recognising double-precision integers, see @ref{Number Conversion}.
1.21      crook    4622: 
                   4623: A double precision number is represented by a cell pair, with the most
1.67      anton    4624: significant cell at the TOS. It is trivial to convert an unsigned single
                   4625: to a double: simply push a @code{0} onto the TOS. Since numbers are
                   4626: represented by Gforth using 2's complement arithmetic, converting a
                   4627: signed single to a (signed) double requires sign-extension across the
                   4628: most significant cell. This can be achieved using @code{s>d}. The moral
                   4629: of the story is that you cannot convert a number without knowing whether
                   4630: it represents an unsigned or a signed number.
1.21      crook    4631: 
1.67      anton    4632: These words are all defined for signed operands, but some of them also
                   4633: work for unsigned numbers: @code{d+}, @code{d-}.
1.44      crook    4634: 
1.21      crook    4635: doc-s>d
1.67      anton    4636: doc-d>s
1.21      crook    4637: doc-d+
                   4638: doc-d-
                   4639: doc-dnegate
                   4640: doc-dabs
                   4641: doc-dmin
                   4642: doc-dmax
                   4643: 
1.44      crook    4644: 
1.67      anton    4645: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
                   4646: @subsection Bitwise operations
                   4647: @cindex bitwise operation words
                   4648: 
                   4649: 
                   4650: doc-and
                   4651: doc-or
                   4652: doc-xor
                   4653: doc-invert
                   4654: doc-lshift
                   4655: doc-rshift
                   4656: doc-2*
                   4657: doc-d2*
                   4658: doc-2/
                   4659: doc-d2/
                   4660: 
                   4661: 
                   4662: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21      crook    4663: @subsection Numeric comparison
                   4664: @cindex numeric comparison words
                   4665: 
1.67      anton    4666: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
                   4667: d0= d0<>}) work for for both signed and unsigned numbers.
1.44      crook    4668: 
1.28      crook    4669: doc-<
                   4670: doc-<=
                   4671: doc-<>
                   4672: doc-=
                   4673: doc->
                   4674: doc->=
                   4675: 
1.21      crook    4676: doc-0<
1.23      crook    4677: doc-0<=
1.21      crook    4678: doc-0<>
                   4679: doc-0=
1.23      crook    4680: doc-0>
                   4681: doc-0>=
1.28      crook    4682: 
                   4683: doc-u<
                   4684: doc-u<=
1.44      crook    4685: @c u<> and u= exist but are the same as <> and =
1.31      anton    4686: @c doc-u<>
                   4687: @c doc-u=
1.28      crook    4688: doc-u>
                   4689: doc-u>=
                   4690: 
                   4691: doc-within
                   4692: 
                   4693: doc-d<
                   4694: doc-d<=
                   4695: doc-d<>
                   4696: doc-d=
                   4697: doc-d>
                   4698: doc-d>=
1.23      crook    4699: 
1.21      crook    4700: doc-d0<
1.23      crook    4701: doc-d0<=
                   4702: doc-d0<>
1.21      crook    4703: doc-d0=
1.23      crook    4704: doc-d0>
                   4705: doc-d0>=
                   4706: 
1.21      crook    4707: doc-du<
1.28      crook    4708: doc-du<=
1.44      crook    4709: @c du<> and du= exist but are the same as d<> and d=
1.31      anton    4710: @c doc-du<>
                   4711: @c doc-du=
1.28      crook    4712: doc-du>
                   4713: doc-du>=
1.1       anton    4714: 
1.44      crook    4715: 
1.21      crook    4716: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    4717: @subsection Mixed precision
                   4718: @cindex mixed precision arithmetic words
                   4719: 
1.44      crook    4720: 
1.1       anton    4721: doc-m+
                   4722: doc-*/
                   4723: doc-*/mod
                   4724: doc-m*
                   4725: doc-um*
                   4726: doc-m*/
                   4727: doc-um/mod
                   4728: doc-fm/mod
                   4729: doc-sm/rem
                   4730: 
1.44      crook    4731: 
1.21      crook    4732: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    4733: @subsection Floating Point
                   4734: @cindex floating point arithmetic words
                   4735: 
1.49      anton    4736: For the rules used by the text interpreter for
                   4737: recognising floating-point numbers see @ref{Number Conversion}.
1.1       anton    4738: 
1.67      anton    4739: Gforth has a separate floating point stack, but the documentation uses
                   4740: the unified notation.@footnote{It's easy to generate the separate
                   4741: notation from that by just separating the floating-point numbers out:
                   4742: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
                   4743: r3 )}.}
1.1       anton    4744: 
                   4745: @cindex floating-point arithmetic, pitfalls
                   4746: Floating point numbers have a number of unpleasant surprises for the
1.190     anton    4747: unwary (e.g., floating point addition is not associative) and even a
                   4748: few for the wary. You should not use them unless you know what you are
                   4749: doing or you don't care that the results you get are totally bogus. If
                   4750: you want to learn about the problems of floating point numbers (and
                   4751: how to avoid them), you might start with @cite{David Goldberg,
                   4752: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
                   4753: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
                   4754: Computing Surveys 23(1):5@minus{}48, March 1991}.
1.1       anton    4755: 
1.44      crook    4756: 
1.21      crook    4757: doc-d>f
                   4758: doc-f>d
1.1       anton    4759: doc-f+
                   4760: doc-f-
                   4761: doc-f*
                   4762: doc-f/
                   4763: doc-fnegate
                   4764: doc-fabs
                   4765: doc-fmax
                   4766: doc-fmin
                   4767: doc-floor
                   4768: doc-fround
                   4769: doc-f**
                   4770: doc-fsqrt
                   4771: doc-fexp
                   4772: doc-fexpm1
                   4773: doc-fln
                   4774: doc-flnp1
                   4775: doc-flog
                   4776: doc-falog
1.32      anton    4777: doc-f2*
                   4778: doc-f2/
                   4779: doc-1/f
                   4780: doc-precision
                   4781: doc-set-precision
                   4782: 
                   4783: @cindex angles in trigonometric operations
                   4784: @cindex trigonometric operations
                   4785: Angles in floating point operations are given in radians (a full circle
                   4786: has 2 pi radians).
                   4787: 
1.1       anton    4788: doc-fsin
                   4789: doc-fcos
                   4790: doc-fsincos
                   4791: doc-ftan
                   4792: doc-fasin
                   4793: doc-facos
                   4794: doc-fatan
                   4795: doc-fatan2
                   4796: doc-fsinh
                   4797: doc-fcosh
                   4798: doc-ftanh
                   4799: doc-fasinh
                   4800: doc-facosh
                   4801: doc-fatanh
1.21      crook    4802: doc-pi
1.28      crook    4803: 
1.32      anton    4804: @cindex equality of floats
                   4805: @cindex floating-point comparisons
1.31      anton    4806: One particular problem with floating-point arithmetic is that comparison
                   4807: for equality often fails when you would expect it to succeed.  For this
                   4808: reason approximate equality is often preferred (but you still have to
1.67      anton    4809: know what you are doing).  Also note that IEEE NaNs may compare
1.68      anton    4810: differently from what you might expect.  The comparison words are:
1.31      anton    4811: 
                   4812: doc-f~rel
                   4813: doc-f~abs
1.68      anton    4814: doc-f~
1.31      anton    4815: doc-f=
                   4816: doc-f<>
                   4817: 
                   4818: doc-f<
                   4819: doc-f<=
                   4820: doc-f>
                   4821: doc-f>=
                   4822: 
1.21      crook    4823: doc-f0<
1.28      crook    4824: doc-f0<=
                   4825: doc-f0<>
1.21      crook    4826: doc-f0=
1.28      crook    4827: doc-f0>
                   4828: doc-f0>=
                   4829: 
1.1       anton    4830: 
                   4831: @node Stack Manipulation, Memory, Arithmetic, Words
                   4832: @section Stack Manipulation
                   4833: @cindex stack manipulation words
                   4834: 
                   4835: @cindex floating-point stack in the standard
1.21      crook    4836: Gforth maintains a number of separate stacks:
                   4837: 
1.29      crook    4838: @cindex data stack
                   4839: @cindex parameter stack
1.21      crook    4840: @itemize @bullet
                   4841: @item
1.29      crook    4842: A data stack (also known as the @dfn{parameter stack}) -- for
                   4843: characters, cells, addresses, and double cells.
1.21      crook    4844: 
1.29      crook    4845: @cindex floating-point stack
1.21      crook    4846: @item
1.44      crook    4847: A floating point stack -- for holding floating point (FP) numbers.
1.21      crook    4848: 
1.29      crook    4849: @cindex return stack
1.21      crook    4850: @item
1.44      crook    4851: A return stack -- for holding the return addresses of colon
1.32      anton    4852: definitions and other (non-FP) data.
1.21      crook    4853: 
1.29      crook    4854: @cindex locals stack
1.21      crook    4855: @item
1.44      crook    4856: A locals stack -- for holding local variables.
1.21      crook    4857: @end itemize
                   4858: 
1.1       anton    4859: @menu
                   4860: * Data stack::                  
                   4861: * Floating point stack::        
                   4862: * Return stack::                
                   4863: * Locals stack::                
                   4864: * Stack pointer manipulation::  
                   4865: @end menu
                   4866: 
                   4867: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   4868: @subsection Data stack
                   4869: @cindex data stack manipulation words
                   4870: @cindex stack manipulations words, data stack
                   4871: 
1.44      crook    4872: 
1.1       anton    4873: doc-drop
                   4874: doc-nip
                   4875: doc-dup
                   4876: doc-over
                   4877: doc-tuck
                   4878: doc-swap
1.21      crook    4879: doc-pick
1.1       anton    4880: doc-rot
                   4881: doc--rot
                   4882: doc-?dup
                   4883: doc-roll
                   4884: doc-2drop
                   4885: doc-2nip
                   4886: doc-2dup
                   4887: doc-2over
                   4888: doc-2tuck
                   4889: doc-2swap
                   4890: doc-2rot
                   4891: 
1.44      crook    4892: 
1.1       anton    4893: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   4894: @subsection Floating point stack
                   4895: @cindex floating-point stack manipulation words
                   4896: @cindex stack manipulation words, floating-point stack
                   4897: 
1.32      anton    4898: Whilst every sane Forth has a separate floating-point stack, it is not
                   4899: strictly required; an ANS Forth system could theoretically keep
                   4900: floating-point numbers on the data stack. As an additional difficulty,
                   4901: you don't know how many cells a floating-point number takes. It is
                   4902: reportedly possible to write words in a way that they work also for a
                   4903: unified stack model, but we do not recommend trying it. Instead, just
                   4904: say that your program has an environmental dependency on a separate
                   4905: floating-point stack.
                   4906: 
                   4907: doc-floating-stack
                   4908: 
1.1       anton    4909: doc-fdrop
                   4910: doc-fnip
                   4911: doc-fdup
                   4912: doc-fover
                   4913: doc-ftuck
                   4914: doc-fswap
1.21      crook    4915: doc-fpick
1.1       anton    4916: doc-frot
                   4917: 
1.44      crook    4918: 
1.1       anton    4919: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   4920: @subsection Return stack
                   4921: @cindex return stack manipulation words
                   4922: @cindex stack manipulation words, return stack
                   4923: 
1.32      anton    4924: @cindex return stack and locals
                   4925: @cindex locals and return stack
                   4926: A Forth system is allowed to keep local variables on the
                   4927: return stack. This is reasonable, as local variables usually eliminate
                   4928: the need to use the return stack explicitly. So, if you want to produce
                   4929: a standard compliant program and you are using local variables in a
                   4930: word, forget about return stack manipulations in that word (refer to the
                   4931: standard document for the exact rules).
                   4932: 
1.1       anton    4933: doc->r
                   4934: doc-r>
                   4935: doc-r@
                   4936: doc-rdrop
                   4937: doc-2>r
                   4938: doc-2r>
                   4939: doc-2r@
                   4940: doc-2rdrop
                   4941: 
1.44      crook    4942: 
1.1       anton    4943: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   4944: @subsection Locals stack
                   4945: 
1.78      anton    4946: Gforth uses an extra locals stack.  It is described, along with the
                   4947: reasons for its existence, in @ref{Locals implementation}.
1.21      crook    4948: 
1.1       anton    4949: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   4950: @subsection Stack pointer manipulation
                   4951: @cindex stack pointer manipulation words
                   4952: 
1.44      crook    4953: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21      crook    4954: doc-sp0
1.1       anton    4955: doc-sp@
                   4956: doc-sp!
1.21      crook    4957: doc-fp0
1.1       anton    4958: doc-fp@
                   4959: doc-fp!
1.21      crook    4960: doc-rp0
1.1       anton    4961: doc-rp@
                   4962: doc-rp!
1.21      crook    4963: doc-lp0
1.1       anton    4964: doc-lp@
                   4965: doc-lp!
                   4966: 
1.44      crook    4967: 
1.1       anton    4968: @node Memory, Control Structures, Stack Manipulation, Words
                   4969: @section Memory
1.26      crook    4970: @cindex memory words
1.1       anton    4971: 
1.32      anton    4972: @menu
                   4973: * Memory model::                
                   4974: * Dictionary allocation::       
                   4975: * Heap Allocation::             
                   4976: * Memory Access::               
                   4977: * Address arithmetic::          
                   4978: * Memory Blocks::               
                   4979: @end menu
                   4980: 
1.67      anton    4981: In addition to the standard Forth memory allocation words, there is also
                   4982: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   4983: garbage collector}.
                   4984: 
1.32      anton    4985: @node Memory model, Dictionary allocation, Memory, Memory
                   4986: @subsection ANS Forth and Gforth memory models
                   4987: 
                   4988: @c The ANS Forth description is a mess (e.g., is the heap part of
                   4989: @c the dictionary?), so let's not stick to closely with it.
                   4990: 
1.67      anton    4991: ANS Forth considers a Forth system as consisting of several address
                   4992: spaces, of which only @dfn{data space} is managed and accessible with
                   4993: the memory words.  Memory not necessarily in data space includes the
                   4994: stacks, the code (called code space) and the headers (called name
                   4995: space). In Gforth everything is in data space, but the code for the
                   4996: primitives is usually read-only.
1.32      anton    4997: 
                   4998: Data space is divided into a number of areas: The (data space portion of
                   4999: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
                   5000: refer to the search data structure embodied in word lists and headers,
                   5001: because it is used for looking up names, just as you would in a
                   5002: conventional dictionary.}, the heap, and a number of system-allocated
                   5003: buffers.
                   5004: 
1.68      anton    5005: @cindex address arithmetic restrictions, ANS vs. Gforth
                   5006: @cindex contiguous regions, ANS vs. Gforth
1.32      anton    5007: In ANS Forth data space is also divided into contiguous regions.  You
                   5008: can only use address arithmetic within a contiguous region, not between
                   5009: them.  Usually each allocation gives you one contiguous region, but the
1.33      anton    5010: dictionary allocation words have additional rules (@pxref{Dictionary
1.32      anton    5011: allocation}).
                   5012: 
                   5013: Gforth provides one big address space, and address arithmetic can be
                   5014: performed between any addresses. However, in the dictionary headers or
                   5015: code are interleaved with data, so almost the only contiguous data space
                   5016: regions there are those described by ANS Forth as contiguous; but you
                   5017: can be sure that the dictionary is allocated towards increasing
                   5018: addresses even between contiguous regions.  The memory order of
                   5019: allocations in the heap is platform-dependent (and possibly different
                   5020: from one run to the next).
                   5021: 
1.27      crook    5022: 
1.32      anton    5023: @node Dictionary allocation, Heap Allocation, Memory model, Memory
                   5024: @subsection Dictionary allocation
1.27      crook    5025: @cindex reserving data space
                   5026: @cindex data space - reserving some
                   5027: 
1.32      anton    5028: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
                   5029: you want to deallocate X, you also deallocate everything
                   5030: allocated after X.
                   5031: 
1.68      anton    5032: @cindex contiguous regions in dictionary allocation
1.32      anton    5033: The allocations using the words below are contiguous and grow the region
                   5034: towards increasing addresses.  Other words that allocate dictionary
                   5035: memory of any kind (i.e., defining words including @code{:noname}) end
                   5036: the contiguous region and start a new one.
                   5037: 
                   5038: In ANS Forth only @code{create}d words are guaranteed to produce an
                   5039: address that is the start of the following contiguous region.  In
                   5040: particular, the cell allocated by @code{variable} is not guaranteed to
                   5041: be contiguous with following @code{allot}ed memory.
                   5042: 
                   5043: You can deallocate memory by using @code{allot} with a negative argument
                   5044: (with some restrictions, see @code{allot}). For larger deallocations use
                   5045: @code{marker}.
1.27      crook    5046: 
1.29      crook    5047: 
1.27      crook    5048: doc-here
                   5049: doc-unused
                   5050: doc-allot
                   5051: doc-c,
1.29      crook    5052: doc-f,
1.27      crook    5053: doc-,
                   5054: doc-2,
                   5055: 
1.32      anton    5056: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
                   5057: course you should allocate memory in an aligned way, too. I.e., before
                   5058: allocating allocating a cell, @code{here} must be cell-aligned, etc.
                   5059: The words below align @code{here} if it is not already.  Basically it is
                   5060: only already aligned for a type, if the last allocation was a multiple
                   5061: of the size of this type and if @code{here} was aligned for this type
                   5062: before.
                   5063: 
                   5064: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
                   5065: ANS Forth (@code{maxalign}ed in Gforth).
                   5066: 
                   5067: doc-align
                   5068: doc-falign
                   5069: doc-sfalign
                   5070: doc-dfalign
                   5071: doc-maxalign
                   5072: doc-cfalign
                   5073: 
                   5074: 
                   5075: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
                   5076: @subsection Heap allocation
                   5077: @cindex heap allocation
                   5078: @cindex dynamic allocation of memory
                   5079: @cindex memory-allocation word set
                   5080: 
1.68      anton    5081: @cindex contiguous regions and heap allocation
1.32      anton    5082: Heap allocation supports deallocation of allocated memory in any
                   5083: order. Dictionary allocation is not affected by it (i.e., it does not
                   5084: end a contiguous region). In Gforth, these words are implemented using
                   5085: the standard C library calls malloc(), free() and resize().
                   5086: 
1.68      anton    5087: The memory region produced by one invocation of @code{allocate} or
                   5088: @code{resize} is internally contiguous.  There is no contiguity between
                   5089: such a region and any other region (including others allocated from the
                   5090: heap).
                   5091: 
1.32      anton    5092: doc-allocate
                   5093: doc-free
                   5094: doc-resize
                   5095: 
1.27      crook    5096: 
1.32      anton    5097: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1       anton    5098: @subsection Memory Access
                   5099: @cindex memory access words
                   5100: 
                   5101: doc-@
                   5102: doc-!
                   5103: doc-+!
                   5104: doc-c@
                   5105: doc-c!
                   5106: doc-2@
                   5107: doc-2!
                   5108: doc-f@
                   5109: doc-f!
                   5110: doc-sf@
                   5111: doc-sf!
                   5112: doc-df@
                   5113: doc-df!
1.144     anton    5114: doc-sw@
                   5115: doc-uw@
                   5116: doc-w!
                   5117: doc-sl@
                   5118: doc-ul@
                   5119: doc-l!
1.68      anton    5120: 
1.32      anton    5121: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   5122: @subsection Address arithmetic
1.1       anton    5123: @cindex address arithmetic words
                   5124: 
1.67      anton    5125: Address arithmetic is the foundation on which you can build data
                   5126: structures like arrays, records (@pxref{Structures}) and objects
                   5127: (@pxref{Object-oriented Forth}).
1.32      anton    5128: 
1.68      anton    5129: @cindex address unit
                   5130: @cindex au (address unit)
1.1       anton    5131: ANS Forth does not specify the sizes of the data types. Instead, it
                   5132: offers a number of words for computing sizes and doing address
1.29      crook    5133: arithmetic. Address arithmetic is performed in terms of address units
                   5134: (aus); on most systems the address unit is one byte. Note that a
                   5135: character may have more than one au, so @code{chars} is no noop (on
1.68      anton    5136: platforms where it is a noop, it compiles to nothing).
1.1       anton    5137: 
1.67      anton    5138: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
                   5139: you have the address of a cell, perform @code{1 cells +}, and you will
                   5140: have the address of the next cell.
                   5141: 
1.68      anton    5142: @cindex contiguous regions and address arithmetic
1.67      anton    5143: In ANS Forth you can perform address arithmetic only within a contiguous
                   5144: region, i.e., if you have an address into one region, you can only add
                   5145: and subtract such that the result is still within the region; you can
                   5146: only subtract or compare addresses from within the same contiguous
                   5147: region.  Reasons: several contiguous regions can be arranged in memory
                   5148: in any way; on segmented systems addresses may have unusual
                   5149: representations, such that address arithmetic only works within a
                   5150: region.  Gforth provides a few more guarantees (linear address space,
                   5151: dictionary grows upwards), but in general I have found it easy to stay
                   5152: within contiguous regions (exception: computing and comparing to the
                   5153: address just beyond the end of an array).
                   5154: 
1.1       anton    5155: @cindex alignment of addresses for types
                   5156: ANS Forth also defines words for aligning addresses for specific
                   5157: types. Many computers require that accesses to specific data types
                   5158: must only occur at specific addresses; e.g., that cells may only be
                   5159: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   5160: accesses, it can usually perform aligned accesses faster. 
                   5161: 
                   5162: For the performance-conscious: alignment operations are usually only
                   5163: necessary during the definition of a data structure, not during the
                   5164: (more frequent) accesses to it.
                   5165: 
                   5166: ANS Forth defines no words for character-aligning addresses. This is not
                   5167: an oversight, but reflects the fact that addresses that are not
                   5168: char-aligned have no use in the standard and therefore will not be
                   5169: created.
                   5170: 
                   5171: @cindex @code{CREATE} and alignment
1.29      crook    5172: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    5173: are cell-aligned; in addition, Gforth guarantees that these addresses
                   5174: are aligned for all purposes.
                   5175: 
1.26      crook    5176: Note that the ANS Forth word @code{char} has nothing to do with address
                   5177: arithmetic.
1.1       anton    5178: 
1.44      crook    5179: 
1.1       anton    5180: doc-chars
                   5181: doc-char+
                   5182: doc-cells
                   5183: doc-cell+
                   5184: doc-cell
                   5185: doc-aligned
                   5186: doc-floats
                   5187: doc-float+
                   5188: doc-float
                   5189: doc-faligned
                   5190: doc-sfloats
                   5191: doc-sfloat+
                   5192: doc-sfaligned
                   5193: doc-dfloats
                   5194: doc-dfloat+
                   5195: doc-dfaligned
                   5196: doc-maxaligned
                   5197: doc-cfaligned
                   5198: doc-address-unit-bits
1.145     anton    5199: doc-/w
                   5200: doc-/l
1.44      crook    5201: 
1.32      anton    5202: @node Memory Blocks,  , Address arithmetic, Memory
1.1       anton    5203: @subsection Memory Blocks
                   5204: @cindex memory block words
1.27      crook    5205: @cindex character strings - moving and copying
                   5206: 
1.49      anton    5207: Memory blocks often represent character strings; For ways of storing
                   5208: character strings in memory see @ref{String Formats}.  For other
                   5209: string-processing words see @ref{Displaying characters and strings}.
1.1       anton    5210: 
1.67      anton    5211: A few of these words work on address unit blocks.  In that case, you
                   5212: usually have to insert @code{CHARS} before the word when working on
                   5213: character strings.  Most words work on character blocks, and expect a
                   5214: char-aligned address.
                   5215: 
                   5216: When copying characters between overlapping memory regions, use
                   5217: @code{chars move} or choose carefully between @code{cmove} and
                   5218: @code{cmove>}.
1.44      crook    5219: 
1.1       anton    5220: doc-move
                   5221: doc-erase
                   5222: doc-cmove
                   5223: doc-cmove>
                   5224: doc-fill
                   5225: doc-blank
1.21      crook    5226: doc-compare
1.111     anton    5227: doc-str=
                   5228: doc-str<
                   5229: doc-string-prefix?
1.21      crook    5230: doc-search
1.27      crook    5231: doc--trailing
                   5232: doc-/string
1.82      anton    5233: doc-bounds
1.141     anton    5234: doc-pad
1.111     anton    5235: 
1.27      crook    5236: @comment TODO examples
                   5237: 
1.1       anton    5238: 
1.26      crook    5239: @node Control Structures, Defining Words, Memory, Words
1.1       anton    5240: @section Control Structures
                   5241: @cindex control structures
                   5242: 
1.33      anton    5243: Control structures in Forth cannot be used interpretively, only in a
                   5244: colon definition@footnote{To be precise, they have no interpretation
                   5245: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
                   5246: not like this limitation, but have not seen a satisfying way around it
                   5247: yet, although many schemes have been proposed.
1.1       anton    5248: 
                   5249: @menu
1.33      anton    5250: * Selection::                   IF ... ELSE ... ENDIF
                   5251: * Simple Loops::                BEGIN ...
1.29      crook    5252: * Counted Loops::               DO
1.67      anton    5253: * Arbitrary control structures::  
                   5254: * Calls and returns::           
1.1       anton    5255: * Exception Handling::          
                   5256: @end menu
                   5257: 
                   5258: @node Selection, Simple Loops, Control Structures, Control Structures
                   5259: @subsection Selection
                   5260: @cindex selection control structures
                   5261: @cindex control structures for selection
                   5262: 
                   5263: @cindex @code{IF} control structure
                   5264: @example
1.29      crook    5265: @i{flag}
1.1       anton    5266: IF
1.29      crook    5267:   @i{code}
1.1       anton    5268: ENDIF
                   5269: @end example
1.21      crook    5270: @noindent
1.33      anton    5271: 
1.44      crook    5272: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
                   5273: with any bit set represents truth) @i{code} is executed.
1.33      anton    5274: 
1.1       anton    5275: @example
1.29      crook    5276: @i{flag}
1.1       anton    5277: IF
1.29      crook    5278:   @i{code1}
1.1       anton    5279: ELSE
1.29      crook    5280:   @i{code2}
1.1       anton    5281: ENDIF
                   5282: @end example
                   5283: 
1.44      crook    5284: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
                   5285: executed.
1.33      anton    5286: 
1.1       anton    5287: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   5288: standard, and @code{ENDIF} is not, although it is quite popular. We
                   5289: recommend using @code{ENDIF}, because it is less confusing for people
                   5290: who also know other languages (and is not prone to reinforcing negative
                   5291: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   5292: system that only supplies @code{THEN} is simple:
                   5293: @example
1.82      anton    5294: : ENDIF   POSTPONE then ; immediate
1.1       anton    5295: @end example
                   5296: 
                   5297: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   5298: (adv.)}  has the following meanings:
                   5299: @quotation
                   5300: ... 2b: following next after in order ... 3d: as a necessary consequence
                   5301: (if you were there, then you saw them).
                   5302: @end quotation
                   5303: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   5304: and many other programming languages has the meaning 3d.]
                   5305: 
1.21      crook    5306: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    5307: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    5308: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    5309: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   5310: @file{compat/control.fs}.
                   5311: 
                   5312: @cindex @code{CASE} control structure
                   5313: @example
1.29      crook    5314: @i{n}
1.1       anton    5315: CASE
1.29      crook    5316:   @i{n1} OF @i{code1} ENDOF
                   5317:   @i{n2} OF @i{code2} ENDOF
1.1       anton    5318:   @dots{}
1.68      anton    5319:   ( n ) @i{default-code} ( n )
1.131     anton    5320: ENDCASE ( )
1.1       anton    5321: @end example
                   5322: 
1.131     anton    5323: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If
                   5324: no @i{ni} matches, the optional @i{default-code} is executed. The
                   5325: optional default case can be added by simply writing the code after
                   5326: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
                   5327: but must not consume it.  The value @i{n} is consumed by this
                   5328: construction (either by a OF that matches, or by the ENDCASE, if no OF
                   5329: matches).
1.1       anton    5330: 
1.69      anton    5331: @progstyle
1.131     anton    5332: To keep the code understandable, you should ensure that you change the
                   5333: stack in the same way (wrt. number and types of stack items consumed
                   5334: and pushed) on all paths through a selection construct.
1.69      anton    5335: 
1.1       anton    5336: @node Simple Loops, Counted Loops, Selection, Control Structures
                   5337: @subsection Simple Loops
                   5338: @cindex simple loops
                   5339: @cindex loops without count 
                   5340: 
                   5341: @cindex @code{WHILE} loop
                   5342: @example
                   5343: BEGIN
1.29      crook    5344:   @i{code1}
                   5345:   @i{flag}
1.1       anton    5346: WHILE
1.29      crook    5347:   @i{code2}
1.1       anton    5348: REPEAT
                   5349: @end example
                   5350: 
1.29      crook    5351: @i{code1} is executed and @i{flag} is computed. If it is true,
                   5352: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    5353: false, execution continues after the @code{REPEAT}.
                   5354: 
                   5355: @cindex @code{UNTIL} loop
                   5356: @example
                   5357: BEGIN
1.29      crook    5358:   @i{code}
                   5359:   @i{flag}
1.1       anton    5360: UNTIL
                   5361: @end example
                   5362: 
1.29      crook    5363: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    5364: 
1.69      anton    5365: @progstyle
                   5366: To keep the code understandable, a complete iteration of the loop should
                   5367: not change the number and types of the items on the stacks.
                   5368: 
1.1       anton    5369: @cindex endless loop
                   5370: @cindex loops, endless
                   5371: @example
                   5372: BEGIN
1.29      crook    5373:   @i{code}
1.1       anton    5374: AGAIN
                   5375: @end example
                   5376: 
                   5377: This is an endless loop.
                   5378: 
                   5379: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   5380: @subsection Counted Loops
                   5381: @cindex counted loops
                   5382: @cindex loops, counted
                   5383: @cindex @code{DO} loops
                   5384: 
                   5385: The basic counted loop is:
                   5386: @example
1.29      crook    5387: @i{limit} @i{start}
1.1       anton    5388: ?DO
1.29      crook    5389:   @i{body}
1.1       anton    5390: LOOP
                   5391: @end example
                   5392: 
1.29      crook    5393: This performs one iteration for every integer, starting from @i{start}
                   5394: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    5395: accessed with @code{i}. For example, the loop:
1.1       anton    5396: @example
                   5397: 10 0 ?DO
                   5398:   i .
                   5399: LOOP
                   5400: @end example
1.21      crook    5401: @noindent
                   5402: prints @code{0 1 2 3 4 5 6 7 8 9}
                   5403: 
1.1       anton    5404: The index of the innermost loop can be accessed with @code{i}, the index
                   5405: of the next loop with @code{j}, and the index of the third loop with
                   5406: @code{k}.
                   5407: 
1.44      crook    5408: 
1.1       anton    5409: doc-i
                   5410: doc-j
                   5411: doc-k
                   5412: 
1.44      crook    5413: 
1.1       anton    5414: The loop control data are kept on the return stack, so there are some
1.21      crook    5415: restrictions on mixing return stack accesses and counted loop words. In
                   5416: particuler, if you put values on the return stack outside the loop, you
                   5417: cannot read them inside the loop@footnote{well, not in a way that is
                   5418: portable.}. If you put values on the return stack within a loop, you
                   5419: have to remove them before the end of the loop and before accessing the
                   5420: index of the loop.
1.1       anton    5421: 
                   5422: There are several variations on the counted loop:
                   5423: 
1.21      crook    5424: @itemize @bullet
                   5425: @item
                   5426: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   5427: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   5428: 
                   5429: @example
                   5430: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   5431: @end example
                   5432: prints @code{0 1 2 3}
                   5433: 
1.1       anton    5434: 
1.21      crook    5435: @item
                   5436: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   5437: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   5438: return stack so @code{EXIT} can get to its return address. For example:
                   5439: 
                   5440: @example
                   5441: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   5442: @end example
                   5443: prints @code{0 1 2 3}
                   5444: 
                   5445: 
                   5446: @item
1.29      crook    5447: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    5448: (and @code{LOOP} iterates until they become equal by wrap-around
                   5449: arithmetic). This behaviour is usually not what you want. Therefore,
                   5450: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    5451: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   5452: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    5453: unsigned loop parameters.
                   5454: 
1.21      crook    5455: @item
                   5456: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   5457: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   5458: if you know that the loop is entered in any case. Such knowledge tends
                   5459: to become invalid during maintenance of a program, and then the
                   5460: @code{DO} will make trouble.
                   5461: 
                   5462: @item
1.29      crook    5463: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   5464: index by @i{n} instead of by 1. The loop is terminated when the border
                   5465: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    5466: 
1.21      crook    5467: @example
                   5468: 4 0 +DO  i .  2 +LOOP
                   5469: @end example
                   5470: @noindent
                   5471: prints @code{0 2}
                   5472: 
                   5473: @example
                   5474: 4 1 +DO  i .  2 +LOOP
                   5475: @end example
                   5476: @noindent
                   5477: prints @code{1 3}
1.1       anton    5478: 
1.68      anton    5479: @item
1.1       anton    5480: @cindex negative increment for counted loops
                   5481: @cindex counted loops with negative increment
1.29      crook    5482: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    5483: 
1.21      crook    5484: @example
                   5485: -1 0 ?DO  i .  -1 +LOOP
                   5486: @end example
                   5487: @noindent
                   5488: prints @code{0 -1}
1.1       anton    5489: 
1.21      crook    5490: @example
                   5491: 0 0 ?DO  i .  -1 +LOOP
                   5492: @end example
                   5493: prints nothing.
1.1       anton    5494: 
1.29      crook    5495: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   5496: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   5497: index by @i{u} each iteration. The loop is terminated when the border
                   5498: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    5499: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   5500: 
1.21      crook    5501: @example
                   5502: -2 0 -DO  i .  1 -LOOP
                   5503: @end example
                   5504: @noindent
                   5505: prints @code{0 -1}
1.1       anton    5506: 
1.21      crook    5507: @example
                   5508: -1 0 -DO  i .  1 -LOOP
                   5509: @end example
                   5510: @noindent
                   5511: prints @code{0}
                   5512: 
                   5513: @example
                   5514: 0 0 -DO  i .  1 -LOOP
                   5515: @end example
                   5516: @noindent
                   5517: prints nothing.
1.1       anton    5518: 
1.21      crook    5519: @end itemize
1.1       anton    5520: 
                   5521: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    5522: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   5523: for these words that uses only standard words is provided in
                   5524: @file{compat/loops.fs}.
1.1       anton    5525: 
                   5526: 
                   5527: @cindex @code{FOR} loops
1.26      crook    5528: Another counted loop is:
1.1       anton    5529: @example
1.29      crook    5530: @i{n}
1.1       anton    5531: FOR
1.29      crook    5532:   @i{body}
1.1       anton    5533: NEXT
                   5534: @end example
                   5535: This is the preferred loop of native code compiler writers who are too
1.26      crook    5536: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    5537: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   5538: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    5539: Forth systems may behave differently, even if they support @code{FOR}
                   5540: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    5541: 
                   5542: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   5543: @subsection Arbitrary control structures
                   5544: @cindex control structures, user-defined
                   5545: 
                   5546: @cindex control-flow stack
                   5547: ANS Forth permits and supports using control structures in a non-nested
                   5548: way. Information about incomplete control structures is stored on the
                   5549: control-flow stack. This stack may be implemented on the Forth data
                   5550: stack, and this is what we have done in Gforth.
                   5551: 
                   5552: @cindex @code{orig}, control-flow stack item
                   5553: @cindex @code{dest}, control-flow stack item
                   5554: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   5555: entry represents a backward branch target. A few words are the basis for
                   5556: building any control structure possible (except control structures that
                   5557: need storage, like calls, coroutines, and backtracking).
                   5558: 
1.44      crook    5559: 
1.1       anton    5560: doc-if
                   5561: doc-ahead
                   5562: doc-then
                   5563: doc-begin
                   5564: doc-until
                   5565: doc-again
                   5566: doc-cs-pick
                   5567: doc-cs-roll
                   5568: 
1.44      crook    5569: 
1.21      crook    5570: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   5571: manipulate the control-flow stack in a portable way. Without them, you
                   5572: would need to know how many stack items are occupied by a control-flow
                   5573: entry (many systems use one cell. In Gforth they currently take three,
                   5574: but this may change in the future).
                   5575: 
1.1       anton    5576: Some standard control structure words are built from these words:
                   5577: 
1.44      crook    5578: 
1.1       anton    5579: doc-else
                   5580: doc-while
                   5581: doc-repeat
                   5582: 
1.44      crook    5583: 
                   5584: @noindent
1.1       anton    5585: Gforth adds some more control-structure words:
                   5586: 
1.44      crook    5587: 
1.1       anton    5588: doc-endif
                   5589: doc-?dup-if
                   5590: doc-?dup-0=-if
                   5591: 
1.44      crook    5592: 
                   5593: @noindent
1.1       anton    5594: Counted loop words constitute a separate group of words:
                   5595: 
1.44      crook    5596: 
1.1       anton    5597: doc-?do
                   5598: doc-+do
                   5599: doc-u+do
                   5600: doc--do
                   5601: doc-u-do
                   5602: doc-do
                   5603: doc-for
                   5604: doc-loop
                   5605: doc-+loop
                   5606: doc--loop
                   5607: doc-next
                   5608: doc-leave
                   5609: doc-?leave
                   5610: doc-unloop
                   5611: doc-done
                   5612: 
1.44      crook    5613: 
1.21      crook    5614: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   5615: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    5616: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   5617: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   5618: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   5619: resolved (by using one of the loop-ending words or @code{DONE}).
                   5620: 
1.44      crook    5621: @noindent
1.26      crook    5622: Another group of control structure words are:
1.1       anton    5623: 
1.44      crook    5624: 
1.1       anton    5625: doc-case
                   5626: doc-endcase
                   5627: doc-of
                   5628: doc-endof
                   5629: 
1.44      crook    5630: 
1.21      crook    5631: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   5632: @code{CS-ROLL}.
1.1       anton    5633: 
                   5634: @subsubsection Programming Style
1.47      crook    5635: @cindex control structures programming style
                   5636: @cindex programming style, arbitrary control structures
1.1       anton    5637: 
                   5638: In order to ensure readability we recommend that you do not create
                   5639: arbitrary control structures directly, but define new control structure
                   5640: words for the control structure you want and use these words in your
1.26      crook    5641: program. For example, instead of writing:
1.1       anton    5642: 
                   5643: @example
1.26      crook    5644: BEGIN
1.1       anton    5645:   ...
1.26      crook    5646: IF [ 1 CS-ROLL ]
1.1       anton    5647:   ...
1.26      crook    5648: AGAIN THEN
1.1       anton    5649: @end example
                   5650: 
1.21      crook    5651: @noindent
1.1       anton    5652: we recommend defining control structure words, e.g.,
                   5653: 
                   5654: @example
1.26      crook    5655: : WHILE ( DEST -- ORIG DEST )
                   5656:  POSTPONE IF
                   5657:  1 CS-ROLL ; immediate
                   5658: 
                   5659: : REPEAT ( orig dest -- )
                   5660:  POSTPONE AGAIN
                   5661:  POSTPONE THEN ; immediate
1.1       anton    5662: @end example
                   5663: 
1.21      crook    5664: @noindent
1.1       anton    5665: and then using these to create the control structure:
                   5666: 
                   5667: @example
1.26      crook    5668: BEGIN
1.1       anton    5669:   ...
1.26      crook    5670: WHILE
1.1       anton    5671:   ...
1.26      crook    5672: REPEAT
1.1       anton    5673: @end example
                   5674: 
                   5675: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   5676: @code{WHILE} are predefined, so in this example it would not be
                   5677: necessary to define them.
                   5678: 
                   5679: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   5680: @subsection Calls and returns
                   5681: @cindex calling a definition
                   5682: @cindex returning from a definition
                   5683: 
1.3       anton    5684: @cindex recursive definitions
                   5685: A definition can be called simply be writing the name of the definition
1.26      crook    5686: to be called. Normally a definition is invisible during its own
1.3       anton    5687: definition. If you want to write a directly recursive definition, you
1.26      crook    5688: can use @code{recursive} to make the current definition visible, or
                   5689: @code{recurse} to call the current definition directly.
1.3       anton    5690: 
1.44      crook    5691: 
1.3       anton    5692: doc-recursive
                   5693: doc-recurse
                   5694: 
1.44      crook    5695: 
1.21      crook    5696: @comment TODO add example of the two recursion methods
1.12      anton    5697: @quotation
                   5698: @progstyle
                   5699: I prefer using @code{recursive} to @code{recurse}, because calling the
                   5700: definition by name is more descriptive (if the name is well-chosen) than
                   5701: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   5702: implementation, it is much better to read (and think) ``now sort the
                   5703: partitions'' than to read ``now do a recursive call''.
                   5704: @end quotation
1.3       anton    5705: 
1.29      crook    5706: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    5707: 
                   5708: @example
1.28      crook    5709: Defer foo
1.3       anton    5710: 
                   5711: : bar ( ... -- ... )
                   5712:  ... foo ... ;
                   5713: 
                   5714: :noname ( ... -- ... )
                   5715:  ... bar ... ;
                   5716: IS foo
                   5717: @end example
                   5718: 
1.170     pazsan   5719: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33      anton    5720: 
1.26      crook    5721: The current definition returns control to the calling definition when
1.33      anton    5722: the end of the definition is reached or @code{EXIT} is encountered.
1.1       anton    5723: 
                   5724: doc-exit
                   5725: doc-;s
                   5726: 
1.44      crook    5727: 
1.1       anton    5728: @node Exception Handling,  , Calls and returns, Control Structures
                   5729: @subsection Exception Handling
1.26      crook    5730: @cindex exceptions
1.1       anton    5731: 
1.68      anton    5732: @c quit is a very bad idea for error handling, 
                   5733: @c because it does not translate into a THROW
                   5734: @c it also does not belong into this chapter
                   5735: 
                   5736: If a word detects an error condition that it cannot handle, it can
                   5737: @code{throw} an exception.  In the simplest case, this will terminate
                   5738: your program, and report an appropriate error.
1.21      crook    5739: 
1.68      anton    5740: doc-throw
1.1       anton    5741: 
1.69      anton    5742: @code{Throw} consumes a cell-sized error number on the stack. There are
                   5743: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
                   5744: Gforth (and most other systems) you can use the iors produced by various
                   5745: words as error numbers (e.g., a typical use of @code{allocate} is
                   5746: @code{allocate throw}).  Gforth also provides the word @code{exception}
                   5747: to define your own error numbers (with decent error reporting); an ANS
                   5748: Forth version of this word (but without the error messages) is available
                   5749: in @code{compat/except.fs}.  And finally, you can use your own error
1.68      anton    5750: numbers (anything outside the range -4095..0), but won't get nice error
                   5751: messages, only numbers.  For example, try:
                   5752: 
                   5753: @example
1.69      anton    5754: -10 throw                    \ ANS defined
                   5755: -267 throw                   \ system defined
                   5756: s" my error" exception throw \ user defined
                   5757: 7 throw                      \ arbitrary number
1.68      anton    5758: @end example
                   5759: 
                   5760: doc---exception-exception
1.1       anton    5761: 
1.69      anton    5762: A common idiom to @code{THROW} a specific error if a flag is true is
                   5763: this:
                   5764: 
                   5765: @example
                   5766: @code{( flag ) 0<> @i{errno} and throw}
                   5767: @end example
                   5768: 
                   5769: Your program can provide exception handlers to catch exceptions.  An
                   5770: exception handler can be used to correct the problem, or to clean up
                   5771: some data structures and just throw the exception to the next exception
                   5772: handler.  Note that @code{throw} jumps to the dynamically innermost
                   5773: exception handler.  The system's exception handler is outermost, and just
                   5774: prints an error and restarts command-line interpretation (or, in batch
                   5775: mode (i.e., while processing the shell command line), leaves Gforth).
1.1       anton    5776: 
1.68      anton    5777: The ANS Forth way to catch exceptions is @code{catch}:
1.1       anton    5778: 
1.68      anton    5779: doc-catch
1.160     anton    5780: doc-nothrow
1.68      anton    5781: 
                   5782: The most common use of exception handlers is to clean up the state when
                   5783: an error happens.  E.g.,
1.1       anton    5784: 
1.26      crook    5785: @example
1.68      anton    5786: base @ >r hex \ actually the hex should be inside foo, or we h
                   5787: ['] foo catch ( nerror|0 )
                   5788: r> base !
1.69      anton    5789: ( nerror|0 ) throw \ pass it on
1.26      crook    5790: @end example
1.1       anton    5791: 
1.69      anton    5792: A use of @code{catch} for handling the error @code{myerror} might look
                   5793: like this:
1.44      crook    5794: 
1.68      anton    5795: @example
1.69      anton    5796: ['] foo catch
                   5797: CASE
1.160     anton    5798:   myerror OF ... ( do something about it ) nothrow ENDOF
1.69      anton    5799:   dup throw \ default: pass other errors on, do nothing on non-errors
                   5800: ENDCASE
1.68      anton    5801: @end example
1.44      crook    5802: 
1.68      anton    5803: Having to wrap the code into a separate word is often cumbersome,
                   5804: therefore Gforth provides an alternative syntax:
1.1       anton    5805: 
                   5806: @example
1.69      anton    5807: TRY
1.68      anton    5808:   @i{code1}
1.172     anton    5809:   IFERROR
                   5810:     @i{code2}
                   5811:   THEN
                   5812:   @i{code3}
1.69      anton    5813: ENDTRY
1.1       anton    5814: @end example
                   5815: 
1.172     anton    5816: This performs @i{code1}.  If @i{code1} completes normally, execution
                   5817: continues with @i{code3}.  If @i{code1} or there is an exception
                   5818: before @code{endtry}, the stacks are reset to the state during
                   5819: @code{try}, the throw value is pushed on the data stack, and execution
                   5820: constinues at @i{code2}, and finally falls through the @i{code3}.
1.26      crook    5821: 
1.68      anton    5822: doc-try
                   5823: doc-endtry
1.172     anton    5824: doc-iferror
                   5825: 
                   5826: If you don't need @i{code2}, you can write @code{restore} instead of
                   5827: @code{iferror then}:
                   5828: 
                   5829: @example
                   5830: TRY
                   5831:   @i{code1}
                   5832: RESTORE
                   5833:   @i{code3}
                   5834: ENDTRY
                   5835: @end example
1.26      crook    5836: 
1.172     anton    5837: @cindex unwind-protect
1.69      anton    5838: The cleanup example from above in this syntax:
1.26      crook    5839: 
1.68      anton    5840: @example
1.174     anton    5841: base @@ @{ oldbase @}
1.172     anton    5842: TRY
1.68      anton    5843:   hex foo \ now the hex is placed correctly
1.69      anton    5844:   0       \ value for throw
1.172     anton    5845: RESTORE
                   5846:   oldbase base !
                   5847: ENDTRY
                   5848: throw
1.1       anton    5849: @end example
                   5850: 
1.172     anton    5851: An additional advantage of this variant is that an exception between
                   5852: @code{restore} and @code{endtry} (e.g., from the user pressing
                   5853: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
                   5854: so the base will be restored under all circumstances.
                   5855: 
                   5856: However, you have to ensure that this code does not cause an exception
                   5857: itself, otherwise the @code{iferror}/@code{restore} code will loop.
                   5858: Moreover, you should also make sure that the stack contents needed by
                   5859: the @code{iferror}/@code{restore} code exist everywhere between
                   5860: @code{try} and @code{endtry}; in our example this is achived by
                   5861: putting the data in a local before the @code{try} (you cannot use the
                   5862: return stack because the exception frame (@i{sys1}) is in the way
                   5863: there).
                   5864: 
                   5865: This kind of usage corresponds to Lisp's @code{unwind-protect}.
                   5866: 
                   5867: @cindex @code{recover} (old Gforth versions)
                   5868: If you do not want this exception-restarting behaviour, you achieve
                   5869: this as follows:
                   5870: 
                   5871: @example
                   5872: TRY
                   5873:   @i{code1}
                   5874: ENDTRY-IFERROR
                   5875:   @i{code2}
                   5876: THEN
                   5877: @end example
                   5878: 
                   5879: If there is an exception in @i{code1}, then @i{code2} is executed,
                   5880: otherwise execution continues behind the @code{then} (or in a possible
                   5881: @code{else} branch).  This corresponds to the construct
                   5882: 
                   5883: @example
                   5884: TRY
                   5885:   @i{code1}
                   5886: RECOVER
                   5887:   @i{code2}
                   5888: ENDTRY
                   5889: @end example
                   5890: 
                   5891: in Gforth before version 0.7.  So you can directly replace
                   5892: @code{recover}-using code; however, we recommend that you check if it
                   5893: would not be better to use one of the other @code{try} variants while
                   5894: you are at it.
                   5895: 
1.173     anton    5896: To ease the transition, Gforth provides two compatibility files:
                   5897: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
                   5898: ... then} syntax (but not @code{iferror} or @code{restore}) for old
                   5899: systems; @file{recover-endtry.fs} provides the @code{try ... recover
                   5900: ... endtry} syntax on new systems, so you can use that file as a
                   5901: stopgap to run old programs.  Both files work on any system (they just
                   5902: do nothing if the system already has the syntax it implements), so you
                   5903: can unconditionally @code{require} one of these files, even if you use
                   5904: a mix old and new systems.
                   5905: 
1.172     anton    5906: doc-restore
                   5907: doc-endtry-iferror
                   5908: 
                   5909: Here's the error handling example:
1.1       anton    5910: 
1.68      anton    5911: @example
1.69      anton    5912: TRY
1.68      anton    5913:   foo
1.172     anton    5914: ENDTRY-IFERROR
1.69      anton    5915:   CASE
1.160     anton    5916:     myerror OF ... ( do something about it ) nothrow ENDOF
1.69      anton    5917:     throw \ pass other errors on
                   5918:   ENDCASE
1.172     anton    5919: THEN
1.68      anton    5920: @end example
1.1       anton    5921: 
1.69      anton    5922: @progstyle
                   5923: As usual, you should ensure that the stack depth is statically known at
                   5924: the end: either after the @code{throw} for passing on errors, or after
                   5925: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
                   5926: selection construct for handling the error).
                   5927: 
1.68      anton    5928: There are two alternatives to @code{throw}: @code{Abort"} is conditional
                   5929: and you can provide an error message.  @code{Abort} just produces an
                   5930: ``Aborted'' error.
1.1       anton    5931: 
1.68      anton    5932: The problem with these words is that exception handlers cannot
                   5933: differentiate between different @code{abort"}s; they just look like
                   5934: @code{-2 throw} to them (the error message cannot be accessed by
                   5935: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
                   5936: exception handlers.
1.44      crook    5937: 
1.68      anton    5938: doc-abort"
1.26      crook    5939: doc-abort
1.29      crook    5940: 
                   5941: 
1.44      crook    5942: 
1.29      crook    5943: @c -------------------------------------------------------------
1.47      crook    5944: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29      crook    5945: @section Defining Words
                   5946: @cindex defining words
                   5947: 
1.47      crook    5948: Defining words are used to extend Forth by creating new entries in the dictionary.
                   5949: 
1.29      crook    5950: @menu
1.67      anton    5951: * CREATE::                      
1.44      crook    5952: * Variables::                   Variables and user variables
1.67      anton    5953: * Constants::                   
1.44      crook    5954: * Values::                      Initialised variables
1.67      anton    5955: * Colon Definitions::           
1.44      crook    5956: * Anonymous Definitions::       Definitions without names
1.69      anton    5957: * Supplying names::             Passing definition names as strings
1.67      anton    5958: * User-defined Defining Words::  
1.170     pazsan   5959: * Deferred Words::              Allow forward references
1.67      anton    5960: * Aliases::                     
1.29      crook    5961: @end menu
                   5962: 
1.44      crook    5963: @node CREATE, Variables, Defining Words, Defining Words
                   5964: @subsection @code{CREATE}
1.29      crook    5965: @cindex simple defining words
                   5966: @cindex defining words, simple
                   5967: 
                   5968: Defining words are used to create new entries in the dictionary. The
                   5969: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   5970: this:
                   5971: 
                   5972: @example
                   5973: CREATE new-word1
                   5974: @end example
                   5975: 
1.69      anton    5976: @code{CREATE} is a parsing word, i.e., it takes an argument from the
                   5977: input stream (@code{new-word1} in our example).  It generates a
                   5978: dictionary entry for @code{new-word1}. When @code{new-word1} is
                   5979: executed, all that it does is leave an address on the stack. The address
                   5980: represents the value of the data space pointer (@code{HERE}) at the time
                   5981: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
                   5982: associating a name with the address of a region of memory.
1.29      crook    5983: 
1.34      anton    5984: doc-create
                   5985: 
1.69      anton    5986: Note that in ANS Forth guarantees only for @code{create} that its body
                   5987: is in dictionary data space (i.e., where @code{here}, @code{allot}
                   5988: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
                   5989: @code{create}d words can be modified with @code{does>}
                   5990: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
                   5991: can only be applied to @code{create}d words.
                   5992: 
1.29      crook    5993: By extending this example to reserve some memory in data space, we end
1.69      anton    5994: up with something like a @i{variable}. Here are two different ways to do
                   5995: it:
1.29      crook    5996: 
                   5997: @example
                   5998: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   5999: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   6000: @end example
                   6001: 
                   6002: The variable can be examined and modified using @code{@@} (``fetch'') and
                   6003: @code{!} (``store'') like this:
                   6004: 
                   6005: @example
                   6006: new-word2 @@ .      \ get address, fetch from it and display
                   6007: 1234 new-word2 !   \ new value, get address, store to it
                   6008: @end example
                   6009: 
1.44      crook    6010: @cindex arrays
                   6011: A similar mechanism can be used to create arrays. For example, an
                   6012: 80-character text input buffer:
1.29      crook    6013: 
                   6014: @example
1.44      crook    6015: CREATE text-buf 80 chars allot
                   6016: 
1.168     anton    6017: text-buf 0 chars + c@@ \ the 1st character (offset 0)
                   6018: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44      crook    6019: @end example
1.29      crook    6020: 
1.44      crook    6021: You can build arbitrarily complex data structures by allocating
1.49      anton    6022: appropriate areas of memory. For further discussions of this, and to
1.66      anton    6023: learn about some Gforth tools that make it easier,
1.49      anton    6024: @xref{Structures}.
1.44      crook    6025: 
                   6026: 
                   6027: @node Variables, Constants, CREATE, Defining Words
                   6028: @subsection Variables
                   6029: @cindex variables
                   6030: 
                   6031: The previous section showed how a sequence of commands could be used to
                   6032: generate a variable.  As a final refinement, the whole code sequence can
                   6033: be wrapped up in a defining word (pre-empting the subject of the next
                   6034: section), making it easier to create new variables:
                   6035: 
                   6036: @example
                   6037: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
                   6038: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
                   6039: 
                   6040: myvariableX foo \ variable foo starts off with an unknown value
                   6041: myvariable0 joe \ whilst joe is initialised to 0
1.29      crook    6042: 
                   6043: 45 3 * foo !   \ set foo to 135
                   6044: 1234 joe !     \ set joe to 1234
                   6045: 3 joe +!       \ increment joe by 3.. to 1237
                   6046: @end example
                   6047: 
                   6048: Not surprisingly, there is no need to define @code{myvariable}, since
1.44      crook    6049: Forth already has a definition @code{Variable}. ANS Forth does not
1.69      anton    6050: guarantee that a @code{Variable} is initialised when it is created
                   6051: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
                   6052: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
                   6053: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47      crook    6054: @code{fvariable} for double and floating-point variables, respectively
1.69      anton    6055: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47      crook    6056: store a boolean, you can use @code{on} and @code{off} to toggle its
                   6057: state.
1.29      crook    6058: 
1.34      anton    6059: doc-variable
                   6060: doc-2variable
                   6061: doc-fvariable
                   6062: 
1.29      crook    6063: @cindex user variables
                   6064: @cindex user space
                   6065: The defining word @code{User} behaves in the same way as @code{Variable}.
                   6066: The difference is that it reserves space in @i{user (data) space} rather
                   6067: than normal data space. In a Forth system that has a multi-tasker, each
                   6068: task has its own set of user variables.
                   6069: 
1.34      anton    6070: doc-user
1.67      anton    6071: @c doc-udp
                   6072: @c doc-uallot
1.34      anton    6073: 
1.29      crook    6074: @comment TODO is that stuff about user variables strictly correct? Is it
                   6075: @comment just terminal tasks that have user variables?
                   6076: @comment should document tasker.fs (with some examples) elsewhere
                   6077: @comment in this manual, then expand on user space and user variables.
                   6078: 
1.44      crook    6079: @node Constants, Values, Variables, Defining Words
                   6080: @subsection Constants
                   6081: @cindex constants
                   6082: 
                   6083: @code{Constant} allows you to declare a fixed value and refer to it by
                   6084: name. For example:
1.29      crook    6085: 
                   6086: @example
                   6087: 12 Constant INCHES-PER-FOOT
                   6088: 3E+08 fconstant SPEED-O-LIGHT
                   6089: @end example
                   6090: 
                   6091: A @code{Variable} can be both read and written, so its run-time
                   6092: behaviour is to supply an address through which its current value can be
                   6093: manipulated. In contrast, the value of a @code{Constant} cannot be
                   6094: changed once it has been declared@footnote{Well, often it can be -- but
                   6095: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   6096: on).} so it's not necessary to supply the address -- it is more
                   6097: efficient to return the value of the constant directly. That's exactly
                   6098: what happens; the run-time effect of a constant is to put its value on
1.49      anton    6099: the top of the stack (You can find one
                   6100: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29      crook    6101: 
1.69      anton    6102: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29      crook    6103: double and floating-point constants, respectively.
                   6104: 
1.34      anton    6105: doc-constant
                   6106: doc-2constant
                   6107: doc-fconstant
                   6108: 
                   6109: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44      crook    6110: @c nac-> How could that not be true in an ANS Forth? You can't define a
                   6111: @c constant, use it and then delete the definition of the constant..
1.69      anton    6112: 
                   6113: @c anton->An ANS Forth system can compile a constant to a literal; On
                   6114: @c decompilation you would see only the number, just as if it had been used
                   6115: @c in the first place.  The word will stay, of course, but it will only be
                   6116: @c used by the text interpreter (no run-time duties, except when it is 
                   6117: @c POSTPONEd or somesuch).
                   6118: 
                   6119: @c nac:
1.44      crook    6120: @c I agree that it's rather deep, but IMO it is an important difference
                   6121: @c relative to other programming languages.. often it's annoying: it
                   6122: @c certainly changes my programming style relative to C.
                   6123: 
1.69      anton    6124: @c anton: In what way?
                   6125: 
1.29      crook    6126: Constants in Forth behave differently from their equivalents in other
                   6127: programming languages. In other languages, a constant (such as an EQU in
                   6128: assembler or a #define in C) only exists at compile-time; in the
                   6129: executable program the constant has been translated into an absolute
                   6130: number and, unless you are using a symbolic debugger, it's impossible to
                   6131: know what abstract thing that number represents. In Forth a constant has
1.44      crook    6132: an entry in the header space and remains there after the code that uses
                   6133: it has been defined. In fact, it must remain in the dictionary since it
                   6134: has run-time duties to perform. For example:
1.29      crook    6135: 
                   6136: @example
                   6137: 12 Constant INCHES-PER-FOOT
                   6138: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   6139: @end example
                   6140: 
                   6141: @cindex in-lining of constants
                   6142: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   6143: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   6144: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   6145: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   6146: attempt to optimise constants by in-lining them where they are used. You
                   6147: can force Gforth to in-line a constant like this:
                   6148: 
                   6149: @example
                   6150: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   6151: @end example
                   6152: 
                   6153: If you use @code{see} to decompile @i{this} version of
                   6154: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49      anton    6155: longer present. To understand how this works, read
                   6156: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29      crook    6157: 
                   6158: In-lining constants in this way might improve execution time
                   6159: fractionally, and can ensure that a constant is now only referenced at
                   6160: compile-time. However, the definition of the constant still remains in
                   6161: the dictionary. Some Forth compilers provide a mechanism for controlling
                   6162: a second dictionary for holding transient words such that this second
                   6163: dictionary can be deleted later in order to recover memory
                   6164: space. However, there is no standard way of doing this.
                   6165: 
                   6166: 
1.44      crook    6167: @node Values, Colon Definitions, Constants, Defining Words
                   6168: @subsection Values
                   6169: @cindex values
1.34      anton    6170: 
1.69      anton    6171: A @code{Value} behaves like a @code{Constant}, but it can be changed.
                   6172: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
                   6173: (not in ANS Forth) you can access (and change) a @code{value} also with
                   6174: @code{>body}.
                   6175: 
                   6176: Here are some
                   6177: examples:
1.29      crook    6178: 
                   6179: @example
1.69      anton    6180: 12 Value APPLES     \ Define APPLES with an initial value of 12
                   6181: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
                   6182: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
                   6183: APPLES              \ puts 35 on the top of the stack.
1.29      crook    6184: @end example
                   6185: 
1.44      crook    6186: doc-value
                   6187: doc-to
1.29      crook    6188: 
1.35      anton    6189: 
1.69      anton    6190: 
1.44      crook    6191: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
                   6192: @subsection Colon Definitions
                   6193: @cindex colon definitions
1.35      anton    6194: 
                   6195: @example
1.44      crook    6196: : name ( ... -- ... )
                   6197:     word1 word2 word3 ;
1.29      crook    6198: @end example
                   6199: 
1.44      crook    6200: @noindent
                   6201: Creates a word called @code{name} that, upon execution, executes
                   6202: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29      crook    6203: 
1.49      anton    6204: The explanation above is somewhat superficial. For simple examples of
                   6205: colon definitions see @ref{Your first definition}.  For an in-depth
1.66      anton    6206: discussion of some of the issues involved, @xref{Interpretation and
1.49      anton    6207: Compilation Semantics}.
1.29      crook    6208: 
1.44      crook    6209: doc-:
                   6210: doc-;
1.1       anton    6211: 
1.34      anton    6212: 
1.69      anton    6213: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44      crook    6214: @subsection Anonymous Definitions
                   6215: @cindex colon definitions
                   6216: @cindex defining words without name
1.34      anton    6217: 
1.44      crook    6218: Sometimes you want to define an @dfn{anonymous word}; a word without a
                   6219: name. You can do this with:
1.1       anton    6220: 
1.44      crook    6221: doc-:noname
1.1       anton    6222: 
1.44      crook    6223: This leaves the execution token for the word on the stack after the
                   6224: closing @code{;}. Here's an example in which a deferred word is
                   6225: initialised with an @code{xt} from an anonymous colon definition:
1.1       anton    6226: 
1.29      crook    6227: @example
1.44      crook    6228: Defer deferred
                   6229: :noname ( ... -- ... )
                   6230:   ... ;
                   6231: IS deferred
1.29      crook    6232: @end example
1.26      crook    6233: 
1.44      crook    6234: @noindent
                   6235: Gforth provides an alternative way of doing this, using two separate
                   6236: words:
1.27      crook    6237: 
1.44      crook    6238: doc-noname
                   6239: @cindex execution token of last defined word
1.116     anton    6240: doc-latestxt
1.1       anton    6241: 
1.44      crook    6242: @noindent
                   6243: The previous example can be rewritten using @code{noname} and
1.116     anton    6244: @code{latestxt}:
1.1       anton    6245: 
1.26      crook    6246: @example
1.44      crook    6247: Defer deferred
                   6248: noname : ( ... -- ... )
                   6249:   ... ;
1.116     anton    6250: latestxt IS deferred
1.26      crook    6251: @end example
1.1       anton    6252: 
1.29      crook    6253: @noindent
1.44      crook    6254: @code{noname} works with any defining word, not just @code{:}.
                   6255: 
1.116     anton    6256: @code{latestxt} also works when the last word was not defined as
1.71      anton    6257: @code{noname}.  It does not work for combined words, though.  It also has
                   6258: the useful property that is is valid as soon as the header for a
                   6259: definition has been built. Thus:
1.44      crook    6260: 
                   6261: @example
1.116     anton    6262: latestxt . : foo [ latestxt . ] ; ' foo .
1.44      crook    6263: @end example
1.1       anton    6264: 
1.44      crook    6265: @noindent
                   6266: prints 3 numbers; the last two are the same.
1.26      crook    6267: 
1.69      anton    6268: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
                   6269: @subsection Supplying the name of a defined word
                   6270: @cindex names for defined words
                   6271: @cindex defining words, name given in a string
                   6272: 
                   6273: By default, a defining word takes the name for the defined word from the
                   6274: input stream. Sometimes you want to supply the name from a string. You
                   6275: can do this with:
                   6276: 
                   6277: doc-nextname
                   6278: 
                   6279: For example:
                   6280: 
                   6281: @example
                   6282: s" foo" nextname create
                   6283: @end example
                   6284: 
                   6285: @noindent
                   6286: is equivalent to:
                   6287: 
                   6288: @example
                   6289: create foo
                   6290: @end example
                   6291: 
                   6292: @noindent
                   6293: @code{nextname} works with any defining word.
                   6294: 
1.1       anton    6295: 
1.170     pazsan   6296: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26      crook    6297: @subsection User-defined Defining Words
                   6298: @cindex user-defined defining words
                   6299: @cindex defining words, user-defined
1.1       anton    6300: 
1.29      crook    6301: You can create a new defining word by wrapping defining-time code around
                   6302: an existing defining word and putting the sequence in a colon
1.69      anton    6303: definition. 
                   6304: 
                   6305: @c anton: This example is very complex and leads in a quite different
                   6306: @c direction from the CREATE-DOES> stuff that follows.  It should probably
                   6307: @c be done elsewhere, or as a subsubsection of this subsection (or as a
                   6308: @c subsection of Defining Words)
                   6309: 
                   6310: For example, suppose that you have a word @code{stats} that
1.29      crook    6311: gathers statistics about colon definitions given the @i{xt} of the
                   6312: definition, and you want every colon definition in your application to
                   6313: make a call to @code{stats}. You can define and use a new version of
                   6314: @code{:} like this:
                   6315: 
                   6316: @example
                   6317: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   6318:   ... ;  \ other code
                   6319: 
1.116     anton    6320: : my: : latestxt postpone literal ['] stats compile, ;
1.29      crook    6321: 
                   6322: my: foo + - ;
                   6323: @end example
                   6324: 
                   6325: When @code{foo} is defined using @code{my:} these steps occur:
                   6326: 
                   6327: @itemize @bullet
                   6328: @item
                   6329: @code{my:} is executed.
                   6330: @item
                   6331: The @code{:} within the definition (the one between @code{my:} and
1.116     anton    6332: @code{latestxt}) is executed, and does just what it always does; it parses
1.29      crook    6333: the input stream for a name, builds a dictionary header for the name
                   6334: @code{foo} and switches @code{state} from interpret to compile.
                   6335: @item
1.116     anton    6336: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29      crook    6337: being defined -- @code{foo} -- onto the stack.
                   6338: @item
                   6339: The code that was produced by @code{postpone literal} is executed; this
                   6340: causes the value on the stack to be compiled as a literal in the code
                   6341: area of @code{foo}.
                   6342: @item
                   6343: The code @code{['] stats} compiles a literal into the definition of
                   6344: @code{my:}. When @code{compile,} is executed, that literal -- the
                   6345: execution token for @code{stats} -- is layed down in the code area of
                   6346: @code{foo} , following the literal@footnote{Strictly speaking, the
                   6347: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   6348: in the code area is implementation-dependent. A threaded implementation
                   6349: might spit out the execution token directly whilst another
                   6350: implementation might spit out a native code sequence.}.
                   6351: @item
                   6352: At this point, the execution of @code{my:} is complete, and control
                   6353: returns to the text interpreter. The text interpreter is in compile
                   6354: state, so subsequent text @code{+ -} is compiled into the definition of
                   6355: @code{foo} and the @code{;} terminates the definition as always.
                   6356: @end itemize
                   6357: 
                   6358: You can use @code{see} to decompile a word that was defined using
                   6359: @code{my:} and see how it is different from a normal @code{:}
                   6360: definition. For example:
                   6361: 
                   6362: @example
                   6363: : bar + - ;  \ like foo but using : rather than my:
                   6364: see bar
                   6365: : bar
                   6366:   + - ;
                   6367: see foo
                   6368: : foo
                   6369:   107645672 stats + - ;
                   6370: 
1.140     anton    6371: \ use ' foo . to show that 107645672 is the xt for foo
1.29      crook    6372: @end example
                   6373: 
                   6374: You can use techniques like this to make new defining words in terms of
                   6375: @i{any} existing defining word.
1.1       anton    6376: 
                   6377: 
1.29      crook    6378: @cindex defining defining words
1.26      crook    6379: @cindex @code{CREATE} ... @code{DOES>}
                   6380: If you want the words defined with your defining words to behave
                   6381: differently from words defined with standard defining words, you can
                   6382: write your defining word like this:
1.1       anton    6383: 
                   6384: @example
1.26      crook    6385: : def-word ( "name" -- )
1.29      crook    6386:     CREATE @i{code1}
1.26      crook    6387: DOES> ( ... -- ... )
1.29      crook    6388:     @i{code2} ;
1.26      crook    6389: 
                   6390: def-word name
1.1       anton    6391: @end example
                   6392: 
1.29      crook    6393: @cindex child words
                   6394: This fragment defines a @dfn{defining word} @code{def-word} and then
                   6395: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   6396: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   6397: is not executed at this time. The word @code{name} is sometimes called a
                   6398: @dfn{child} of @code{def-word}.
                   6399: 
                   6400: When you execute @code{name}, the address of the body of @code{name} is
                   6401: put on the data stack and @i{code2} is executed (the address of the body
                   6402: of @code{name} is the address @code{HERE} returns immediately after the
1.69      anton    6403: @code{CREATE}, i.e., the address a @code{create}d word returns by
                   6404: default).
                   6405: 
                   6406: @c anton:
                   6407: @c www.dictionary.com says:
                   6408: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
                   6409: @c several generations of absence, usually caused by the chance
                   6410: @c recombination of genes.  2.An individual or a part that exhibits
                   6411: @c atavism. Also called throwback.  3.The return of a trait or recurrence
                   6412: @c of previous behavior after a period of absence.
                   6413: @c
                   6414: @c Doesn't seem to fit.
1.29      crook    6415: 
1.69      anton    6416: @c @cindex atavism in child words
1.33      anton    6417: You can use @code{def-word} to define a set of child words that behave
1.69      anton    6418: similarly; they all have a common run-time behaviour determined by
                   6419: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
                   6420: body of the child word. The structure of the data is common to all
                   6421: children of @code{def-word}, but the data values are specific -- and
                   6422: private -- to each child word. When a child word is executed, the
                   6423: address of its private data area is passed as a parameter on TOS to be
                   6424: used and manipulated@footnote{It is legitimate both to read and write to
                   6425: this data area.} by @i{code2}.
1.29      crook    6426: 
                   6427: The two fragments of code that make up the defining words act (are
                   6428: executed) at two completely separate times:
1.1       anton    6429: 
1.29      crook    6430: @itemize @bullet
                   6431: @item
                   6432: At @i{define time}, the defining word executes @i{code1} to generate a
                   6433: child word
                   6434: @item
                   6435: At @i{child execution time}, when a child word is invoked, @i{code2}
                   6436: is executed, using parameters (data) that are private and specific to
                   6437: the child word.
                   6438: @end itemize
                   6439: 
1.44      crook    6440: Another way of understanding the behaviour of @code{def-word} and
                   6441: @code{name} is to say that, if you make the following definitions:
1.33      anton    6442: @example
                   6443: : def-word1 ( "name" -- )
                   6444:     CREATE @i{code1} ;
                   6445: 
                   6446: : action1 ( ... -- ... )
                   6447:     @i{code2} ;
                   6448: 
                   6449: def-word1 name1
                   6450: @end example
                   6451: 
1.44      crook    6452: @noindent
                   6453: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    6454: 
1.29      crook    6455: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    6456: 
1.1       anton    6457: @example
1.29      crook    6458: : CONSTANT ( w "name" -- )
                   6459:     CREATE ,
1.26      crook    6460: DOES> ( -- w )
                   6461:     @@ ;
1.1       anton    6462: @end example
                   6463: 
1.29      crook    6464: @comment There is a beautiful description of how this works and what
                   6465: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   6466: @comment commentary on the Counting Fruits problem.
                   6467: 
                   6468: When you create a constant with @code{5 CONSTANT five}, a set of
                   6469: define-time actions take place; first a new word @code{five} is created,
                   6470: then the value 5 is laid down in the body of @code{five} with
1.44      crook    6471: @code{,}. When @code{five} is executed, the address of the body is put on
1.29      crook    6472: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   6473: no code of its own; it simply contains a data field and a pointer to the
                   6474: code that follows @code{DOES>} in its defining word. That makes words
                   6475: created in this way very compact.
                   6476: 
                   6477: The final example in this section is intended to remind you that space
                   6478: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   6479: both read and written by a Standard program@footnote{Exercise: use this
                   6480: example as a starting point for your own implementation of @code{Value}
                   6481: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   6482: @code{[']}.}:
                   6483: 
                   6484: @example
                   6485: : foo ( "name" -- )
                   6486:     CREATE -1 ,
                   6487: DOES> ( -- )
1.33      anton    6488:     @@ . ;
1.29      crook    6489: 
                   6490: foo first-word
                   6491: foo second-word
                   6492: 
                   6493: 123 ' first-word >BODY !
                   6494: @end example
                   6495: 
                   6496: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   6497: have executed it to get the address of its data field. However, since it
                   6498: was defined to have @code{DOES>} actions, its execution semantics are to
                   6499: perform those @code{DOES>} actions. To get the address of its data field
                   6500: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   6501: translate the xt into the address of the data field.  When you execute
                   6502: @code{first-word}, it will display @code{123}. When you execute
                   6503: @code{second-word} it will display @code{-1}.
1.26      crook    6504: 
                   6505: @cindex stack effect of @code{DOES>}-parts
                   6506: @cindex @code{DOES>}-parts, stack effect
1.29      crook    6507: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    6508: the stack effect of the defined words, not the stack effect of the
                   6509: following code (the following code expects the address of the body on
                   6510: the top of stack, which is not reflected in the stack comment). This is
                   6511: the convention that I use and recommend (it clashes a bit with using
                   6512: locals declarations for stack effect specification, though).
1.1       anton    6513: 
1.53      anton    6514: @menu
                   6515: * CREATE..DOES> applications::  
                   6516: * CREATE..DOES> details::       
1.63      anton    6517: * Advanced does> usage example::  
1.155     anton    6518: * Const-does>::                 
1.53      anton    6519: @end menu
                   6520: 
                   6521: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26      crook    6522: @subsubsection Applications of @code{CREATE..DOES>}
                   6523: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    6524: 
1.26      crook    6525: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    6526: 
1.26      crook    6527: @cindex factoring similar colon definitions
                   6528: When you see a sequence of code occurring several times, and you can
                   6529: identify a meaning, you will factor it out as a colon definition. When
                   6530: you see similar colon definitions, you can factor them using
                   6531: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   6532: that look very similar:
1.1       anton    6533: @example
1.26      crook    6534: : ori, ( reg-target reg-source n -- )
                   6535:     0 asm-reg-reg-imm ;
                   6536: : andi, ( reg-target reg-source n -- )
                   6537:     1 asm-reg-reg-imm ;
1.1       anton    6538: @end example
                   6539: 
1.26      crook    6540: @noindent
                   6541: This could be factored with:
                   6542: @example
                   6543: : reg-reg-imm ( op-code -- )
                   6544:     CREATE ,
                   6545: DOES> ( reg-target reg-source n -- )
                   6546:     @@ asm-reg-reg-imm ;
                   6547: 
                   6548: 0 reg-reg-imm ori,
                   6549: 1 reg-reg-imm andi,
                   6550: @end example
1.1       anton    6551: 
1.26      crook    6552: @cindex currying
                   6553: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   6554: supply a part of the parameters for a word (known as @dfn{currying} in
                   6555: the functional language community). E.g., @code{+} needs two
                   6556: parameters. Creating versions of @code{+} with one parameter fixed can
                   6557: be done like this:
1.82      anton    6558: 
1.1       anton    6559: @example
1.82      anton    6560: : curry+ ( n1 "name" -- )
1.26      crook    6561:     CREATE ,
                   6562: DOES> ( n2 -- n1+n2 )
                   6563:     @@ + ;
                   6564: 
                   6565:  3 curry+ 3+
                   6566: -2 curry+ 2-
1.1       anton    6567: @end example
                   6568: 
1.91      anton    6569: 
1.63      anton    6570: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26      crook    6571: @subsubsection The gory details of @code{CREATE..DOES>}
                   6572: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    6573: 
1.26      crook    6574: doc-does>
1.1       anton    6575: 
1.26      crook    6576: @cindex @code{DOES>} in a separate definition
                   6577: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   6578: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    6579: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    6580: @example
                   6581: : does1 
                   6582: DOES> ( ... -- ... )
1.44      crook    6583:     ... ;
                   6584: 
                   6585: : does2
                   6586: DOES> ( ... -- ... )
                   6587:     ... ;
                   6588: 
                   6589: : def-word ( ... -- ... )
                   6590:     create ...
                   6591:     IF
                   6592:        does1
                   6593:     ELSE
                   6594:        does2
                   6595:     ENDIF ;
                   6596: @end example
                   6597: 
                   6598: In this example, the selection of whether to use @code{does1} or
1.69      anton    6599: @code{does2} is made at definition-time; at the time that the child word is
1.44      crook    6600: @code{CREATE}d.
                   6601: 
                   6602: @cindex @code{DOES>} in interpretation state
                   6603: In a standard program you can apply a @code{DOES>}-part only if the last
                   6604: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   6605: will override the behaviour of the last word defined in any case. In a
                   6606: standard program, you can use @code{DOES>} only in a colon
                   6607: definition. In Gforth, you can also use it in interpretation state, in a
                   6608: kind of one-shot mode; for example:
                   6609: @example
                   6610: CREATE name ( ... -- ... )
                   6611:   @i{initialization}
                   6612: DOES>
                   6613:   @i{code} ;
                   6614: @end example
                   6615: 
                   6616: @noindent
                   6617: is equivalent to the standard:
                   6618: @example
                   6619: :noname
                   6620: DOES>
                   6621:     @i{code} ;
                   6622: CREATE name EXECUTE ( ... -- ... )
                   6623:     @i{initialization}
                   6624: @end example
                   6625: 
1.53      anton    6626: doc->body
                   6627: 
1.152     pazsan   6628: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63      anton    6629: @subsubsection Advanced does> usage example
                   6630: 
                   6631: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
                   6632: for disassembling instructions, that follow a very repetetive scheme:
                   6633: 
                   6634: @example
                   6635: :noname @var{disasm-operands} s" @var{inst-name}" type ;
                   6636: @var{entry-num} cells @var{table} + !
                   6637: @end example
                   6638: 
                   6639: Of course, this inspires the idea to factor out the commonalities to
                   6640: allow a definition like
                   6641: 
                   6642: @example
                   6643: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
                   6644: @end example
                   6645: 
                   6646: The parameters @var{disasm-operands} and @var{table} are usually
1.69      anton    6647: correlated.  Moreover, before I wrote the disassembler, there already
                   6648: existed code that defines instructions like this:
1.63      anton    6649: 
                   6650: @example
                   6651: @var{entry-num} @var{inst-format} @var{inst-name}
                   6652: @end example
                   6653: 
                   6654: This code comes from the assembler and resides in
                   6655: @file{arch/mips/insts.fs}.
                   6656: 
                   6657: So I had to define the @var{inst-format} words that performed the scheme
                   6658: above when executed.  At first I chose to use run-time code-generation:
                   6659: 
                   6660: @example
                   6661: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
                   6662:   :noname Postpone @var{disasm-operands}
                   6663:   name Postpone sliteral Postpone type Postpone ;
                   6664:   swap cells @var{table} + ! ;
                   6665: @end example
                   6666: 
                   6667: Note that this supplies the other two parameters of the scheme above.
1.44      crook    6668: 
1.63      anton    6669: An alternative would have been to write this using
                   6670: @code{create}/@code{does>}:
                   6671: 
                   6672: @example
                   6673: : @var{inst-format} ( entry-num "name" -- )
                   6674:   here name string, ( entry-num c-addr ) \ parse and save "name"
                   6675:   noname create , ( entry-num )
1.116     anton    6676:   latestxt swap cells @var{table} + !
1.63      anton    6677: does> ( addr w -- )
                   6678:   \ disassemble instruction w at addr
                   6679:   @@ >r 
                   6680:   @var{disasm-operands}
                   6681:   r> count type ;
                   6682: @end example
                   6683: 
                   6684: Somehow the first solution is simpler, mainly because it's simpler to
                   6685: shift a string from definition-time to use-time with @code{sliteral}
                   6686: than with @code{string,} and friends.
                   6687: 
                   6688: I wrote a lot of words following this scheme and soon thought about
                   6689: factoring out the commonalities among them.  Note that this uses a
                   6690: two-level defining word, i.e., a word that defines ordinary defining
                   6691: words.
                   6692: 
                   6693: This time a solution involving @code{postpone} and friends seemed more
                   6694: difficult (try it as an exercise), so I decided to use a
                   6695: @code{create}/@code{does>} word; since I was already at it, I also used
                   6696: @code{create}/@code{does>} for the lower level (try using
                   6697: @code{postpone} etc. as an exercise), resulting in the following
                   6698: definition:
                   6699: 
                   6700: @example
                   6701: : define-format ( disasm-xt table-xt -- )
                   6702:     \ define an instruction format that uses disasm-xt for
                   6703:     \ disassembling and enters the defined instructions into table
                   6704:     \ table-xt
                   6705:     create 2,
                   6706: does> ( u "inst" -- )
                   6707:     \ defines an anonymous word for disassembling instruction inst,
                   6708:     \ and enters it as u-th entry into table-xt
                   6709:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
                   6710:     noname create 2,      \ define anonymous word
1.116     anton    6711:     execute latestxt swap ! \ enter xt of defined word into table-xt
1.63      anton    6712: does> ( addr w -- )
                   6713:     \ disassemble instruction w at addr
                   6714:     2@@ >r ( addr w disasm-xt R: c-addr )
                   6715:     execute ( R: c-addr ) \ disassemble operands
                   6716:     r> count type ; \ print name 
                   6717: @end example
                   6718: 
                   6719: Note that the tables here (in contrast to above) do the @code{cells +}
                   6720: by themselves (that's why you have to pass an xt).  This word is used in
                   6721: the following way:
                   6722: 
                   6723: @example
                   6724: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
                   6725: @end example
                   6726: 
1.71      anton    6727: As shown above, the defined instruction format is then used like this:
                   6728: 
                   6729: @example
                   6730: @var{entry-num} @var{inst-format} @var{inst-name}
                   6731: @end example
                   6732: 
1.63      anton    6733: In terms of currying, this kind of two-level defining word provides the
                   6734: parameters in three stages: first @var{disasm-operands} and @var{table},
                   6735: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
                   6736: the instruction to be disassembled.  
                   6737: 
                   6738: Of course this did not quite fit all the instruction format names used
                   6739: in @file{insts.fs}, so I had to define a few wrappers that conditioned
                   6740: the parameters into the right form.
                   6741: 
                   6742: If you have trouble following this section, don't worry.  First, this is
                   6743: involved and takes time (and probably some playing around) to
                   6744: understand; second, this is the first two-level
                   6745: @code{create}/@code{does>} word I have written in seventeen years of
                   6746: Forth; and if I did not have @file{insts.fs} to start with, I may well
                   6747: have elected to use just a one-level defining word (with some repeating
                   6748: of parameters when using the defining word). So it is not necessary to
                   6749: understand this, but it may improve your understanding of Forth.
1.44      crook    6750: 
                   6751: 
1.152     pazsan   6752: @node Const-does>,  , Advanced does> usage example, User-defined Defining Words
1.91      anton    6753: @subsubsection @code{Const-does>}
                   6754: 
                   6755: A frequent use of @code{create}...@code{does>} is for transferring some
                   6756: values from definition-time to run-time.  Gforth supports this use with
                   6757: 
                   6758: doc-const-does>
                   6759: 
                   6760: A typical use of this word is:
                   6761: 
                   6762: @example
                   6763: : curry+ ( n1 "name" -- )
                   6764: 1 0 CONST-DOES> ( n2 -- n1+n2 )
                   6765:     + ;
                   6766: 
                   6767: 3 curry+ 3+
                   6768: @end example
                   6769: 
                   6770: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
                   6771: definition to run-time.
                   6772: 
                   6773: The advantages of using @code{const-does>} are:
                   6774: 
                   6775: @itemize
                   6776: 
                   6777: @item
                   6778: You don't have to deal with storing and retrieving the values, i.e.,
                   6779: your program becomes more writable and readable.
                   6780: 
                   6781: @item
                   6782: When using @code{does>}, you have to introduce a @code{@@} that cannot
                   6783: be optimized away (because you could change the data using
                   6784: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
                   6785: 
                   6786: @end itemize
                   6787: 
                   6788: An ANS Forth implementation of @code{const-does>} is available in
                   6789: @file{compat/const-does.fs}.
                   6790: 
                   6791: 
1.170     pazsan   6792: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
                   6793: @subsection Deferred Words
1.44      crook    6794: @cindex deferred words
                   6795: 
                   6796: The defining word @code{Defer} allows you to define a word by name
                   6797: without defining its behaviour; the definition of its behaviour is
                   6798: deferred. Here are two situation where this can be useful:
                   6799: 
                   6800: @itemize @bullet
                   6801: @item
                   6802: Where you want to allow the behaviour of a word to be altered later, and
                   6803: for all precompiled references to the word to change when its behaviour
                   6804: is changed.
                   6805: @item
                   6806: For mutual recursion; @xref{Calls and returns}.
                   6807: @end itemize
                   6808: 
                   6809: In the following example, @code{foo} always invokes the version of
                   6810: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
                   6811: always invokes the version that prints ``@code{Hello}''. There is no way
                   6812: of getting @code{foo} to use the later version without re-ordering the
                   6813: source code and recompiling it.
                   6814: 
                   6815: @example
                   6816: : greet ." Good morning" ;
                   6817: : foo ... greet ... ;
                   6818: : greet ." Hello" ;
                   6819: : bar ... greet ... ;
                   6820: @end example
                   6821: 
                   6822: This problem can be solved by defining @code{greet} as a @code{Defer}red
                   6823: word. The behaviour of a @code{Defer}red word can be defined and
                   6824: redefined at any time by using @code{IS} to associate the xt of a
                   6825: previously-defined word with it. The previous example becomes:
                   6826: 
                   6827: @example
1.69      anton    6828: Defer greet ( -- )
1.44      crook    6829: : foo ... greet ... ;
                   6830: : bar ... greet ... ;
1.69      anton    6831: : greet1 ( -- ) ." Good morning" ;
                   6832: : greet2 ( -- ) ." Hello" ;
1.132     anton    6833: ' greet2 IS greet  \ make greet behave like greet2
1.44      crook    6834: @end example
                   6835: 
1.69      anton    6836: @progstyle
                   6837: You should write a stack comment for every deferred word, and put only
                   6838: XTs into deferred words that conform to this stack effect.  Otherwise
                   6839: it's too difficult to use the deferred word.
                   6840: 
1.44      crook    6841: A deferred word can be used to improve the statistics-gathering example
                   6842: from @ref{User-defined Defining Words}; rather than edit the
                   6843: application's source code to change every @code{:} to a @code{my:}, do
                   6844: this:
                   6845: 
                   6846: @example
                   6847: : real: : ;     \ retain access to the original
                   6848: defer :         \ redefine as a deferred word
1.132     anton    6849: ' my: IS :      \ use special version of :
1.44      crook    6850: \
                   6851: \ load application here
                   6852: \
1.132     anton    6853: ' real: IS :    \ go back to the original
1.44      crook    6854: @end example
                   6855: 
                   6856: 
1.132     anton    6857: One thing to note is that @code{IS} has special compilation semantics,
                   6858: such that it parses the name at compile time (like @code{TO}):
1.44      crook    6859: 
                   6860: @example
                   6861: : set-greet ( xt -- )
1.132     anton    6862:   IS greet ;
1.44      crook    6863: 
                   6864: ' greet1 set-greet
                   6865: @end example
                   6866: 
1.132     anton    6867: In situations where @code{IS} does not fit, use @code{defer!} instead.
                   6868: 
1.69      anton    6869: A deferred word can only inherit execution semantics from the xt
                   6870: (because that is all that an xt can represent -- for more discussion of
                   6871: this @pxref{Tokens for Words}); by default it will have default
                   6872: interpretation and compilation semantics deriving from this execution
                   6873: semantics.  However, you can change the interpretation and compilation
                   6874: semantics of the deferred word in the usual ways:
1.44      crook    6875: 
                   6876: @example
1.132     anton    6877: : bar .... ; immediate
1.44      crook    6878: Defer fred immediate
                   6879: Defer jim
                   6880: 
1.132     anton    6881: ' bar IS jim  \ jim has default semantics
                   6882: ' bar IS fred \ fred is immediate
1.44      crook    6883: @end example
                   6884: 
                   6885: doc-defer
1.132     anton    6886: doc-defer!
1.44      crook    6887: doc-is
1.132     anton    6888: doc-defer@
                   6889: doc-action-of
1.44      crook    6890: @comment TODO document these: what's defers [is]
                   6891: doc-defers
                   6892: 
                   6893: @c Use @code{words-deferred} to see a list of deferred words.
                   6894: 
1.132     anton    6895: Definitions of these words (except @code{defers}) in ANS Forth are
                   6896: provided in @file{compat/defer.fs}.
1.44      crook    6897: 
                   6898: 
1.170     pazsan   6899: @node Aliases,  , Deferred Words, Defining Words
1.44      crook    6900: @subsection Aliases
                   6901: @cindex aliases
1.1       anton    6902: 
1.44      crook    6903: The defining word @code{Alias} allows you to define a word by name that
                   6904: has the same behaviour as some other word. Here are two situation where
                   6905: this can be useful:
1.1       anton    6906: 
1.44      crook    6907: @itemize @bullet
                   6908: @item
                   6909: When you want access to a word's definition from a different word list
                   6910: (for an example of this, see the definition of the @code{Root} word list
                   6911: in the Gforth source).
                   6912: @item
                   6913: When you want to create a synonym; a definition that can be known by
                   6914: either of two names (for example, @code{THEN} and @code{ENDIF} are
                   6915: aliases).
                   6916: @end itemize
1.1       anton    6917: 
1.69      anton    6918: Like deferred words, an alias has default compilation and interpretation
                   6919: semantics at the beginning (not the modifications of the other word),
                   6920: but you can change them in the usual ways (@code{immediate},
                   6921: @code{compile-only}). For example:
1.1       anton    6922: 
                   6923: @example
1.44      crook    6924: : foo ... ; immediate
                   6925: 
                   6926: ' foo Alias bar \ bar is not an immediate word
                   6927: ' foo Alias fooby immediate \ fooby is an immediate word
1.1       anton    6928: @end example
                   6929: 
1.44      crook    6930: Words that are aliases have the same xt, different headers in the
                   6931: dictionary, and consequently different name tokens (@pxref{Tokens for
                   6932: Words}) and possibly different immediate flags.  An alias can only have
                   6933: default or immediate compilation semantics; you can define aliases for
                   6934: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1       anton    6935: 
1.44      crook    6936: doc-alias
1.1       anton    6937: 
                   6938: 
1.47      crook    6939: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
                   6940: @section Interpretation and Compilation Semantics
1.26      crook    6941: @cindex semantics, interpretation and compilation
1.1       anton    6942: 
1.71      anton    6943: @c !! state and ' are used without explanation
                   6944: @c example for immediate/compile-only? or is the tutorial enough
                   6945: 
1.26      crook    6946: @cindex interpretation semantics
1.71      anton    6947: The @dfn{interpretation semantics} of a (named) word are what the text
1.26      crook    6948: interpreter does when it encounters the word in interpret state. It also
                   6949: appears in some other contexts, e.g., the execution token returned by
1.71      anton    6950: @code{' @i{word}} identifies the interpretation semantics of @i{word}
                   6951: (in other words, @code{' @i{word} execute} is equivalent to
1.29      crook    6952: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    6953: 
1.26      crook    6954: @cindex compilation semantics
1.71      anton    6955: The @dfn{compilation semantics} of a (named) word are what the text
                   6956: interpreter does when it encounters the word in compile state. It also
                   6957: appears in other contexts, e.g, @code{POSTPONE @i{word}}
                   6958: compiles@footnote{In standard terminology, ``appends to the current
                   6959: definition''.} the compilation semantics of @i{word}.
1.1       anton    6960: 
1.26      crook    6961: @cindex execution semantics
                   6962: The standard also talks about @dfn{execution semantics}. They are used
                   6963: only for defining the interpretation and compilation semantics of many
                   6964: words. By default, the interpretation semantics of a word are to
                   6965: @code{execute} its execution semantics, and the compilation semantics of
                   6966: a word are to @code{compile,} its execution semantics.@footnote{In
                   6967: standard terminology: The default interpretation semantics are its
                   6968: execution semantics; the default compilation semantics are to append its
                   6969: execution semantics to the execution semantics of the current
                   6970: definition.}
                   6971: 
1.71      anton    6972: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
                   6973: the text interpreter, ticked, or @code{postpone}d, so they have no
                   6974: interpretation or compilation semantics.  Their behaviour is represented
                   6975: by their XT (@pxref{Tokens for Words}), and we call it execution
                   6976: semantics, too.
                   6977: 
1.26      crook    6978: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   6979: 
                   6980: @cindex immediate words
                   6981: @cindex compile-only words
                   6982: You can change the semantics of the most-recently defined word:
                   6983: 
1.44      crook    6984: 
1.26      crook    6985: doc-immediate
                   6986: doc-compile-only
                   6987: doc-restrict
                   6988: 
1.82      anton    6989: By convention, words with non-default compilation semantics (e.g.,
                   6990: immediate words) often have names surrounded with brackets (e.g.,
                   6991: @code{[']}, @pxref{Execution token}).
1.44      crook    6992: 
1.26      crook    6993: Note that ticking (@code{'}) a compile-only word gives an error
                   6994: (``Interpreting a compile-only word'').
1.1       anton    6995: 
1.47      crook    6996: @menu
1.67      anton    6997: * Combined words::              
1.47      crook    6998: @end menu
1.44      crook    6999: 
1.71      anton    7000: 
1.48      anton    7001: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44      crook    7002: @subsection Combined Words
                   7003: @cindex combined words
                   7004: 
                   7005: Gforth allows you to define @dfn{combined words} -- words that have an
                   7006: arbitrary combination of interpretation and compilation semantics.
                   7007: 
1.26      crook    7008: doc-interpret/compile:
1.1       anton    7009: 
1.26      crook    7010: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   7011: recommend that you do not define such words, as cute as they may be:
                   7012: they make it hard to get at both parts of the word in some contexts.
                   7013: E.g., assume you want to get an execution token for the compilation
                   7014: part. Instead, define two words, one that embodies the interpretation
                   7015: part, and one that embodies the compilation part.  Once you have done
                   7016: that, you can define a combined word with @code{interpret/compile:} for
                   7017: the convenience of your users.
1.1       anton    7018: 
1.26      crook    7019: You might try to use this feature to provide an optimizing
                   7020: implementation of the default compilation semantics of a word. For
                   7021: example, by defining:
1.1       anton    7022: @example
1.26      crook    7023: :noname
                   7024:    foo bar ;
                   7025: :noname
                   7026:    POSTPONE foo POSTPONE bar ;
1.29      crook    7027: interpret/compile: opti-foobar
1.1       anton    7028: @end example
1.26      crook    7029: 
1.23      crook    7030: @noindent
1.26      crook    7031: as an optimizing version of:
                   7032: 
1.1       anton    7033: @example
1.26      crook    7034: : foobar
                   7035:     foo bar ;
1.1       anton    7036: @end example
                   7037: 
1.26      crook    7038: Unfortunately, this does not work correctly with @code{[compile]},
                   7039: because @code{[compile]} assumes that the compilation semantics of all
                   7040: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    7041: opti-foobar} would compile compilation semantics, whereas
                   7042: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    7043: 
1.26      crook    7044: @cindex state-smart words (are a bad idea)
1.82      anton    7045: @anchor{state-smartness}
1.29      crook    7046: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    7047: by @code{interpret/compile:} (words are state-smart if they check
                   7048: @code{STATE} during execution). E.g., they would try to code
                   7049: @code{foobar} like this:
1.1       anton    7050: 
1.26      crook    7051: @example
                   7052: : foobar
                   7053:   STATE @@
                   7054:   IF ( compilation state )
                   7055:     POSTPONE foo POSTPONE bar
                   7056:   ELSE
                   7057:     foo bar
                   7058:   ENDIF ; immediate
                   7059: @end example
1.1       anton    7060: 
1.26      crook    7061: Although this works if @code{foobar} is only processed by the text
                   7062: interpreter, it does not work in other contexts (like @code{'} or
                   7063: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   7064: for a state-smart word, not for the interpretation semantics of the
                   7065: original @code{foobar}; when you execute this execution token (directly
                   7066: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   7067: state, the result will not be what you expected (i.e., it will not
                   7068: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   7069: write them@footnote{For a more detailed discussion of this topic, see
1.66      anton    7070: M. Anton Ertl,
                   7071: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
                   7072: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1       anton    7073: 
1.26      crook    7074: @cindex defining words with arbitrary semantics combinations
                   7075: It is also possible to write defining words that define words with
                   7076: arbitrary combinations of interpretation and compilation semantics. In
                   7077: general, they look like this:
1.1       anton    7078: 
1.26      crook    7079: @example
                   7080: : def-word
                   7081:     create-interpret/compile
1.29      crook    7082:     @i{code1}
1.26      crook    7083: interpretation>
1.29      crook    7084:     @i{code2}
1.26      crook    7085: <interpretation
                   7086: compilation>
1.29      crook    7087:     @i{code3}
1.26      crook    7088: <compilation ;
                   7089: @end example
1.1       anton    7090: 
1.29      crook    7091: For a @i{word} defined with @code{def-word}, the interpretation
                   7092: semantics are to push the address of the body of @i{word} and perform
                   7093: @i{code2}, and the compilation semantics are to push the address of
                   7094: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    7095: can also be defined like this (except that the defined constants don't
                   7096: behave correctly when @code{[compile]}d):
1.1       anton    7097: 
1.26      crook    7098: @example
                   7099: : constant ( n "name" -- )
                   7100:     create-interpret/compile
                   7101:     ,
                   7102: interpretation> ( -- n )
                   7103:     @@
                   7104: <interpretation
                   7105: compilation> ( compilation. -- ; run-time. -- n )
                   7106:     @@ postpone literal
                   7107: <compilation ;
                   7108: @end example
1.1       anton    7109: 
1.44      crook    7110: 
1.26      crook    7111: doc-create-interpret/compile
                   7112: doc-interpretation>
                   7113: doc-<interpretation
                   7114: doc-compilation>
                   7115: doc-<compilation
1.1       anton    7116: 
1.44      crook    7117: 
1.29      crook    7118: Words defined with @code{interpret/compile:} and
1.26      crook    7119: @code{create-interpret/compile} have an extended header structure that
                   7120: differs from other words; however, unless you try to access them with
                   7121: plain address arithmetic, you should not notice this. Words for
                   7122: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    7123: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   7124: with @code{create-interpret/compile}.
1.1       anton    7125: 
1.44      crook    7126: 
1.47      crook    7127: @c -------------------------------------------------------------
1.81      anton    7128: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47      crook    7129: @section Tokens for Words
                   7130: @cindex tokens for words
                   7131: 
                   7132: This section describes the creation and use of tokens that represent
                   7133: words.
                   7134: 
1.71      anton    7135: @menu
                   7136: * Execution token::             represents execution/interpretation semantics
                   7137: * Compilation token::           represents compilation semantics
                   7138: * Name token::                  represents named words
                   7139: @end menu
1.47      crook    7140: 
1.71      anton    7141: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
                   7142: @subsection Execution token
1.47      crook    7143: 
                   7144: @cindex xt
                   7145: @cindex execution token
1.71      anton    7146: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
                   7147: You can use @code{execute} to invoke this behaviour.
1.47      crook    7148: 
1.71      anton    7149: @cindex tick (')
                   7150: You can use @code{'} to get an execution token that represents the
                   7151: interpretation semantics of a named word:
1.47      crook    7152: 
                   7153: @example
1.97      anton    7154: 5 ' .   ( n xt ) 
                   7155: execute ( )      \ execute the xt (i.e., ".")
1.71      anton    7156: @end example
1.47      crook    7157: 
1.71      anton    7158: doc-'
                   7159: 
                   7160: @code{'} parses at run-time; there is also a word @code{[']} that parses
                   7161: when it is compiled, and compiles the resulting XT:
                   7162: 
                   7163: @example
                   7164: : foo ['] . execute ;
                   7165: 5 foo
                   7166: : bar ' execute ; \ by contrast,
                   7167: 5 bar .           \ ' parses "." when bar executes
                   7168: @end example
                   7169: 
                   7170: doc-[']
                   7171: 
                   7172: If you want the execution token of @i{word}, write @code{['] @i{word}}
                   7173: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
                   7174: @code{'} and @code{[']} behave somewhat unusually by complaining about
                   7175: compile-only words (because these words have no interpretation
                   7176: semantics).  You might get what you want by using @code{COMP' @i{word}
                   7177: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
                   7178: token}).
                   7179: 
1.116     anton    7180: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71      anton    7181: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
                   7182: for the only behaviour the word has (the execution semantics).  For
1.116     anton    7183: named words, @code{latestxt} produces an XT for the same behaviour it
1.71      anton    7184: would produce if the word was defined anonymously.
                   7185: 
                   7186: @example
                   7187: :noname ." hello" ;
                   7188: execute
1.47      crook    7189: @end example
                   7190: 
1.71      anton    7191: An XT occupies one cell and can be manipulated like any other cell.
                   7192: 
1.47      crook    7193: @cindex code field address
                   7194: @cindex CFA
1.71      anton    7195: In ANS Forth the XT is just an abstract data type (i.e., defined by the
                   7196: operations that produce or consume it).  For old hands: In Gforth, the
                   7197: XT is implemented as a code field address (CFA).
                   7198: 
                   7199: doc-execute
                   7200: doc-perform
                   7201: 
                   7202: @node Compilation token, Name token, Execution token, Tokens for Words
                   7203: @subsection Compilation token
1.47      crook    7204: 
                   7205: @cindex compilation token
1.71      anton    7206: @cindex CT (compilation token)
                   7207: Gforth represents the compilation semantics of a named word by a
1.47      crook    7208: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   7209: @i{xt} is an execution token. The compilation semantics represented by
                   7210: the compilation token can be performed with @code{execute}, which
                   7211: consumes the whole compilation token, with an additional stack effect
                   7212: determined by the represented compilation semantics.
                   7213: 
                   7214: At present, the @i{w} part of a compilation token is an execution token,
                   7215: and the @i{xt} part represents either @code{execute} or
                   7216: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   7217: word. If the word has default compilation semantics, the @i{xt} will
                   7218: represent @code{compile,}. Otherwise (e.g., for immediate words), the
                   7219: @i{xt} will represent @code{execute}.}. However, don't rely on that
                   7220: knowledge, unless necessary; future versions of Gforth may introduce
                   7221: unusual compilation tokens (e.g., a compilation token that represents
                   7222: the compilation semantics of a literal).
                   7223: 
1.71      anton    7224: You can perform the compilation semantics represented by the compilation
                   7225: token with @code{execute}.  You can compile the compilation semantics
                   7226: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
                   7227: equivalent to @code{postpone @i{word}}.
                   7228: 
                   7229: doc-[comp']
                   7230: doc-comp'
                   7231: doc-postpone,
                   7232: 
                   7233: @node Name token,  , Compilation token, Tokens for Words
                   7234: @subsection Name token
1.47      crook    7235: 
                   7236: @cindex name token
1.116     anton    7237: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
                   7238: token is an abstract data type that occurs as argument or result of the
                   7239: words below.
                   7240: 
                   7241: @c !! put this elswhere?
1.47      crook    7242: @cindex name field address
                   7243: @cindex NFA
1.116     anton    7244: The closest thing to the nt in older Forth systems is the name field
                   7245: address (NFA), but there are significant differences: in older Forth
                   7246: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
                   7247: LFA, NFA, CFA, PFA) and there were words for getting from one to the
                   7248: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
                   7249: is a link field in the structure identified by the name token, but
                   7250: searching usually uses a hash table external to these structures; the
                   7251: name in Gforth has a cell-wide count-and-flags field, and the nt is not
                   7252: implemented as the address of that count field.
1.47      crook    7253: 
                   7254: doc-find-name
1.116     anton    7255: doc-latest
                   7256: doc->name
1.47      crook    7257: doc-name>int
                   7258: doc-name?int
                   7259: doc-name>comp
                   7260: doc-name>string
1.109     anton    7261: doc-id.
                   7262: doc-.name
                   7263: doc-.id
1.47      crook    7264: 
1.81      anton    7265: @c ----------------------------------------------------------
                   7266: @node Compiling words, The Text Interpreter, Tokens for Words, Words
                   7267: @section Compiling words
                   7268: @cindex compiling words
                   7269: @cindex macros
                   7270: 
                   7271: In contrast to most other languages, Forth has no strict boundary
1.82      anton    7272: between compilation and run-time.  E.g., you can run arbitrary code
                   7273: between defining words (or for computing data used by defining words
                   7274: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
                   7275: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
                   7276: running arbitrary code while compiling a colon definition (exception:
                   7277: you must not allot dictionary space).
                   7278: 
                   7279: @menu
                   7280: * Literals::                    Compiling data values
                   7281: * Macros::                      Compiling words
                   7282: @end menu
                   7283: 
                   7284: @node Literals, Macros, Compiling words, Compiling words
                   7285: @subsection Literals
                   7286: @cindex Literals
                   7287: 
                   7288: The simplest and most frequent example is to compute a literal during
                   7289: compilation.  E.g., the following definition prints an array of strings,
                   7290: one string per line:
                   7291: 
                   7292: @example
                   7293: : .strings ( addr u -- ) \ gforth
                   7294:     2* cells bounds U+DO
                   7295:        cr i 2@@ type
                   7296:     2 cells +LOOP ;  
                   7297: @end example
1.81      anton    7298: 
1.82      anton    7299: With a simple-minded compiler like Gforth's, this computes @code{2
                   7300: cells} on every loop iteration.  You can compute this value once and for
                   7301: all at compile time and compile it into the definition like this:
                   7302: 
                   7303: @example
                   7304: : .strings ( addr u -- ) \ gforth
                   7305:     2* cells bounds U+DO
                   7306:        cr i 2@@ type
                   7307:     [ 2 cells ] literal +LOOP ;  
                   7308: @end example
                   7309: 
                   7310: @code{[} switches the text interpreter to interpret state (you will get
                   7311: an @code{ok} prompt if you type this example interactively and insert a
                   7312: newline between @code{[} and @code{]}), so it performs the
                   7313: interpretation semantics of @code{2 cells}; this computes a number.
                   7314: @code{]} switches the text interpreter back into compile state.  It then
                   7315: performs @code{Literal}'s compilation semantics, which are to compile
                   7316: this number into the current word.  You can decompile the word with
                   7317: @code{see .strings} to see the effect on the compiled code.
1.81      anton    7318: 
1.82      anton    7319: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
                   7320: *} in this way.
1.81      anton    7321: 
1.82      anton    7322: doc-[
                   7323: doc-]
1.81      anton    7324: doc-literal
                   7325: doc-]L
1.82      anton    7326: 
                   7327: There are also words for compiling other data types than single cells as
                   7328: literals:
                   7329: 
1.81      anton    7330: doc-2literal
                   7331: doc-fliteral
1.82      anton    7332: doc-sliteral
                   7333: 
                   7334: @cindex colon-sys, passing data across @code{:}
                   7335: @cindex @code{:}, passing data across
                   7336: You might be tempted to pass data from outside a colon definition to the
                   7337: inside on the data stack.  This does not work, because @code{:} puhes a
                   7338: colon-sys, making stuff below unaccessible.  E.g., this does not work:
                   7339: 
                   7340: @example
                   7341: 5 : foo literal ; \ error: "unstructured"
                   7342: @end example
                   7343: 
                   7344: Instead, you have to pass the value in some other way, e.g., through a
                   7345: variable:
                   7346: 
                   7347: @example
                   7348: variable temp
                   7349: 5 temp !
                   7350: : foo [ temp @@ ] literal ;
                   7351: @end example
                   7352: 
                   7353: 
                   7354: @node Macros,  , Literals, Compiling words
                   7355: @subsection Macros
                   7356: @cindex Macros
                   7357: @cindex compiling compilation semantics
                   7358: 
                   7359: @code{Literal} and friends compile data values into the current
                   7360: definition.  You can also write words that compile other words into the
                   7361: current definition.  E.g.,
                   7362: 
                   7363: @example
                   7364: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
                   7365:   POSTPONE + ;
                   7366: 
                   7367: : foo ( n1 n2 -- n )
                   7368:   [ compile-+ ] ;
                   7369: 1 2 foo .
                   7370: @end example
                   7371: 
                   7372: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
                   7373: What happens in this example?  @code{Postpone} compiles the compilation
                   7374: semantics of @code{+} into @code{compile-+}; later the text interpreter
                   7375: executes @code{compile-+} and thus the compilation semantics of +, which
                   7376: compile (the execution semantics of) @code{+} into
                   7377: @code{foo}.@footnote{A recent RFI answer requires that compiling words
                   7378: should only be executed in compile state, so this example is not
                   7379: guaranteed to work on all standard systems, but on any decent system it
                   7380: will work.}
                   7381: 
                   7382: doc-postpone
                   7383: doc-[compile]
                   7384: 
                   7385: Compiling words like @code{compile-+} are usually immediate (or similar)
                   7386: so you do not have to switch to interpret state to execute them;
                   7387: mopifying the last example accordingly produces:
                   7388: 
                   7389: @example
                   7390: : [compile-+] ( compilation: --; interpretation: -- )
                   7391:   \ compiled code: ( n1 n2 -- n )
                   7392:   POSTPONE + ; immediate
                   7393: 
                   7394: : foo ( n1 n2 -- n )
                   7395:   [compile-+] ;
                   7396: 1 2 foo .
                   7397: @end example
                   7398: 
                   7399: Immediate compiling words are similar to macros in other languages (in
                   7400: particular, Lisp).  The important differences to macros in, e.g., C are:
                   7401: 
                   7402: @itemize @bullet
                   7403: 
                   7404: @item
                   7405: You use the same language for defining and processing macros, not a
                   7406: separate preprocessing language and processor.
                   7407: 
                   7408: @item
                   7409: Consequently, the full power of Forth is available in macro definitions.
                   7410: E.g., you can perform arbitrarily complex computations, or generate
                   7411: different code conditionally or in a loop (e.g., @pxref{Advanced macros
                   7412: Tutorial}).  This power is very useful when writing a parser generators
                   7413: or other code-generating software.
                   7414: 
                   7415: @item
                   7416: Macros defined using @code{postpone} etc. deal with the language at a
                   7417: higher level than strings; name binding happens at macro definition
                   7418: time, so you can avoid the pitfalls of name collisions that can happen
                   7419: in C macros.  Of course, Forth is a liberal language and also allows to
                   7420: shoot yourself in the foot with text-interpreted macros like
                   7421: 
                   7422: @example
                   7423: : [compile-+] s" +" evaluate ; immediate
                   7424: @end example
                   7425: 
                   7426: Apart from binding the name at macro use time, using @code{evaluate}
                   7427: also makes your definition @code{state}-smart (@pxref{state-smartness}).
                   7428: @end itemize
                   7429: 
                   7430: You may want the macro to compile a number into a word.  The word to do
                   7431: it is @code{literal}, but you have to @code{postpone} it, so its
                   7432: compilation semantics take effect when the macro is executed, not when
                   7433: it is compiled:
                   7434: 
                   7435: @example
                   7436: : [compile-5] ( -- ) \ compiled code: ( -- n )
                   7437:   5 POSTPONE literal ; immediate
                   7438: 
                   7439: : foo [compile-5] ;
                   7440: foo .
                   7441: @end example
                   7442: 
                   7443: You may want to pass parameters to a macro, that the macro should
                   7444: compile into the current definition.  If the parameter is a number, then
                   7445: you can use @code{postpone literal} (similar for other values).
                   7446: 
                   7447: If you want to pass a word that is to be compiled, the usual way is to
                   7448: pass an execution token and @code{compile,} it:
                   7449: 
                   7450: @example
                   7451: : twice1 ( xt -- ) \ compiled code: ... -- ...
                   7452:   dup compile, compile, ;
                   7453: 
                   7454: : 2+ ( n1 -- n2 )
                   7455:   [ ' 1+ twice1 ] ;
                   7456: @end example
                   7457: 
                   7458: doc-compile,
                   7459: 
                   7460: An alternative available in Gforth, that allows you to pass compile-only
                   7461: words as parameters is to use the compilation token (@pxref{Compilation
                   7462: token}).  The same example in this technique:
                   7463: 
                   7464: @example
                   7465: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
                   7466:   2dup 2>r execute 2r> execute ;
                   7467: 
                   7468: : 2+ ( n1 -- n2 )
                   7469:   [ comp' 1+ twice ] ;
                   7470: @end example
                   7471: 
                   7472: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
                   7473: works even if the executed compilation semantics has an effect on the
                   7474: data stack.
                   7475: 
                   7476: You can also define complete definitions with these words; this provides
                   7477: an alternative to using @code{does>} (@pxref{User-defined Defining
                   7478: Words}).  E.g., instead of
                   7479: 
                   7480: @example
                   7481: : curry+ ( n1 "name" -- )
                   7482:     CREATE ,
                   7483: DOES> ( n2 -- n1+n2 )
                   7484:     @@ + ;
                   7485: @end example
                   7486: 
                   7487: you could define
                   7488: 
                   7489: @example
                   7490: : curry+ ( n1 "name" -- )
                   7491:   \ name execution: ( n2 -- n1+n2 )
                   7492:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81      anton    7493: 
1.82      anton    7494: -3 curry+ 3-
                   7495: see 3-
                   7496: @end example
1.81      anton    7497: 
1.82      anton    7498: The sequence @code{>r : r>} is necessary, because @code{:} puts a
                   7499: colon-sys on the data stack that makes everything below it unaccessible.
1.81      anton    7500: 
1.82      anton    7501: This way of writing defining words is sometimes more, sometimes less
                   7502: convenient than using @code{does>} (@pxref{Advanced does> usage
                   7503: example}).  One advantage of this method is that it can be optimized
                   7504: better, because the compiler knows that the value compiled with
                   7505: @code{literal} is fixed, whereas the data associated with a
                   7506: @code{create}d word can be changed.
1.47      crook    7507: 
1.26      crook    7508: @c ----------------------------------------------------------
1.111     anton    7509: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26      crook    7510: @section  The Text Interpreter
                   7511: @cindex interpreter - outer
                   7512: @cindex text interpreter
                   7513: @cindex outer interpreter
1.1       anton    7514: 
1.34      anton    7515: @c Should we really describe all these ugly details?  IMO the text
                   7516: @c interpreter should be much cleaner, but that may not be possible within
                   7517: @c ANS Forth. - anton
1.44      crook    7518: @c nac-> I wanted to explain how it works to show how you can exploit
                   7519: @c it in your own programs. When I was writing a cross-compiler, figuring out
                   7520: @c some of these gory details was very helpful to me. None of the textbooks
                   7521: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
                   7522: @c seems to positively avoid going into too much detail for some of
                   7523: @c the internals.
1.34      anton    7524: 
1.71      anton    7525: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
                   7526: @c it is; for the ugly details, I would prefer another place.  I wonder
                   7527: @c whether we should have a chapter before "Words" that describes some
                   7528: @c basic concepts referred to in words, and a chapter after "Words" that
                   7529: @c describes implementation details.
                   7530: 
1.29      crook    7531: The text interpreter@footnote{This is an expanded version of the
                   7532: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34      anton    7533: that processes input from the current input device. It is also called
                   7534: the outer interpreter, in contrast to the inner interpreter
                   7535: (@pxref{Engine}) which executes the compiled Forth code on interpretive
                   7536: implementations.
1.27      crook    7537: 
1.29      crook    7538: @cindex interpret state
                   7539: @cindex compile state
                   7540: The text interpreter operates in one of two states: @dfn{interpret
                   7541: state} and @dfn{compile state}. The current state is defined by the
1.71      anton    7542: aptly-named variable @code{state}.
1.29      crook    7543: 
                   7544: This section starts by describing how the text interpreter behaves when
                   7545: it is in interpret state, processing input from the user input device --
                   7546: the keyboard. This is the mode that a Forth system is in after it starts
                   7547: up.
                   7548: 
                   7549: @cindex input buffer
                   7550: @cindex terminal input buffer
                   7551: The text interpreter works from an area of memory called the @dfn{input
                   7552: buffer}@footnote{When the text interpreter is processing input from the
                   7553: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   7554: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   7555: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    7556: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    7557: leading spaces (called @dfn{delimiters}) then parses a string (a
                   7558: sequence of non-space characters) until it reaches either a space
                   7559: character or the end of the buffer. Having parsed a string, it makes two
                   7560: attempts to process it:
1.27      crook    7561: 
1.29      crook    7562: @cindex dictionary
1.27      crook    7563: @itemize @bullet
                   7564: @item
1.29      crook    7565: It looks for the string in a @dfn{dictionary} of definitions. If the
                   7566: string is found, the string names a @dfn{definition} (also known as a
                   7567: @dfn{word}) and the dictionary search returns information that allows
                   7568: the text interpreter to perform the word's @dfn{interpretation
                   7569: semantics}. In most cases, this simply means that the word will be
                   7570: executed.
1.27      crook    7571: @item
                   7572: If the string is not found in the dictionary, the text interpreter
1.29      crook    7573: attempts to treat it as a number, using the rules described in
                   7574: @ref{Number Conversion}. If the string represents a legal number in the
                   7575: current radix, the number is pushed onto a parameter stack (the data
                   7576: stack for integers, the floating-point stack for floating-point
                   7577: numbers).
                   7578: @end itemize
                   7579: 
                   7580: If both attempts fail, or if the word is found in the dictionary but has
                   7581: no interpretation semantics@footnote{This happens if the word was
                   7582: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   7583: remainder of the input buffer, issues an error message and waits for
                   7584: more input. If one of the attempts succeeds, the text interpreter
                   7585: repeats the parsing process until the whole of the input buffer has been
                   7586: processed, at which point it prints the status message ``@code{ ok}''
                   7587: and waits for more input.
                   7588: 
1.71      anton    7589: @c anton: this should be in the input stream subsection (or below it)
                   7590: 
1.29      crook    7591: @cindex parse area
                   7592: The text interpreter keeps track of its position in the input buffer by
                   7593: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   7594: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   7595: of the input buffer. The region from offset @code{>IN @@} to the end of
                   7596: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   7597: the text interpreter processes the contents of the input buffer by
                   7598: parsing strings from the parse area until the parse area is empty.}.
                   7599: This example shows how @code{>IN} changes as the text interpreter parses
                   7600: the input buffer:
                   7601: 
                   7602: @example
                   7603: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   7604:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   7605: 
                   7606: 1 2 3 remaining + remaining . 
                   7607: 
                   7608: : foo 1 2 3 remaining SWAP remaining ;
                   7609: @end example
                   7610: 
                   7611: @noindent
                   7612: The result is:
                   7613: 
                   7614: @example
                   7615: ->+ remaining .<-
                   7616: ->.<-5  ok
                   7617: 
                   7618: ->SWAP remaining ;-<
                   7619: ->;<-  ok
                   7620: @end example
                   7621: 
                   7622: @cindex parsing words
                   7623: The value of @code{>IN} can also be modified by a word in the input
                   7624: buffer that is executed by the text interpreter.  This means that a word
                   7625: can ``trick'' the text interpreter into either skipping a section of the
                   7626: input buffer@footnote{This is how parsing words work.} or into parsing a
                   7627: section twice. For example:
1.27      crook    7628: 
1.29      crook    7629: @example
1.71      anton    7630: : lat ." <<foo>>" ;
                   7631: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29      crook    7632: @end example
                   7633: 
                   7634: @noindent
                   7635: When @code{flat} is executed, this output is produced@footnote{Exercise
                   7636: for the reader: what would happen if the @code{3} were replaced with
                   7637: @code{4}?}:
                   7638: 
                   7639: @example
1.71      anton    7640: <<bar>><<foo>>
1.29      crook    7641: @end example
                   7642: 
1.71      anton    7643: This technique can be used to work around some of the interoperability
                   7644: problems of parsing words.  Of course, it's better to avoid parsing
                   7645: words where possible.
                   7646: 
1.29      crook    7647: @noindent
                   7648: Two important notes about the behaviour of the text interpreter:
1.27      crook    7649: 
                   7650: @itemize @bullet
                   7651: @item
                   7652: It processes each input string to completion before parsing additional
1.29      crook    7653: characters from the input buffer.
                   7654: @item
                   7655: It treats the input buffer as a read-only region (and so must your code).
                   7656: @end itemize
                   7657: 
                   7658: @noindent
                   7659: When the text interpreter is in compile state, its behaviour changes in
                   7660: these ways:
                   7661: 
                   7662: @itemize @bullet
                   7663: @item
                   7664: If a parsed string is found in the dictionary, the text interpreter will
                   7665: perform the word's @dfn{compilation semantics}. In most cases, this
                   7666: simply means that the execution semantics of the word will be appended
                   7667: to the current definition.
1.27      crook    7668: @item
1.29      crook    7669: When a number is encountered, it is compiled into the current definition
                   7670: (as a literal) rather than being pushed onto a parameter stack.
                   7671: @item
                   7672: If an error occurs, @code{state} is modified to put the text interpreter
                   7673: back into interpret state.
                   7674: @item
                   7675: Each time a line is entered from the keyboard, Gforth prints
                   7676: ``@code{ compiled}'' rather than `` @code{ok}''.
                   7677: @end itemize
                   7678: 
                   7679: @cindex text interpreter - input sources
                   7680: When the text interpreter is using an input device other than the
                   7681: keyboard, its behaviour changes in these ways:
                   7682: 
                   7683: @itemize @bullet
                   7684: @item
                   7685: When the parse area is empty, the text interpreter attempts to refill
                   7686: the input buffer from the input source. When the input source is
1.71      anton    7687: exhausted, the input source is set back to the previous input source.
1.29      crook    7688: @item
                   7689: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   7690: time the parse area is emptied.
                   7691: @item
                   7692: If an error occurs, the input source is set back to the user input
                   7693: device.
1.27      crook    7694: @end itemize
1.21      crook    7695: 
1.49      anton    7696: You can read about this in more detail in @ref{Input Sources}.
1.44      crook    7697: 
1.26      crook    7698: doc->in
1.27      crook    7699: doc-source
                   7700: 
1.26      crook    7701: doc-tib
                   7702: doc-#tib
1.1       anton    7703: 
1.44      crook    7704: 
1.26      crook    7705: @menu
1.67      anton    7706: * Input Sources::               
                   7707: * Number Conversion::           
                   7708: * Interpret/Compile states::    
                   7709: * Interpreter Directives::      
1.26      crook    7710: @end menu
1.1       anton    7711: 
1.29      crook    7712: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   7713: @subsection Input Sources
                   7714: @cindex input sources
                   7715: @cindex text interpreter - input sources
                   7716: 
1.44      crook    7717: By default, the text interpreter processes input from the user input
1.29      crook    7718: device (the keyboard) when Forth starts up. The text interpreter can
                   7719: process input from any of these sources:
                   7720: 
                   7721: @itemize @bullet
                   7722: @item
                   7723: The user input device -- the keyboard.
                   7724: @item
                   7725: A file, using the words described in @ref{Forth source files}.
                   7726: @item
                   7727: A block, using the words described in @ref{Blocks}.
                   7728: @item
                   7729: A text string, using @code{evaluate}.
                   7730: @end itemize
                   7731: 
                   7732: A program can identify the current input device from the values of
                   7733: @code{source-id} and @code{blk}.
                   7734: 
1.44      crook    7735: 
1.29      crook    7736: doc-source-id
                   7737: doc-blk
                   7738: 
                   7739: doc-save-input
                   7740: doc-restore-input
                   7741: 
                   7742: doc-evaluate
1.111     anton    7743: doc-query
1.1       anton    7744: 
1.29      crook    7745: 
1.44      crook    7746: 
1.29      crook    7747: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    7748: @subsection Number Conversion
                   7749: @cindex number conversion
                   7750: @cindex double-cell numbers, input format
                   7751: @cindex input format for double-cell numbers
                   7752: @cindex single-cell numbers, input format
                   7753: @cindex input format for single-cell numbers
                   7754: @cindex floating-point numbers, input format
                   7755: @cindex input format for floating-point numbers
1.1       anton    7756: 
1.29      crook    7757: This section describes the rules that the text interpreter uses when it
                   7758: tries to convert a string into a number.
1.1       anton    7759: 
1.26      crook    7760: Let <digit> represent any character that is a legal digit in the current
1.29      crook    7761: number base@footnote{For example, 0-9 when the number base is decimal or
                   7762: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    7763: 
1.26      crook    7764: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    7765: 
1.29      crook    7766: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   7767: in the braces (@i{a} or @i{b} or neither).
1.1       anton    7768: 
1.26      crook    7769: Let * represent any number of instances of the previous character
                   7770: (including none).
1.1       anton    7771: 
1.26      crook    7772: Let any other character represent itself.
1.1       anton    7773: 
1.29      crook    7774: @noindent
1.26      crook    7775: Now, the conversion rules are:
1.21      crook    7776: 
1.26      crook    7777: @itemize @bullet
                   7778: @item
                   7779: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    7780: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    7781: @item
                   7782: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    7783: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    7784: arithmetic. Examples are -45 -5681 -0
                   7785: @item
                   7786: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    7787: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   7788: (all three of these represent the same number).
1.26      crook    7789: @item
                   7790: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    7791: double-precision (double-cell-sized) negative integer, and is
1.26      crook    7792: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    7793: -34.65 (all three of these represent the same number).
1.26      crook    7794: @item
1.29      crook    7795: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   7796: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35      anton    7797: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    7798: number) +12.E-4
1.26      crook    7799: @end itemize
1.1       anton    7800: 
1.174     anton    7801: By default, the number base used for integer number conversion is
                   7802: given by the contents of the variable @code{base}.  Note that a lot of
1.35      anton    7803: confusion can result from unexpected values of @code{base}.  If you
1.174     anton    7804: change @code{base} anywhere, make sure to save the old value and
                   7805: restore it afterwards; better yet, use @code{base-execute}, which does
                   7806: this for you.  In general I recommend keeping @code{base} decimal, and
1.35      anton    7807: using the prefixes described below for the popular non-decimal bases.
1.1       anton    7808: 
1.29      crook    7809: doc-dpl
1.174     anton    7810: doc-base-execute
1.26      crook    7811: doc-base
                   7812: doc-hex
                   7813: doc-decimal
1.1       anton    7814: 
1.26      crook    7815: @cindex '-prefix for character strings
                   7816: @cindex &-prefix for decimal numbers
1.133     anton    7817: @cindex #-prefix for decimal numbers
1.26      crook    7818: @cindex %-prefix for binary numbers
                   7819: @cindex $-prefix for hexadecimal numbers
1.133     anton    7820: @cindex 0x-prefix for hexadecimal numbers
1.35      anton    7821: Gforth allows you to override the value of @code{base} by using a
1.29      crook    7822: prefix@footnote{Some Forth implementations provide a similar scheme by
                   7823: implementing @code{$} etc. as parsing words that process the subsequent
                   7824: number in the input stream and push it onto the stack. For example, see
                   7825: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   7826: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   7827: is required between the prefix and the number.} before the first digit
1.133     anton    7828: of an (integer) number. The following prefixes are supported:
1.1       anton    7829: 
1.26      crook    7830: @itemize @bullet
                   7831: @item
1.35      anton    7832: @code{&} -- decimal
1.26      crook    7833: @item
1.133     anton    7834: @code{#} -- decimal
                   7835: @item
1.35      anton    7836: @code{%} -- binary
1.26      crook    7837: @item
1.35      anton    7838: @code{$} -- hexadecimal
1.26      crook    7839: @item
1.133     anton    7840: @code{0x} -- hexadecimal, if base<33.
                   7841: @item
                   7842: @code{'} -- numeric value (e.g., ASCII code) of next character; an
                   7843: optional @code{'} may be present after the character.
1.26      crook    7844: @end itemize
1.1       anton    7845: 
1.26      crook    7846: Here are some examples, with the equivalent decimal number shown after
                   7847: in braces:
1.1       anton    7848: 
1.26      crook    7849: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133     anton    7850: 'A (65),
                   7851: -'a' (-97),
1.26      crook    7852: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    7853: 
1.26      crook    7854: @cindex number conversion - traps for the unwary
1.29      crook    7855: @noindent
1.26      crook    7856: Number conversion has a number of traps for the unwary:
1.1       anton    7857: 
1.26      crook    7858: @itemize @bullet
                   7859: @item
                   7860: You cannot determine the current number base using the code sequence
1.35      anton    7861: @code{base @@ .} -- the number base is always 10 in the current number
                   7862: base. Instead, use something like @code{base @@ dec.}
1.26      crook    7863: @item
                   7864: If the number base is set to a value greater than 14 (for example,
                   7865: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   7866: it to be intepreted as either a single-precision integer or a
                   7867: floating-point number (Gforth treats it as an integer). The ambiguity
                   7868: can be resolved by explicitly stating the sign of the mantissa and/or
                   7869: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   7870: ambiguity arises; either representation will be treated as a
                   7871: floating-point number.
                   7872: @item
1.29      crook    7873: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    7874: It is used to specify file types.
                   7875: @item
1.72      anton    7876: ANS Forth requires the @code{.} of a double-precision number to be the
                   7877: final character in the string.  Gforth allows the @code{.} to be
                   7878: anywhere after the first digit.
1.26      crook    7879: @item
                   7880: The number conversion process does not check for overflow.
                   7881: @item
1.72      anton    7882: In an ANS Forth program @code{base} is required to be decimal when
                   7883: converting floating-point numbers.  In Gforth, number conversion to
                   7884: floating-point numbers always uses base &10, irrespective of the value
                   7885: of @code{base}.
1.26      crook    7886: @end itemize
1.1       anton    7887: 
1.49      anton    7888: You can read numbers into your programs with the words described in
1.181     anton    7889: @ref{Line input and conversion}.
1.1       anton    7890: 
1.82      anton    7891: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26      crook    7892: @subsection Interpret/Compile states
                   7893: @cindex Interpret/Compile states
1.1       anton    7894: 
1.29      crook    7895: A standard program is not permitted to change @code{state}
                   7896: explicitly. However, it can change @code{state} implicitly, using the
                   7897: words @code{[} and @code{]}. When @code{[} is executed it switches
                   7898: @code{state} to interpret state, and therefore the text interpreter
                   7899: starts interpreting. When @code{]} is executed it switches @code{state}
                   7900: to compile state and therefore the text interpreter starts
1.44      crook    7901: compiling. The most common usage for these words is for switching into
                   7902: interpret state and back from within a colon definition; this technique
1.49      anton    7903: can be used to compile a literal (for an example, @pxref{Literals}) or
                   7904: for conditional compilation (for an example, @pxref{Interpreter
                   7905: Directives}).
1.44      crook    7906: 
1.35      anton    7907: 
                   7908: @c This is a bad example: It's non-standard, and it's not necessary.
                   7909: @c However, I can't think of a good example for switching into compile
                   7910: @c state when there is no current word (@code{state}-smart words are not a
                   7911: @c good reason).  So maybe we should use an example for switching into
                   7912: @c interpret @code{state} in a colon def. - anton
1.44      crook    7913: @c nac-> I agree. I started out by putting in the example, then realised
                   7914: @c that it was non-ANS, so wrote more words around it. I hope this
                   7915: @c re-written version is acceptable to you. I do want to keep the example
                   7916: @c as it is helpful for showing what is and what is not portable, particularly
                   7917: @c where it outlaws a style in common use.
                   7918: 
1.72      anton    7919: @c anton: it's more important to show what's portable.  After we have done
1.83      anton    7920: @c that, we can also show what's not.  In any case, I have written a
                   7921: @c section Compiling Words which also deals with [ ].
1.35      anton    7922: 
1.95      anton    7923: @c  !! The following example does not work in Gforth 0.5.9 or later.
1.29      crook    7924: 
1.95      anton    7925: @c  @code{[} and @code{]} also give you the ability to switch into compile
                   7926: @c  state and back, but we cannot think of any useful Standard application
                   7927: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
                   7928: 
                   7929: @c  @example
                   7930: @c  : AA ." this is A" ;
                   7931: @c  : BB ." this is B" ;
                   7932: @c  : CC ." this is C" ;
                   7933: 
                   7934: @c  create table ] aa bb cc [
                   7935: 
                   7936: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   7937: @c    cells table + @@ execute ;
                   7938: @c  @end example
                   7939: 
                   7940: @c  This example builds a jump table; @code{0 go} will display ``@code{this
                   7941: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
                   7942: @c  defining @code{table} like this:
                   7943: 
                   7944: @c  @example
                   7945: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
                   7946: @c  @end example
                   7947: 
                   7948: @c  The problem with this code is that the definition of @code{table} is not
                   7949: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
                   7950: @c  @i{may} work on systems where code space and data space co-incide, the
                   7951: @c  Standard only allows data space to be assigned for a @code{CREATE}d
                   7952: @c  word. In addition, the Standard only allows @code{@@} to access data
                   7953: @c  space, whilst this example is using it to access code space. The only
                   7954: @c  portable, Standard way to build this table is to build it in data space,
                   7955: @c  like this:
                   7956: 
                   7957: @c  @example
                   7958: @c  create table ' aa , ' bb , ' cc ,
                   7959: @c  @end example
1.29      crook    7960: 
1.95      anton    7961: @c  doc-state
1.44      crook    7962: 
1.29      crook    7963: 
1.82      anton    7964: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
1.26      crook    7965: @subsection Interpreter Directives
                   7966: @cindex interpreter directives
1.72      anton    7967: @cindex conditional compilation
1.1       anton    7968: 
1.29      crook    7969: These words are usually used in interpret state; typically to control
                   7970: which parts of a source file are processed by the text
1.26      crook    7971: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   7972: supplements these with a rich set of immediate control structure words
                   7973: to compensate for the fact that the non-immediate versions can only be
1.29      crook    7974: used in compile state (@pxref{Control Structures}). Typical usages:
                   7975: 
                   7976: @example
1.72      anton    7977: FALSE Constant HAVE-ASSEMBLER
1.29      crook    7978: .
                   7979: .
1.72      anton    7980: HAVE-ASSEMBLER [IF]
1.29      crook    7981: : ASSEMBLER-FEATURE
                   7982:   ...
                   7983: ;
                   7984: [ENDIF]
                   7985: .
                   7986: .
                   7987: : SEE
                   7988:   ... \ general-purpose SEE code
1.72      anton    7989:   [ HAVE-ASSEMBLER [IF] ]
1.29      crook    7990:   ... \ assembler-specific SEE code
                   7991:   [ [ENDIF] ]
                   7992: ;
                   7993: @end example
1.1       anton    7994: 
1.44      crook    7995: 
1.26      crook    7996: doc-[IF]
                   7997: doc-[ELSE]
                   7998: doc-[THEN]
                   7999: doc-[ENDIF]
1.1       anton    8000: 
1.26      crook    8001: doc-[IFDEF]
                   8002: doc-[IFUNDEF]
1.1       anton    8003: 
1.26      crook    8004: doc-[?DO]
                   8005: doc-[DO]
                   8006: doc-[FOR]
                   8007: doc-[LOOP]
                   8008: doc-[+LOOP]
                   8009: doc-[NEXT]
1.1       anton    8010: 
1.26      crook    8011: doc-[BEGIN]
                   8012: doc-[UNTIL]
                   8013: doc-[AGAIN]
                   8014: doc-[WHILE]
                   8015: doc-[REPEAT]
1.1       anton    8016: 
1.27      crook    8017: 
1.26      crook    8018: @c -------------------------------------------------------------
1.111     anton    8019: @node The Input Stream, Word Lists, The Text Interpreter, Words
                   8020: @section The Input Stream
                   8021: @cindex input stream
                   8022: 
                   8023: @c !! integrate this better with the "Text Interpreter" section
                   8024: The text interpreter reads from the input stream, which can come from
                   8025: several sources (@pxref{Input Sources}).  Some words, in particular
                   8026: defining words, but also words like @code{'}, read parameters from the
                   8027: input stream instead of from the stack.
                   8028: 
                   8029: Such words are called parsing words, because they parse the input
                   8030: stream.  Parsing words are hard to use in other words, because it is
                   8031: hard to pass program-generated parameters through the input stream.
                   8032: They also usually have an unintuitive combination of interpretation and
                   8033: compilation semantics when implemented naively, leading to various
                   8034: approaches that try to produce a more intuitive behaviour
                   8035: (@pxref{Combined words}).
                   8036: 
                   8037: It should be obvious by now that parsing words are a bad idea.  If you
                   8038: want to implement a parsing word for convenience, also provide a factor
                   8039: of the word that does not parse, but takes the parameters on the stack.
                   8040: To implement the parsing word on top if it, you can use the following
                   8041: words:
                   8042: 
                   8043: @c anton: these belong in the input stream section
                   8044: doc-parse
1.138     anton    8045: doc-parse-name
1.111     anton    8046: doc-parse-word
                   8047: doc-name
                   8048: doc-word
                   8049: doc-refill
                   8050: 
                   8051: Conversely, if you have the bad luck (or lack of foresight) to have to
                   8052: deal with parsing words without having such factors, how do you pass a
                   8053: string that is not in the input stream to it?
                   8054: 
                   8055: doc-execute-parsing
                   8056: 
1.146     anton    8057: A definition of this word in ANS Forth is provided in
                   8058: @file{compat/execute-parsing.fs}.
                   8059: 
1.111     anton    8060: If you want to run a parsing word on a file, the following word should
                   8061: help:
                   8062: 
                   8063: doc-execute-parsing-file
                   8064: 
                   8065: @c -------------------------------------------------------------
                   8066: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26      crook    8067: @section Word Lists
                   8068: @cindex word lists
1.32      anton    8069: @cindex header space
1.1       anton    8070: 
1.36      anton    8071: A wordlist is a list of named words; you can add new words and look up
                   8072: words by name (and you can remove words in a restricted way with
                   8073: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
                   8074: 
                   8075: @cindex search order stack
                   8076: The text interpreter searches the wordlists present in the search order
                   8077: (a stack of wordlists), from the top to the bottom.  Within each
                   8078: wordlist, the search starts conceptually at the newest word; i.e., if
                   8079: two words in a wordlist have the same name, the newer word is found.
1.1       anton    8080: 
1.26      crook    8081: @cindex compilation word list
1.36      anton    8082: New words are added to the @dfn{compilation wordlist} (aka current
                   8083: wordlist).
1.1       anton    8084: 
1.36      anton    8085: @cindex wid
                   8086: A word list is identified by a cell-sized word list identifier (@i{wid})
                   8087: in much the same way as a file is identified by a file handle. The
                   8088: numerical value of the wid has no (portable) meaning, and might change
                   8089: from session to session.
1.1       anton    8090: 
1.29      crook    8091: The ANS Forth ``Search order'' word set is intended to provide a set of
                   8092: low-level tools that allow various different schemes to be
1.74      anton    8093: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26      crook    8094: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
1.45      crook    8095: Forth.
1.1       anton    8096: 
1.27      crook    8097: @comment TODO: locals section refers to here, saying that every word list (aka
                   8098: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78      anton    8099: @c anton: but better in a separate subsection on wordlist internals
1.1       anton    8100: 
1.45      crook    8101: @comment TODO: document markers, reveal, tables, mappedwordlist
                   8102: 
                   8103: @comment the gforthman- prefix is used to pick out the true definition of a
1.27      crook    8104: @comment word from the source files, rather than some alias.
1.44      crook    8105: 
1.26      crook    8106: doc-forth-wordlist
                   8107: doc-definitions
                   8108: doc-get-current
                   8109: doc-set-current
                   8110: doc-get-order
1.185     anton    8111: doc-set-order
1.26      crook    8112: doc-wordlist
1.30      anton    8113: doc-table
1.79      anton    8114: doc->order
1.36      anton    8115: doc-previous
1.26      crook    8116: doc-also
1.185     anton    8117: doc-forth
1.26      crook    8118: doc-only
1.185     anton    8119: doc-order
1.15      anton    8120: 
1.26      crook    8121: doc-find
                   8122: doc-search-wordlist
1.15      anton    8123: 
1.26      crook    8124: doc-words
                   8125: doc-vlist
1.44      crook    8126: @c doc-words-deferred
1.1       anton    8127: 
1.74      anton    8128: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26      crook    8129: doc-root
                   8130: doc-vocabulary
                   8131: doc-seal
                   8132: doc-vocs
                   8133: doc-current
                   8134: doc-context
1.1       anton    8135: 
1.44      crook    8136: 
1.26      crook    8137: @menu
1.75      anton    8138: * Vocabularies::                
1.67      anton    8139: * Why use word lists?::         
1.75      anton    8140: * Word list example::           
1.26      crook    8141: @end menu
                   8142: 
1.75      anton    8143: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
                   8144: @subsection Vocabularies
                   8145: @cindex Vocabularies, detailed explanation
                   8146: 
                   8147: Here is an example of creating and using a new wordlist using ANS
                   8148: Forth words:
                   8149: 
                   8150: @example
                   8151: wordlist constant my-new-words-wordlist
                   8152: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
                   8153: 
                   8154: \ add it to the search order
                   8155: also my-new-words
                   8156: 
                   8157: \ alternatively, add it to the search order and make it
                   8158: \ the compilation word list
                   8159: also my-new-words definitions
                   8160: \ type "order" to see the problem
                   8161: @end example
                   8162: 
                   8163: The problem with this example is that @code{order} has no way to
                   8164: associate the name @code{my-new-words} with the wid of the word list (in
                   8165: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   8166: that has no associated name). There is no Standard way of associating a
                   8167: name with a wid.
                   8168: 
                   8169: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   8170: associates a name with a wid:
                   8171: 
                   8172: @example
                   8173: vocabulary my-new-words
                   8174: 
                   8175: \ add it to the search order
                   8176: also my-new-words
                   8177: 
                   8178: \ alternatively, add it to the search order and make it
                   8179: \ the compilation word list
                   8180: my-new-words definitions
                   8181: \ type "order" to see that the problem is solved
                   8182: @end example
                   8183: 
                   8184: 
                   8185: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26      crook    8186: @subsection Why use word lists?
                   8187: @cindex word lists - why use them?
                   8188: 
1.74      anton    8189: Here are some reasons why people use wordlists:
1.26      crook    8190: 
                   8191: @itemize @bullet
1.74      anton    8192: 
                   8193: @c anton: Gforth's hashing implementation makes the search speed
                   8194: @c independent from the number of words.  But it is linear with the number
                   8195: @c of wordlists that have to be searched, so in effect using more wordlists
                   8196: @c actually slows down compilation.
                   8197: 
                   8198: @c @item
                   8199: @c To improve compilation speed by reducing the number of header space
                   8200: @c entries that must be searched. This is achieved by creating a new
                   8201: @c word list that contains all of the definitions that are used in the
                   8202: @c definition of a Forth system but which would not usually be used by
                   8203: @c programs running on that system. That word list would be on the search
                   8204: @c list when the Forth system was compiled but would be removed from the
                   8205: @c search list for normal operation. This can be a useful technique for
                   8206: @c low-performance systems (for example, 8-bit processors in embedded
                   8207: @c systems) but is unlikely to be necessary in high-performance desktop
                   8208: @c systems.
                   8209: 
1.26      crook    8210: @item
                   8211: To prevent a set of words from being used outside the context in which
                   8212: they are valid. Two classic examples of this are an integrated editor
                   8213: (all of the edit commands are defined in a separate word list; the
                   8214: search order is set to the editor word list when the editor is invoked;
                   8215: the old search order is restored when the editor is terminated) and an
                   8216: integrated assembler (the op-codes for the machine are defined in a
                   8217: separate word list which is used when a @code{CODE} word is defined).
1.74      anton    8218: 
                   8219: @item
                   8220: To organize the words of an application or library into a user-visible
                   8221: set (in @code{forth-wordlist} or some other common wordlist) and a set
                   8222: of helper words used just for the implementation (hidden in a separate
1.75      anton    8223: wordlist).  This keeps @code{words}' output smaller, separates
                   8224: implementation and interface, and reduces the chance of name conflicts
                   8225: within the common wordlist.
1.74      anton    8226: 
1.26      crook    8227: @item
                   8228: To prevent a name-space clash between multiple definitions with the same
                   8229: name. For example, when building a cross-compiler you might have a word
                   8230: @code{IF} that generates conditional code for your target system. By
                   8231: placing this definition in a different word list you can control whether
                   8232: the host system's @code{IF} or the target system's @code{IF} get used in
                   8233: any particular context by controlling the order of the word lists on the
                   8234: search order stack.
1.74      anton    8235: 
1.26      crook    8236: @end itemize
1.1       anton    8237: 
1.74      anton    8238: The downsides of using wordlists are:
                   8239: 
                   8240: @itemize
                   8241: 
                   8242: @item
                   8243: Debugging becomes more cumbersome.
                   8244: 
                   8245: @item
                   8246: Name conflicts worked around with wordlists are still there, and you
                   8247: have to arrange the search order carefully to get the desired results;
                   8248: if you forget to do that, you get hard-to-find errors (as in any case
                   8249: where you read the code differently from the compiler; @code{see} can
1.75      anton    8250: help seeing which of several possible words the name resolves to in such
                   8251: cases).  @code{See} displays just the name of the words, not what
                   8252: wordlist they belong to, so it might be misleading.  Using unique names
                   8253: is a better approach to avoid name conflicts.
1.74      anton    8254: 
                   8255: @item
                   8256: You have to explicitly undo any changes to the search order.  In many
                   8257: cases it would be more convenient if this happened implicitly.  Gforth
                   8258: currently does not provide such a feature, but it may do so in the
                   8259: future.
                   8260: @end itemize
                   8261: 
                   8262: 
1.75      anton    8263: @node Word list example,  , Why use word lists?, Word Lists
                   8264: @subsection Word list example
                   8265: @cindex word lists - example
1.1       anton    8266: 
1.74      anton    8267: The following example is from the
                   8268: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   8269: garbage collector} and uses wordlists to separate public words from
                   8270: helper words:
                   8271: 
                   8272: @example
                   8273: get-current ( wid )
                   8274: vocabulary garbage-collector also garbage-collector definitions
                   8275: ... \ define helper words
                   8276: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
                   8277: ... \ define the public (i.e., API) words
                   8278:     \ they can refer to the helper words
                   8279: previous \ restore original search order (helper words become invisible)
                   8280: @end example
                   8281: 
1.26      crook    8282: @c -------------------------------------------------------------
                   8283: @node Environmental Queries, Files, Word Lists, Words
                   8284: @section Environmental Queries
                   8285: @cindex environmental queries
1.21      crook    8286: 
1.26      crook    8287: ANS Forth introduced the idea of ``environmental queries'' as a way
                   8288: for a program running on a system to determine certain characteristics of the system.
                   8289: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    8290: 
1.32      anton    8291: The Standard requires that the header space used for environmental queries
                   8292: be distinct from the header space used for definitions.
1.21      crook    8293: 
1.26      crook    8294: Typically, environmental queries are supported by creating a set of
1.29      crook    8295: definitions in a word list that is @i{only} used during environmental
1.26      crook    8296: queries; that is what Gforth does. There is no Standard way of adding
                   8297: definitions to the set of recognised environmental queries, but any
                   8298: implementation that supports the loading of optional word sets must have
                   8299: some mechanism for doing this (after loading the word set, the
                   8300: associated environmental query string must return @code{true}). In
                   8301: Gforth, the word list used to honour environmental queries can be
                   8302: manipulated just like any other word list.
1.21      crook    8303: 
1.44      crook    8304: 
1.26      crook    8305: doc-environment?
                   8306: doc-environment-wordlist
1.21      crook    8307: 
1.26      crook    8308: doc-gforth
                   8309: doc-os-class
1.21      crook    8310: 
1.44      crook    8311: 
1.26      crook    8312: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   8313: returning two items on the stack, querying it using @code{environment?}
                   8314: will return an additional item; the @code{true} flag that shows that the
                   8315: string was recognised.
1.21      crook    8316: 
1.26      crook    8317: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    8318: 
1.26      crook    8319: Here are some examples of using environmental queries:
1.21      crook    8320: 
1.26      crook    8321: @example
                   8322: s" address-unit-bits" environment? 0=
                   8323: [IF]
                   8324:      cr .( environmental attribute address-units-bits unknown... ) cr
1.75      anton    8325: [ELSE]
                   8326:      drop \ ensure balanced stack effect
1.26      crook    8327: [THEN]
1.21      crook    8328: 
1.75      anton    8329: \ this might occur in the prelude of a standard program that uses THROW
                   8330: s" exception" environment? [IF]
                   8331:    0= [IF]
                   8332:       : throw abort" exception thrown" ;
                   8333:    [THEN]
                   8334: [ELSE] \ we don't know, so make sure
                   8335:    : throw abort" exception thrown" ;
                   8336: [THEN]
1.21      crook    8337: 
1.26      crook    8338: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   8339:                         [ELSE] .( Not Gforth..) [THEN]
1.75      anton    8340: 
                   8341: \ a program using v*
                   8342: s" gforth" environment? [IF]
                   8343:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
                   8344:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8345:      >r swap 2swap swap 0e r> 0 ?DO
1.190     anton    8346:        dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
1.75      anton    8347:      LOOP
                   8348:      2drop 2drop ; 
                   8349:   [THEN]
                   8350: [ELSE] \ 
                   8351:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8352:   ...
                   8353: [THEN]
1.26      crook    8354: @end example
1.21      crook    8355: 
1.26      crook    8356: Here is an example of adding a definition to the environment word list:
1.21      crook    8357: 
1.26      crook    8358: @example
                   8359: get-current environment-wordlist set-current
                   8360: true constant block
                   8361: true constant block-ext
                   8362: set-current
                   8363: @end example
1.21      crook    8364: 
1.26      crook    8365: You can see what definitions are in the environment word list like this:
1.21      crook    8366: 
1.26      crook    8367: @example
1.79      anton    8368: environment-wordlist >order words previous
1.26      crook    8369: @end example
1.21      crook    8370: 
                   8371: 
1.26      crook    8372: @c -------------------------------------------------------------
                   8373: @node Files, Blocks, Environmental Queries, Words
                   8374: @section Files
1.28      crook    8375: @cindex files
                   8376: @cindex I/O - file-handling
1.21      crook    8377: 
1.26      crook    8378: Gforth provides facilities for accessing files that are stored in the
                   8379: host operating system's file-system. Files that are processed by Gforth
                   8380: can be divided into two categories:
1.21      crook    8381: 
1.23      crook    8382: @itemize @bullet
                   8383: @item
1.29      crook    8384: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    8385: @item
1.29      crook    8386: Files that are processed by some other program (@dfn{general files}).
1.26      crook    8387: @end itemize
                   8388: 
                   8389: @menu
1.48      anton    8390: * Forth source files::          
                   8391: * General files::               
1.167     anton    8392: * Redirection::                 
1.48      anton    8393: * Search Paths::                
1.26      crook    8394: @end menu
                   8395: 
                   8396: @c -------------------------------------------------------------
                   8397: @node Forth source files, General files, Files, Files
                   8398: @subsection Forth source files
                   8399: @cindex including files
                   8400: @cindex Forth source files
1.21      crook    8401: 
1.26      crook    8402: The simplest way to interpret the contents of a file is to use one of
                   8403: these two formats:
1.21      crook    8404: 
1.26      crook    8405: @example
                   8406: include mysource.fs
                   8407: s" mysource.fs" included
                   8408: @end example
1.21      crook    8409: 
1.75      anton    8410: You usually want to include a file only if it is not included already
1.26      crook    8411: (by, say, another source file). In that case, you can use one of these
1.45      crook    8412: three formats:
1.21      crook    8413: 
1.26      crook    8414: @example
                   8415: require mysource.fs
                   8416: needs mysource.fs
                   8417: s" mysource.fs" required
                   8418: @end example
1.21      crook    8419: 
1.26      crook    8420: @cindex stack effect of included files
                   8421: @cindex including files, stack effect
1.45      crook    8422: It is good practice to write your source files such that interpreting them
                   8423: does not change the stack. Source files designed in this way can be used with
1.26      crook    8424: @code{required} and friends without complications. For example:
1.21      crook    8425: 
1.26      crook    8426: @example
1.75      anton    8427: 1024 require foo.fs drop
1.26      crook    8428: @end example
1.21      crook    8429: 
1.75      anton    8430: Here you want to pass the argument 1024 (e.g., a buffer size) to
                   8431: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
                   8432: ), which allows its use with @code{require}.  Of course with such
                   8433: parameters to required files, you have to ensure that the first
                   8434: @code{require} fits for all uses (i.e., @code{require} it early in the
                   8435: master load file).
1.44      crook    8436: 
1.26      crook    8437: doc-include-file
                   8438: doc-included
1.28      crook    8439: doc-included?
1.26      crook    8440: doc-include
                   8441: doc-required
                   8442: doc-require
                   8443: doc-needs
1.75      anton    8444: @c doc-init-included-files @c internal
                   8445: doc-sourcefilename
                   8446: doc-sourceline#
1.44      crook    8447: 
1.26      crook    8448: A definition in ANS Forth for @code{required} is provided in
                   8449: @file{compat/required.fs}.
1.21      crook    8450: 
1.26      crook    8451: @c -------------------------------------------------------------
1.167     anton    8452: @node General files, Redirection, Forth source files, Files
1.26      crook    8453: @subsection General files
                   8454: @cindex general files
                   8455: @cindex file-handling
1.21      crook    8456: 
1.75      anton    8457: Files are opened/created by name and type. The following file access
                   8458: methods (FAMs) are recognised:
1.44      crook    8459: 
1.75      anton    8460: @cindex fam (file access method)
1.26      crook    8461: doc-r/o
                   8462: doc-r/w
                   8463: doc-w/o
                   8464: doc-bin
1.1       anton    8465: 
1.44      crook    8466: 
1.26      crook    8467: When a file is opened/created, it returns a file identifier,
1.29      crook    8468: @i{wfileid} that is used for all other file commands. All file
                   8469: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    8470: successful operation and an implementation-defined non-zero value in the
                   8471: case of an error.
1.21      crook    8472: 
1.44      crook    8473: 
1.26      crook    8474: doc-open-file
                   8475: doc-create-file
1.21      crook    8476: 
1.26      crook    8477: doc-close-file
                   8478: doc-delete-file
                   8479: doc-rename-file
                   8480: doc-read-file
                   8481: doc-read-line
1.154     anton    8482: doc-key-file
                   8483: doc-key?-file
1.26      crook    8484: doc-write-file
                   8485: doc-write-line
                   8486: doc-emit-file
                   8487: doc-flush-file
1.21      crook    8488: 
1.26      crook    8489: doc-file-status
                   8490: doc-file-position
                   8491: doc-reposition-file
                   8492: doc-file-size
                   8493: doc-resize-file
1.21      crook    8494: 
1.93      anton    8495: doc-slurp-file
                   8496: doc-slurp-fid
1.112     anton    8497: doc-stdin
                   8498: doc-stdout
                   8499: doc-stderr
1.44      crook    8500: 
1.26      crook    8501: @c ---------------------------------------------------------
1.167     anton    8502: @node Redirection, Search Paths, General files, Files
                   8503: @subsection Redirection
                   8504: @cindex Redirection
                   8505: @cindex Input Redirection
                   8506: @cindex Output Redirection
                   8507: 
                   8508: You can redirect the output of @code{type} and @code{emit} and all the
                   8509: words that use them (all output words that don't have an explicit
1.174     anton    8510: target file) to an arbitrary file with the @code{outfile-execute},
                   8511: used like this:
1.167     anton    8512: 
                   8513: @example
1.174     anton    8514: : some-warning ( n -- )
                   8515:     cr ." warning# " . ;
                   8516: 
1.167     anton    8517: : print-some-warning ( n -- )
1.174     anton    8518:     ['] some-warning stderr outfile-execute ;
1.167     anton    8519: @end example
                   8520: 
1.174     anton    8521: After @code{some-warning} is executed, the original output direction
                   8522: is restored; this construct is safe against exceptions.  Similarly,
                   8523: there is @code{infile-execute} for redirecting the input of @code{key}
                   8524: and its users (any input word that does not take a file explicitly).
                   8525: 
                   8526: doc-outfile-execute
                   8527: doc-infile-execute
1.167     anton    8528: 
                   8529: If you do not want to redirect the input or output to a file, you can
                   8530: also make use of the fact that @code{key}, @code{emit} and @code{type}
                   8531: are deferred words (@pxref{Deferred Words}).  However, in that case
                   8532: you have to worry about the restoration and the protection against
                   8533: exceptions yourself; also, note that for redirecting the output in
                   8534: this way, you have to redirect both @code{emit} and @code{type}.
                   8535: 
                   8536: @c ---------------------------------------------------------
                   8537: @node Search Paths,  , Redirection, Files
1.26      crook    8538: @subsection Search Paths
                   8539: @cindex path for @code{included}
                   8540: @cindex file search path
                   8541: @cindex @code{include} search path
                   8542: @cindex search path for files
1.21      crook    8543: 
1.26      crook    8544: If you specify an absolute filename (i.e., a filename starting with
                   8545: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   8546: @samp{C:...})) for @code{included} and friends, that file is included
                   8547: just as you would expect.
1.21      crook    8548: 
1.75      anton    8549: If the filename starts with @file{./}, this refers to the directory that
                   8550: the present file was @code{included} from.  This allows files to include
                   8551: other files relative to their own position (irrespective of the current
                   8552: working directory or the absolute position).  This feature is essential
                   8553: for libraries consisting of several files, where a file may include
                   8554: other files from the library.  It corresponds to @code{#include "..."}
                   8555: in C. If the current input source is not a file, @file{.} refers to the
                   8556: directory of the innermost file being included, or, if there is no file
                   8557: being included, to the current working directory.
                   8558: 
                   8559: For relative filenames (not starting with @file{./}), Gforth uses a
                   8560: search path similar to Forth's search order (@pxref{Word Lists}). It
                   8561: tries to find the given filename in the directories present in the path,
                   8562: and includes the first one it finds. There are separate search paths for
                   8563: Forth source files and general files.  If the search path contains the
                   8564: directory @file{.}, this refers to the directory of the current file, or
                   8565: the working directory, as if the file had been specified with @file{./}.
1.21      crook    8566: 
1.26      crook    8567: Use @file{~+} to refer to the current working directory (as in the
                   8568: @code{bash}).
1.1       anton    8569: 
1.75      anton    8570: @c anton: fold the following subsubsections into this subsection?
1.1       anton    8571: 
1.48      anton    8572: @menu
1.75      anton    8573: * Source Search Paths::         
1.48      anton    8574: * General Search Paths::        
                   8575: @end menu
                   8576: 
1.26      crook    8577: @c ---------------------------------------------------------
1.75      anton    8578: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
                   8579: @subsubsection Source Search Paths
                   8580: @cindex search path control, source files
1.5       anton    8581: 
1.26      crook    8582: The search path is initialized when you start Gforth (@pxref{Invoking
1.75      anton    8583: Gforth}). You can display it and change it using @code{fpath} in
                   8584: combination with the general path handling words.
1.5       anton    8585: 
1.75      anton    8586: doc-fpath
                   8587: @c the functionality of the following words is easily available through
                   8588: @c   fpath and the general path words.  The may go away.
                   8589: @c doc-.fpath
                   8590: @c doc-fpath+
                   8591: @c doc-fpath=
                   8592: @c doc-open-fpath-file
1.44      crook    8593: 
                   8594: @noindent
1.26      crook    8595: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    8596: 
1.26      crook    8597: @example
1.75      anton    8598: fpath path= /usr/lib/forth/|./
1.26      crook    8599: require timer.fs
                   8600: @end example
1.5       anton    8601: 
1.75      anton    8602: 
1.26      crook    8603: @c ---------------------------------------------------------
1.75      anton    8604: @node General Search Paths,  , Source Search Paths, Search Paths
1.26      crook    8605: @subsubsection General Search Paths
1.75      anton    8606: @cindex search path control, source files
1.5       anton    8607: 
1.26      crook    8608: Your application may need to search files in several directories, like
                   8609: @code{included} does. To facilitate this, Gforth allows you to define
                   8610: and use your own search paths, by providing generic equivalents of the
                   8611: Forth search path words:
1.5       anton    8612: 
1.75      anton    8613: doc-open-path-file
                   8614: doc-path-allot
                   8615: doc-clear-path
                   8616: doc-also-path
1.26      crook    8617: doc-.path
                   8618: doc-path+
                   8619: doc-path=
1.5       anton    8620: 
1.75      anton    8621: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44      crook    8622: 
1.75      anton    8623: Here's an example of creating an empty search path:
                   8624: @c
1.26      crook    8625: @example
1.75      anton    8626: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26      crook    8627: @end example
1.5       anton    8628: 
1.26      crook    8629: @c -------------------------------------------------------------
                   8630: @node Blocks, Other I/O, Files, Words
                   8631: @section Blocks
1.28      crook    8632: @cindex I/O - blocks
                   8633: @cindex blocks
                   8634: 
                   8635: When you run Gforth on a modern desk-top computer, it runs under the
                   8636: control of an operating system which provides certain services.  One of
                   8637: these services is @var{file services}, which allows Forth source code
                   8638: and data to be stored in files and read into Gforth (@pxref{Files}).
                   8639: 
                   8640: Traditionally, Forth has been an important programming language on
                   8641: systems where it has interfaced directly to the underlying hardware with
                   8642: no intervening operating system. Forth provides a mechanism, called
1.29      crook    8643: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    8644: 
                   8645: A block is a 1024-byte data area, which can be used to hold data or
                   8646: Forth source code. No structure is imposed on the contents of the
                   8647: block. A block is identified by its number; blocks are numbered
                   8648: contiguously from 1 to an implementation-defined maximum.
                   8649: 
                   8650: A typical system that used blocks but no operating system might use a
                   8651: single floppy-disk drive for mass storage, with the disks formatted to
                   8652: provide 256-byte sectors. Blocks would be implemented by assigning the
                   8653: first four sectors of the disk to block 1, the second four sectors to
                   8654: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   8655: would not contain any file system information, just the set of blocks.
                   8656: 
1.29      crook    8657: @cindex blocks file
1.28      crook    8658: On systems that do provide file services, blocks are typically
1.29      crook    8659: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    8660: file}.  The size of the blocks file will be an exact multiple of 1024
                   8661: bytes, corresponding to the number of blocks it contains. This is the
                   8662: mechanism that Gforth uses.
                   8663: 
1.29      crook    8664: @cindex @file{blocks.fb}
1.75      anton    8665: Only one blocks file can be open at a time. If you use block words without
1.28      crook    8666: having specified a blocks file, Gforth defaults to the blocks file
                   8667: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75      anton    8668: locate a blocks file (@pxref{Source Search Paths}).
1.28      crook    8669: 
1.29      crook    8670: @cindex block buffers
1.28      crook    8671: When you read and write blocks under program control, Gforth uses a
1.29      crook    8672: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    8673: not used when you use @code{load} to interpret the contents of a block.
                   8674: 
1.75      anton    8675: The behaviour of the block buffers is analagous to that of a cache.
                   8676: Each block buffer has three states:
1.28      crook    8677: 
                   8678: @itemize @bullet
                   8679: @item
                   8680: Unassigned
                   8681: @item
                   8682: Assigned-clean
                   8683: @item
                   8684: Assigned-dirty
                   8685: @end itemize
                   8686: 
1.29      crook    8687: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    8688: block, the block (specified by its block number) must be assigned to a
                   8689: block buffer.
                   8690: 
                   8691: The assignment of a block to a block buffer is performed by @code{block}
                   8692: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   8693: contents of a block. Use @code{buffer} when you don't care about the
                   8694: existing contents of the block@footnote{The ANS Forth definition of
1.35      anton    8695: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28      crook    8696: with the particular block is already stored in a block buffer due to an
                   8697: earlier @code{block} command, @code{buffer} will return that block
                   8698: buffer and the existing contents of the block will be
                   8699: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    8700: block buffer for the block.}.
1.28      crook    8701: 
1.47      crook    8702: Once a block has been assigned to a block buffer using @code{block} or
1.75      anton    8703: @code{buffer}, that block buffer becomes the @i{current block
                   8704: buffer}. Data may only be manipulated (read or written) within the
                   8705: current block buffer.
1.47      crook    8706: 
                   8707: When the contents of the current block buffer has been modified it is
1.48      anton    8708: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75      anton    8709: either abandon the changes (by doing nothing) or mark the block as
                   8710: changed (assigned-dirty), using @code{update}. Using @code{update} does
                   8711: not change the blocks file; it simply changes a block buffer's state to
                   8712: @i{assigned-dirty}.  The block will be written implicitly when it's
                   8713: buffer is needed for another block, or explicitly by @code{flush} or
                   8714: @code{save-buffers}.
                   8715: 
                   8716: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
                   8717: blocks file on disk. Leaving Gforth with @code{bye} also performs a
                   8718: @code{flush}.
1.28      crook    8719: 
1.29      crook    8720: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    8721: algorithm to assign a block buffer to a block. That means that any
                   8722: particular block can only be assigned to one specific block buffer,
1.29      crook    8723: called (for the particular operation) the @i{victim buffer}. If the
1.47      crook    8724: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
                   8725: the new block immediately. If it is @i{assigned-dirty} its current
                   8726: contents are written back to the blocks file on disk before it is
1.28      crook    8727: allocated to the new block.
                   8728: 
                   8729: Although no structure is imposed on the contents of a block, it is
                   8730: traditional to display the contents as 16 lines each of 64 characters.  A
                   8731: block provides a single, continuous stream of input (for example, it
                   8732: acts as a single parse area) -- there are no end-of-line characters
                   8733: within a block, and no end-of-file character at the end of a
                   8734: block. There are two consequences of this:
1.26      crook    8735: 
1.28      crook    8736: @itemize @bullet
                   8737: @item
                   8738: The last character of one line wraps straight into the first character
                   8739: of the following line
                   8740: @item
                   8741: The word @code{\} -- comment to end of line -- requires special
                   8742: treatment; in the context of a block it causes all characters until the
                   8743: end of the current 64-character ``line'' to be ignored.
                   8744: @end itemize
                   8745: 
                   8746: In Gforth, when you use @code{block} with a non-existent block number,
1.45      crook    8747: the current blocks file will be extended to the appropriate size and the
1.28      crook    8748: block buffer will be initialised with spaces.
                   8749: 
1.47      crook    8750: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
                   8751: for details) but doesn't encourage the use of blocks; the mechanism is
                   8752: only provided for backward compatibility -- ANS Forth requires blocks to
                   8753: be available when files are.
1.28      crook    8754: 
                   8755: Common techniques that are used when working with blocks include:
                   8756: 
                   8757: @itemize @bullet
                   8758: @item
                   8759: A screen editor that allows you to edit blocks without leaving the Forth
                   8760: environment.
                   8761: @item
                   8762: Shadow screens; where every code block has an associated block
                   8763: containing comments (for example: code in odd block numbers, comments in
                   8764: even block numbers). Typically, the block editor provides a convenient
                   8765: mechanism to toggle between code and comments.
                   8766: @item
                   8767: Load blocks; a single block (typically block 1) contains a number of
                   8768: @code{thru} commands which @code{load} the whole of the application.
                   8769: @end itemize
1.26      crook    8770: 
1.29      crook    8771: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   8772: integrated into a Forth programming environment.
1.26      crook    8773: 
                   8774: @comment TODO what about errors on open-blocks?
1.44      crook    8775: 
1.26      crook    8776: doc-open-blocks
                   8777: doc-use
1.75      anton    8778: doc-block-offset
1.26      crook    8779: doc-get-block-fid
                   8780: doc-block-position
1.28      crook    8781: 
1.75      anton    8782: doc-list
1.28      crook    8783: doc-scr
                   8784: 
1.184     anton    8785: doc-block
1.28      crook    8786: doc-buffer
                   8787: 
1.75      anton    8788: doc-empty-buffers
                   8789: doc-empty-buffer
1.26      crook    8790: doc-update
1.28      crook    8791: doc-updated?
1.26      crook    8792: doc-save-buffers
1.75      anton    8793: doc-save-buffer
1.26      crook    8794: doc-flush
1.28      crook    8795: 
1.26      crook    8796: doc-load
                   8797: doc-thru
                   8798: doc-+load
                   8799: doc-+thru
1.45      crook    8800: doc---gforthman--->
1.26      crook    8801: doc-block-included
                   8802: 
1.44      crook    8803: 
1.26      crook    8804: @c -------------------------------------------------------------
1.126     pazsan   8805: @node Other I/O, OS command line arguments, Blocks, Words
1.26      crook    8806: @section Other I/O
1.28      crook    8807: @cindex I/O - keyboard and display
1.26      crook    8808: 
                   8809: @menu
                   8810: * Simple numeric output::       Predefined formats
                   8811: * Formatted numeric output::    Formatted (pictured) output
                   8812: * String Formats::              How Forth stores strings in memory
1.67      anton    8813: * Displaying characters and strings::  Other stuff
1.175     anton    8814: * Terminal output::             Cursor positioning etc.
1.181     anton    8815: * Single-key input::            
                   8816: * Line input and conversion::   
1.112     anton    8817: * Pipes::                       How to create your own pipes
1.149     pazsan   8818: * Xchars and Unicode::          Non-ASCII characters
1.26      crook    8819: @end menu
                   8820: 
                   8821: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   8822: @subsection Simple numeric output
1.28      crook    8823: @cindex numeric output - simple/free-format
1.5       anton    8824: 
1.26      crook    8825: The simplest output functions are those that display numbers from the
                   8826: data or floating-point stacks. Floating-point output is always displayed
                   8827: using base 10. Numbers displayed from the data stack use the value stored
                   8828: in @code{base}.
1.5       anton    8829: 
1.44      crook    8830: 
1.26      crook    8831: doc-.
                   8832: doc-dec.
                   8833: doc-hex.
                   8834: doc-u.
                   8835: doc-.r
                   8836: doc-u.r
                   8837: doc-d.
                   8838: doc-ud.
                   8839: doc-d.r
                   8840: doc-ud.r
                   8841: doc-f.
                   8842: doc-fe.
                   8843: doc-fs.
1.111     anton    8844: doc-f.rdp
1.44      crook    8845: 
1.26      crook    8846: Examples of printing the number 1234.5678E23 in the different floating-point output
                   8847: formats are shown below:
1.5       anton    8848: 
                   8849: @example
1.26      crook    8850: f. 123456779999999000000000000.
                   8851: fe. 123.456779999999E24
                   8852: fs. 1.23456779999999E26
1.5       anton    8853: @end example
                   8854: 
                   8855: 
1.26      crook    8856: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   8857: @subsection Formatted numeric output
1.28      crook    8858: @cindex formatted numeric output
1.26      crook    8859: @cindex pictured numeric output
1.28      crook    8860: @cindex numeric output - formatted
1.26      crook    8861: 
1.29      crook    8862: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    8863: output} for formatted printing of integers.  In this technique, digits
                   8864: are extracted from the number (using the current output radix defined by
                   8865: @code{base}), converted to ASCII codes and appended to a string that is
                   8866: built in a scratch-pad area of memory (@pxref{core-idef,
                   8867: Implementation-defined options, Implementation-defined
                   8868: options}). Arbitrary characters can be appended to the string during the
                   8869: extraction process. The completed string is specified by an address
                   8870: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   8871: under program control.
1.5       anton    8872: 
1.75      anton    8873: All of the integer output words described in the previous section
                   8874: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
                   8875: numeric output.
1.5       anton    8876: 
1.47      crook    8877: Three important things to remember about pictured numeric output:
1.5       anton    8878: 
1.26      crook    8879: @itemize @bullet
                   8880: @item
1.28      crook    8881: It always operates on double-precision numbers; to display a
1.49      anton    8882: single-precision number, convert it first (for ways of doing this
                   8883: @pxref{Double precision}).
1.26      crook    8884: @item
1.28      crook    8885: It always treats the double-precision number as though it were
                   8886: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    8887: @item
                   8888: The string is built up from right to left; least significant digit first.
                   8889: @end itemize
1.5       anton    8890: 
1.44      crook    8891: 
1.26      crook    8892: doc-<#
1.47      crook    8893: doc-<<#
1.26      crook    8894: doc-#
                   8895: doc-#s
                   8896: doc-hold
                   8897: doc-sign
                   8898: doc-#>
1.47      crook    8899: doc-#>>
1.5       anton    8900: 
1.26      crook    8901: doc-represent
1.111     anton    8902: doc-f>str-rdp
                   8903: doc-f>buf-rdp
1.5       anton    8904: 
1.44      crook    8905: 
                   8906: @noindent
1.26      crook    8907: Here are some examples of using pictured numeric output:
1.5       anton    8908: 
                   8909: @example
1.26      crook    8910: : my-u. ( u -- )
                   8911:   \ Simplest use of pns.. behaves like Standard u. 
                   8912:   0              \ convert to unsigned double
1.75      anton    8913:   <<#            \ start conversion
1.26      crook    8914:   #s             \ convert all digits
                   8915:   #>             \ complete conversion
1.75      anton    8916:   TYPE SPACE     \ display, with trailing space
                   8917:   #>> ;          \ release hold area
1.5       anton    8918: 
1.26      crook    8919: : cents-only ( u -- )
                   8920:   0              \ convert to unsigned double
1.75      anton    8921:   <<#            \ start conversion
1.26      crook    8922:   # #            \ convert two least-significant digits
                   8923:   #>             \ complete conversion, discard other digits
1.75      anton    8924:   TYPE SPACE     \ display, with trailing space
                   8925:   #>> ;          \ release hold area
1.5       anton    8926: 
1.26      crook    8927: : dollars-and-cents ( u -- )
                   8928:   0              \ convert to unsigned double
1.75      anton    8929:   <<#            \ start conversion
1.26      crook    8930:   # #            \ convert two least-significant digits
                   8931:   [char] . hold  \ insert decimal point
                   8932:   #s             \ convert remaining digits
                   8933:   [char] $ hold  \ append currency symbol
                   8934:   #>             \ complete conversion
1.75      anton    8935:   TYPE SPACE     \ display, with trailing space
                   8936:   #>> ;          \ release hold area
1.5       anton    8937: 
1.26      crook    8938: : my-. ( n -- )
                   8939:   \ handling negatives.. behaves like Standard .
                   8940:   s>d            \ convert to signed double
                   8941:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    8942:   <<#            \ start conversion
1.26      crook    8943:   #s             \ convert all digits
                   8944:   rot sign       \ get at sign byte, append "-" if needed
                   8945:   #>             \ complete conversion
1.75      anton    8946:   TYPE SPACE     \ display, with trailing space
                   8947:   #>> ;          \ release hold area
1.5       anton    8948: 
1.26      crook    8949: : account. ( n -- )
1.75      anton    8950:   \ accountants don't like minus signs, they use parentheses
1.26      crook    8951:   \ for negative numbers
                   8952:   s>d            \ convert to signed double
                   8953:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    8954:   <<#            \ start conversion
1.26      crook    8955:   2 pick         \ get copy of sign byte
                   8956:   0< IF [char] ) hold THEN \ right-most character of output
                   8957:   #s             \ convert all digits
                   8958:   rot            \ get at sign byte
                   8959:   0< IF [char] ( hold THEN
                   8960:   #>             \ complete conversion
1.75      anton    8961:   TYPE SPACE     \ display, with trailing space
                   8962:   #>> ;          \ release hold area
                   8963: 
1.5       anton    8964: @end example
                   8965: 
1.26      crook    8966: Here are some examples of using these words:
1.5       anton    8967: 
                   8968: @example
1.26      crook    8969: 1 my-u. 1
                   8970: hex -1 my-u. decimal FFFFFFFF
                   8971: 1 cents-only 01
                   8972: 1234 cents-only 34
                   8973: 2 dollars-and-cents $0.02
                   8974: 1234 dollars-and-cents $12.34
                   8975: 123 my-. 123
                   8976: -123 my. -123
                   8977: 123 account. 123
                   8978: -456 account. (456)
1.5       anton    8979: @end example
                   8980: 
                   8981: 
1.26      crook    8982: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   8983: @subsection String Formats
1.27      crook    8984: @cindex strings - see character strings
                   8985: @cindex character strings - formats
1.28      crook    8986: @cindex I/O - see character strings
1.75      anton    8987: @cindex counted strings
                   8988: 
                   8989: @c anton: this does not really belong here; maybe the memory section,
                   8990: @c  or the principles chapter
1.26      crook    8991: 
1.27      crook    8992: Forth commonly uses two different methods for representing character
                   8993: strings:
1.26      crook    8994: 
                   8995: @itemize @bullet
                   8996: @item
                   8997: @cindex address of counted string
1.45      crook    8998: @cindex counted string
1.29      crook    8999: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   9000: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   9001: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    9002: memory.
                   9003: @item
1.29      crook    9004: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   9005: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    9006: first byte of the string.
                   9007: @end itemize
                   9008: 
                   9009: ANS Forth encourages the use of the second format when representing
1.75      anton    9010: strings.
1.26      crook    9011: 
1.44      crook    9012: 
1.26      crook    9013: doc-count
                   9014: 
1.44      crook    9015: 
1.49      anton    9016: For words that move, copy and search for strings see @ref{Memory
                   9017: Blocks}. For words that display characters and strings see
                   9018: @ref{Displaying characters and strings}.
1.26      crook    9019: 
1.175     anton    9020: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
1.26      crook    9021: @subsection Displaying characters and strings
1.27      crook    9022: @cindex characters - compiling and displaying
                   9023: @cindex character strings - compiling and displaying
1.26      crook    9024: 
                   9025: This section starts with a glossary of Forth words and ends with a set
                   9026: of examples.
                   9027: 
                   9028: doc-bl
                   9029: doc-space
                   9030: doc-spaces
                   9031: doc-emit
                   9032: doc-toupper
                   9033: doc-."
                   9034: doc-.(
1.98      anton    9035: doc-.\"
1.26      crook    9036: doc-type
1.44      crook    9037: doc-typewhite
1.26      crook    9038: doc-cr
1.27      crook    9039: @cindex cursor control
1.26      crook    9040: doc-s"
1.98      anton    9041: doc-s\"
1.26      crook    9042: doc-c"
                   9043: doc-char
                   9044: doc-[char]
                   9045: 
1.44      crook    9046: 
                   9047: @noindent
1.26      crook    9048: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    9049: 
                   9050: @example
1.26      crook    9051: .( text-1)
                   9052: : my-word
                   9053:   ." text-2" cr
                   9054:   .( text-3)
                   9055: ;
                   9056: 
                   9057: ." text-4"
                   9058: 
                   9059: : my-char
                   9060:   [char] ALPHABET emit
                   9061:   char emit
                   9062: ;
1.5       anton    9063: @end example
                   9064: 
1.26      crook    9065: When you load this code into Gforth, the following output is generated:
1.5       anton    9066: 
1.26      crook    9067: @example
1.30      anton    9068: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    9069: @end example
1.5       anton    9070: 
1.26      crook    9071: @itemize @bullet
                   9072: @item
                   9073: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   9074: is an immediate word; it behaves in the same way whether it is used inside
                   9075: or outside a colon definition.
                   9076: @item
                   9077: Message @code{text-4} is displayed because of Gforth's added interpretation
                   9078: semantics for @code{."}.
                   9079: @item
1.29      crook    9080: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    9081: performs the compilation semantics for @code{."} within the definition of
                   9082: @code{my-word}.
                   9083: @end itemize
1.5       anton    9084: 
1.26      crook    9085: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    9086: 
1.26      crook    9087: @example
1.30      anton    9088: @kbd{my-word @key{RET}} text-2
1.26      crook    9089:  ok
1.30      anton    9090: @kbd{my-char fred @key{RET}} Af ok
                   9091: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    9092: @end example
1.5       anton    9093: 
                   9094: @itemize @bullet
                   9095: @item
1.26      crook    9096: Message @code{text-2} is displayed because of the run-time behaviour of
                   9097: @code{."}.
                   9098: @item
                   9099: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   9100: on the stack at run-time. @code{emit} always displays the character
                   9101: when @code{my-char} is executed.
                   9102: @item
                   9103: @code{char} parses a string at run-time and the second @code{emit} displays
                   9104: the first character of the string.
1.5       anton    9105: @item
1.26      crook    9106: If you type @code{see my-char} you can see that @code{[char]} discarded
                   9107: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   9108: definition of @code{my-char}.
1.5       anton    9109: @end itemize
                   9110: 
                   9111: 
1.181     anton    9112: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
1.175     anton    9113: @subsection Terminal output
                   9114: @cindex output to terminal
                   9115: @cindex terminal output
                   9116: 
                   9117: If you are outputting to a terminal, you may want to control the
                   9118: positioning of the cursor:
                   9119: @cindex cursor positioning
                   9120: 
                   9121: doc-at-xy
                   9122: 
                   9123: In order to know where to position the cursor, it is often helpful to
                   9124: know the size of the screen:
                   9125: @cindex terminal size 
                   9126: 
                   9127: doc-form
                   9128: 
                   9129: And sometimes you want to use:
                   9130: @cindex clear screen
                   9131: 
                   9132: doc-page
                   9133: 
                   9134: Note that on non-terminals you should use @code{12 emit}, not
                   9135: @code{page}, to get a form feed.
                   9136: 
1.5       anton    9137: 
1.181     anton    9138: @node Single-key input, Line input and conversion, Terminal output, Other I/O
                   9139: @subsection Single-key input
                   9140: @cindex single-key input
                   9141: @cindex input, single-key
                   9142: 
                   9143: If you want to get a single printable character, you can use
                   9144: @code{key}; to check whether a character is available for @code{key},
                   9145: you can use @code{key?}.
1.5       anton    9146: 
1.181     anton    9147: doc-key
                   9148: doc-key?
1.27      crook    9149: 
1.181     anton    9150: If you want to process a mix of printable and non-printable
                   9151: characters, you can do that with @code{ekey} and friends.  @code{Ekey}
                   9152: produces a keyboard event that you have to convert into a character
                   9153: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
                   9154: 
                   9155: Typical code for using EKEY looks like this:
                   9156: 
                   9157: @example
                   9158: ekey ekey>char if ( c )
                   9159:   ... \ do something with the character
                   9160: else ekey>fkey if ( key-id )
                   9161:   case
                   9162:     k-up                                  of ... endof
                   9163:     k-f1                                  of ... endof
                   9164:     k-left k-shift-mask or k-ctrl-mask or of ... endof
                   9165:     ...
                   9166:   endcase
                   9167: else ( keyboard-event )
                   9168:   drop \ just ignore an unknown keyboard event type
                   9169: then then
                   9170: @end example
1.44      crook    9171: 
1.45      crook    9172: doc-ekey
1.141     anton    9173: doc-ekey>char
1.181     anton    9174: doc-ekey>fkey
1.45      crook    9175: doc-ekey?
1.141     anton    9176: 
1.181     anton    9177: The key identifiers for cursor keys are:
1.141     anton    9178: 
                   9179: doc-k-left
                   9180: doc-k-right
1.185     anton    9181: doc-k-up
                   9182: doc-k-down
                   9183: doc-k-home
                   9184: doc-k-end
1.141     anton    9185: doc-k-prior
                   9186: doc-k-next
                   9187: doc-k-insert
                   9188: doc-k-delete
                   9189: 
1.181     anton    9190: The key identifiers for function keys (aka keypad keys) are:
1.141     anton    9191: 
1.181     anton    9192: doc-k-f1
                   9193: doc-k-f2
                   9194: doc-k-f3
                   9195: doc-k-f4
                   9196: doc-k-f5
                   9197: doc-k-f6
                   9198: doc-k-f7
                   9199: doc-k-f8
                   9200: doc-k-f9
                   9201: doc-k-f10
                   9202: doc-k-f11
                   9203: doc-k-f12
                   9204: 
                   9205: Note that @code{k-f11} and @code{k-f12} are not as widely available.
                   9206: 
                   9207: You can combine these key identifiers with masks for various shift keys:
                   9208: 
                   9209: doc-k-shift-mask
                   9210: doc-k-ctrl-mask
                   9211: doc-k-alt-mask
                   9212: 
                   9213: Note that, even if a Forth system has @code{ekey>fkey} and the key
                   9214: identifier words, the keys are not necessarily available or it may not
                   9215: necessarily be able to report all the keys and all the possible
                   9216: combinations with shift masks.  Therefore, write your programs in such
                   9217: a way that they are still useful even if the keys and key combinations
                   9218: cannot be pressed or are not recognized.
                   9219: 
                   9220: Examples: Older keyboards often do not have an F11 and F12 key.  If
                   9221: you run Gforth in an xterm, the xterm catches a number of combinations
                   9222: (e.g., @key{Shift-Up}), and never passes it to Gforth.  Finally,
                   9223: Gforth currently does not recognize and report combinations with
                   9224: multiple shift keys (so the @key{shift-ctrl-left} case in the example
                   9225: above would never be entered).
                   9226: 
                   9227: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
                   9228: you need the ANSI.SYS driver to get that behaviour); it works by
                   9229: recognizing the escape sequences that ANSI terminals send when such a
                   9230: key is pressed.  If you have a terminal that sends other escape
                   9231: sequences, you will not get useful results on Gforth.  Other Forth
                   9232: systems may work in a different way.
                   9233: 
                   9234: 
                   9235: @node  Line input and conversion, Pipes, Single-key input, Other I/O
                   9236: @subsection Line input and conversion
                   9237: @cindex line input from terminal
                   9238: @cindex input, linewise from terminal
                   9239: @cindex convertin strings to numbers
                   9240: @cindex I/O - see input
                   9241: 
                   9242: For ways of storing character strings in memory see @ref{String Formats}.
                   9243: 
                   9244: @comment TODO examples for >number >float accept key key? pad parse word refill
                   9245: @comment then index them
1.141     anton    9246: 
                   9247: Words for inputting one line from the keyboard:
                   9248: 
                   9249: doc-accept
                   9250: doc-edit-line
                   9251: 
                   9252: Conversion words:
                   9253: 
1.143     anton    9254: doc-s>number?
                   9255: doc-s>unumber?
1.26      crook    9256: doc->number
                   9257: doc->float
1.143     anton    9258: 
1.141     anton    9259: 
1.27      crook    9260: @comment obsolescent words..
1.141     anton    9261: Obsolescent input and conversion words:
                   9262: 
1.27      crook    9263: doc-convert
1.26      crook    9264: doc-expect
1.27      crook    9265: doc-span
1.5       anton    9266: 
                   9267: 
1.181     anton    9268: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
1.112     anton    9269: @subsection Pipes
                   9270: @cindex pipes, creating your own
                   9271: 
                   9272: In addition to using Gforth in pipes created by other processes
                   9273: (@pxref{Gforth in pipes}), you can create your own pipe with
                   9274: @code{open-pipe}, and read from or write to it.
                   9275: 
                   9276: doc-open-pipe
                   9277: doc-close-pipe
                   9278: 
                   9279: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
                   9280: you don't catch this exception, Gforth will catch it and exit, usually
                   9281: silently (@pxref{Gforth in pipes}).  Since you probably do not want
                   9282: this, you should wrap a @code{catch} or @code{try} block around the code
                   9283: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
                   9284: problem yourself, and then return to regular processing.
                   9285: 
                   9286: doc-broken-pipe-error
                   9287: 
1.155     anton    9288: @node Xchars and Unicode,  , Pipes, Other I/O
                   9289: @subsection Xchars and Unicode
1.149     pazsan   9290: 
1.188     pazsan   9291: ASCII is only appropriate for the English language. Most western
                   9292: languages however fit somewhat into the Forth frame, since a byte is
                   9293: sufficient to encode the few special characters in each (though not
                   9294: always the same encoding can be used; latin-1 is most widely used,
                   9295: though). For other languages, different char-sets have to be used,
                   9296: several of them variable-width. Most prominent representant is
                   9297: UTF-8. Let's call these extended characters xchars. The primitive
                   9298: fixed-size characters stored as bytes are called pchars in this
                   9299: section.
                   9300: 
                   9301: The xchar words add a few data types:
                   9302: 
                   9303: @itemize
                   9304: 
                   9305: @item
                   9306: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
                   9307: and is a subset of unsigned cell. Note: UTF-8 can not store more that
                   9308: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
                   9309: character set can be used.
                   9310: 
                   9311: @item
                   9312: @var{xc-addr} is the address of an xchar in memory. Alignment
                   9313: requirements are the same as @var{c-addr}. The memory representation of an
                   9314: xchar differs from the stack representation, and depends on the
                   9315: encoding used. An xchar may use a variable number of pchars in memory.
                   9316: 
                   9317: @item
                   9318: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
                   9319: @var{xc-addr}, @var{u} pchars long.
                   9320: 
                   9321: @end itemize
                   9322: 
                   9323: doc-xc-size
                   9324: doc-x-size
                   9325: doc-xc@+
                   9326: doc-xc!+
                   9327: doc-xc!+?
                   9328: doc-xchar+
                   9329: doc-xchar-
                   9330: doc-+x/string
                   9331: doc-x\string-
                   9332: doc--trailing-garbage
                   9333: doc-x-width
                   9334: doc-xkey
                   9335: doc-xemit
                   9336: 
                   9337: There's a new environment query
                   9338: 
                   9339: doc-xchar-encoding
1.112     anton    9340: 
1.121     anton    9341: @node OS command line arguments, Locals, Other I/O, Words
                   9342: @section OS command line arguments
                   9343: @cindex OS command line arguments
                   9344: @cindex command line arguments, OS
                   9345: @cindex arguments, OS command line
                   9346: 
                   9347: The usual way to pass arguments to Gforth programs on the command line
                   9348: is via the @option{-e} option, e.g.
                   9349: 
                   9350: @example
                   9351: gforth -e "123 456" foo.fs -e bye
                   9352: @end example
                   9353: 
                   9354: However, you may want to interpret the command-line arguments directly.
                   9355: In that case, you can access the (image-specific) command-line arguments
1.123     anton    9356: through @code{next-arg}:
1.121     anton    9357: 
1.123     anton    9358: doc-next-arg
1.121     anton    9359: 
1.123     anton    9360: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121     anton    9361: 
                   9362: @example
                   9363: : echo ( -- )
1.122     anton    9364:     begin
1.123     anton    9365:        next-arg 2dup 0 0 d<> while
                   9366:            type space
                   9367:     repeat
                   9368:     2drop ;
1.121     anton    9369: 
                   9370: echo cr bye
                   9371: @end example
                   9372: 
                   9373: This can be invoked with
                   9374: 
                   9375: @example
                   9376: gforth echo.fs hello world
                   9377: @end example
1.123     anton    9378: 
                   9379: and it will print
                   9380: 
                   9381: @example
                   9382: hello world
                   9383: @end example
                   9384: 
                   9385: The next lower level of dealing with the OS command line are the
                   9386: following words:
                   9387: 
                   9388: doc-arg
                   9389: doc-shift-args
                   9390: 
                   9391: Finally, at the lowest level Gforth provides the following words:
                   9392: 
                   9393: doc-argc
                   9394: doc-argv
1.121     anton    9395: 
1.78      anton    9396: @c -------------------------------------------------------------
1.126     pazsan   9397: @node Locals, Structures, OS command line arguments, Words
1.78      anton    9398: @section Locals
                   9399: @cindex locals
                   9400: 
                   9401: Local variables can make Forth programming more enjoyable and Forth
                   9402: programs easier to read. Unfortunately, the locals of ANS Forth are
                   9403: laden with restrictions. Therefore, we provide not only the ANS Forth
                   9404: locals wordset, but also our own, more powerful locals wordset (we
                   9405: implemented the ANS Forth locals wordset through our locals wordset).
1.44      crook    9406: 
1.78      anton    9407: The ideas in this section have also been published in M. Anton Ertl,
                   9408: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
                   9409: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12      anton    9410: 
                   9411: @menu
1.78      anton    9412: * Gforth locals::               
                   9413: * ANS Forth locals::            
1.5       anton    9414: @end menu
                   9415: 
1.78      anton    9416: @node Gforth locals, ANS Forth locals, Locals, Locals
                   9417: @subsection Gforth locals
                   9418: @cindex Gforth locals
                   9419: @cindex locals, Gforth style
1.5       anton    9420: 
1.78      anton    9421: Locals can be defined with
1.44      crook    9422: 
1.78      anton    9423: @example
                   9424: @{ local1 local2 ... -- comment @}
                   9425: @end example
                   9426: or
                   9427: @example
                   9428: @{ local1 local2 ... @}
                   9429: @end example
1.5       anton    9430: 
1.78      anton    9431: E.g.,
                   9432: @example
                   9433: : max @{ n1 n2 -- n3 @}
                   9434:  n1 n2 > if
                   9435:    n1
                   9436:  else
                   9437:    n2
                   9438:  endif ;
                   9439: @end example
1.44      crook    9440: 
1.78      anton    9441: The similarity of locals definitions with stack comments is intended. A
                   9442: locals definition often replaces the stack comment of a word. The order
                   9443: of the locals corresponds to the order in a stack comment and everything
                   9444: after the @code{--} is really a comment.
1.77      anton    9445: 
1.78      anton    9446: This similarity has one disadvantage: It is too easy to confuse locals
                   9447: declarations with stack comments, causing bugs and making them hard to
                   9448: find. However, this problem can be avoided by appropriate coding
                   9449: conventions: Do not use both notations in the same program. If you do,
                   9450: they should be distinguished using additional means, e.g. by position.
1.77      anton    9451: 
1.78      anton    9452: @cindex types of locals
                   9453: @cindex locals types
                   9454: The name of the local may be preceded by a type specifier, e.g.,
                   9455: @code{F:} for a floating point value:
1.5       anton    9456: 
1.78      anton    9457: @example
                   9458: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   9459: \ complex multiplication
                   9460:  Ar Br f* Ai Bi f* f-
                   9461:  Ar Bi f* Ai Br f* f+ ;
                   9462: @end example
1.44      crook    9463: 
1.78      anton    9464: @cindex flavours of locals
                   9465: @cindex locals flavours
                   9466: @cindex value-flavoured locals
                   9467: @cindex variable-flavoured locals
                   9468: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   9469: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   9470: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   9471: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   9472: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   9473: produces its address (which becomes invalid when the variable's scope is
                   9474: left). E.g., the standard word @code{emit} can be defined in terms of
                   9475: @code{type} like this:
1.5       anton    9476: 
1.78      anton    9477: @example
                   9478: : emit @{ C^ char* -- @}
                   9479:     char* 1 type ;
                   9480: @end example
1.5       anton    9481: 
1.78      anton    9482: @cindex default type of locals
                   9483: @cindex locals, default type
                   9484: A local without type specifier is a @code{W:} local. Both flavours of
                   9485: locals are initialized with values from the data or FP stack.
1.44      crook    9486: 
1.78      anton    9487: Currently there is no way to define locals with user-defined data
                   9488: structures, but we are working on it.
1.5       anton    9489: 
1.78      anton    9490: Gforth allows defining locals everywhere in a colon definition. This
                   9491: poses the following questions:
1.5       anton    9492: 
1.78      anton    9493: @menu
                   9494: * Where are locals visible by name?::  
                   9495: * How long do locals live?::    
                   9496: * Locals programming style::    
                   9497: * Locals implementation::       
                   9498: @end menu
1.44      crook    9499: 
1.78      anton    9500: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   9501: @subsubsection Where are locals visible by name?
                   9502: @cindex locals visibility
                   9503: @cindex visibility of locals
                   9504: @cindex scope of locals
1.5       anton    9505: 
1.78      anton    9506: Basically, the answer is that locals are visible where you would expect
                   9507: it in block-structured languages, and sometimes a little longer. If you
                   9508: want to restrict the scope of a local, enclose its definition in
                   9509: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    9510: 
                   9511: 
1.78      anton    9512: doc-scope
                   9513: doc-endscope
1.5       anton    9514: 
                   9515: 
1.78      anton    9516: These words behave like control structure words, so you can use them
                   9517: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   9518: arbitrary ways.
1.77      anton    9519: 
1.78      anton    9520: If you want a more exact answer to the visibility question, here's the
                   9521: basic principle: A local is visible in all places that can only be
                   9522: reached through the definition of the local@footnote{In compiler
                   9523: construction terminology, all places dominated by the definition of the
                   9524: local.}. In other words, it is not visible in places that can be reached
                   9525: without going through the definition of the local. E.g., locals defined
                   9526: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   9527: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   9528: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77      anton    9529: 
1.78      anton    9530: The reasoning behind this solution is: We want to have the locals
                   9531: visible as long as it is meaningful. The user can always make the
                   9532: visibility shorter by using explicit scoping. In a place that can
                   9533: only be reached through the definition of a local, the meaning of a
                   9534: local name is clear. In other places it is not: How is the local
                   9535: initialized at the control flow path that does not contain the
                   9536: definition? Which local is meant, if the same name is defined twice in
                   9537: two independent control flow paths?
1.77      anton    9538: 
1.78      anton    9539: This should be enough detail for nearly all users, so you can skip the
                   9540: rest of this section. If you really must know all the gory details and
                   9541: options, read on.
1.77      anton    9542: 
1.78      anton    9543: In order to implement this rule, the compiler has to know which places
                   9544: are unreachable. It knows this automatically after @code{AHEAD},
                   9545: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   9546: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   9547: compiler that the control flow never reaches that place. If
                   9548: @code{UNREACHABLE} is not used where it could, the only consequence is
                   9549: that the visibility of some locals is more limited than the rule above
                   9550: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   9551: lie to the compiler), buggy code will be produced.
1.77      anton    9552: 
1.5       anton    9553: 
1.78      anton    9554: doc-unreachable
1.5       anton    9555: 
1.23      crook    9556: 
1.78      anton    9557: Another problem with this rule is that at @code{BEGIN}, the compiler
                   9558: does not know which locals will be visible on the incoming
                   9559: back-edge. All problems discussed in the following are due to this
                   9560: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   9561: loops as examples; the discussion also applies to @code{?DO} and other
                   9562: loops). Perhaps the most insidious example is:
1.26      crook    9563: @example
1.78      anton    9564: AHEAD
                   9565: BEGIN
                   9566:   x
                   9567: [ 1 CS-ROLL ] THEN
                   9568:   @{ x @}
                   9569:   ...
                   9570: UNTIL
1.26      crook    9571: @end example
1.23      crook    9572: 
1.78      anton    9573: This should be legal according to the visibility rule. The use of
                   9574: @code{x} can only be reached through the definition; but that appears
                   9575: textually below the use.
                   9576: 
                   9577: From this example it is clear that the visibility rules cannot be fully
                   9578: implemented without major headaches. Our implementation treats common
                   9579: cases as advertised and the exceptions are treated in a safe way: The
                   9580: compiler makes a reasonable guess about the locals visible after a
                   9581: @code{BEGIN}; if it is too pessimistic, the
                   9582: user will get a spurious error about the local not being defined; if the
                   9583: compiler is too optimistic, it will notice this later and issue a
                   9584: warning. In the case above the compiler would complain about @code{x}
                   9585: being undefined at its use. You can see from the obscure examples in
                   9586: this section that it takes quite unusual control structures to get the
                   9587: compiler into trouble, and even then it will often do fine.
1.23      crook    9588: 
1.78      anton    9589: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   9590: is that all locals visible before the @code{BEGIN} will also be
                   9591: visible after the @code{BEGIN}. This guess is valid for all loops that
                   9592: are entered only through the @code{BEGIN}, in particular, for normal
                   9593: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   9594: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   9595: compiler. When the branch to the @code{BEGIN} is finally generated by
                   9596: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   9597: warns the user if it was too optimistic:
1.26      crook    9598: @example
1.78      anton    9599: IF
                   9600:   @{ x @}
                   9601: BEGIN
                   9602:   \ x ? 
                   9603: [ 1 cs-roll ] THEN
                   9604:   ...
                   9605: UNTIL
1.26      crook    9606: @end example
1.23      crook    9607: 
1.78      anton    9608: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   9609: optimistically assumes that it lives until the @code{THEN}. It notices
                   9610: this difference when it compiles the @code{UNTIL} and issues a
                   9611: warning. The user can avoid the warning, and make sure that @code{x}
                   9612: is not used in the wrong area by using explicit scoping:
                   9613: @example
                   9614: IF
                   9615:   SCOPE
                   9616:   @{ x @}
                   9617:   ENDSCOPE
                   9618: BEGIN
                   9619: [ 1 cs-roll ] THEN
                   9620:   ...
                   9621: UNTIL
                   9622: @end example
1.23      crook    9623: 
1.78      anton    9624: Since the guess is optimistic, there will be no spurious error messages
                   9625: about undefined locals.
1.44      crook    9626: 
1.78      anton    9627: If the @code{BEGIN} is not reachable from above (e.g., after
                   9628: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   9629: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   9630: defined later. Therefore, the compiler assumes that no locals are
                   9631: visible after the @code{BEGIN}. However, the user can use
                   9632: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   9633: visible at the BEGIN as at the point where the top control-flow stack
                   9634: item was created.
1.23      crook    9635: 
1.44      crook    9636: 
1.78      anton    9637: doc-assume-live
1.26      crook    9638: 
1.23      crook    9639: 
1.78      anton    9640: @noindent
                   9641: E.g.,
                   9642: @example
                   9643: @{ x @}
                   9644: AHEAD
                   9645: ASSUME-LIVE
                   9646: BEGIN
                   9647:   x
                   9648: [ 1 CS-ROLL ] THEN
                   9649:   ...
                   9650: UNTIL
                   9651: @end example
1.44      crook    9652: 
1.78      anton    9653: Other cases where the locals are defined before the @code{BEGIN} can be
                   9654: handled by inserting an appropriate @code{CS-ROLL} before the
                   9655: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   9656: behind the @code{ASSUME-LIVE}).
1.23      crook    9657: 
1.78      anton    9658: Cases where locals are defined after the @code{BEGIN} (but should be
                   9659: visible immediately after the @code{BEGIN}) can only be handled by
                   9660: rearranging the loop. E.g., the ``most insidious'' example above can be
                   9661: arranged into:
                   9662: @example
                   9663: BEGIN
                   9664:   @{ x @}
                   9665:   ... 0=
                   9666: WHILE
                   9667:   x
                   9668: REPEAT
                   9669: @end example
1.44      crook    9670: 
1.78      anton    9671: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
                   9672: @subsubsection How long do locals live?
                   9673: @cindex locals lifetime
                   9674: @cindex lifetime of locals
1.23      crook    9675: 
1.78      anton    9676: The right answer for the lifetime question would be: A local lives at
                   9677: least as long as it can be accessed. For a value-flavoured local this
                   9678: means: until the end of its visibility. However, a variable-flavoured
                   9679: local could be accessed through its address far beyond its visibility
                   9680: scope. Ultimately, this would mean that such locals would have to be
                   9681: garbage collected. Since this entails un-Forth-like implementation
                   9682: complexities, I adopted the same cowardly solution as some other
                   9683: languages (e.g., C): The local lives only as long as it is visible;
                   9684: afterwards its address is invalid (and programs that access it
                   9685: afterwards are erroneous).
1.23      crook    9686: 
1.78      anton    9687: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
                   9688: @subsubsection Locals programming style
                   9689: @cindex locals programming style
                   9690: @cindex programming style, locals
1.23      crook    9691: 
1.78      anton    9692: The freedom to define locals anywhere has the potential to change
                   9693: programming styles dramatically. In particular, the need to use the
                   9694: return stack for intermediate storage vanishes. Moreover, all stack
                   9695: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   9696: determined arguments) can be eliminated: If the stack items are in the
                   9697: wrong order, just write a locals definition for all of them; then
                   9698: write the items in the order you want.
1.23      crook    9699: 
1.78      anton    9700: This seems a little far-fetched and eliminating stack manipulations is
                   9701: unlikely to become a conscious programming objective. Still, the number
                   9702: of stack manipulations will be reduced dramatically if local variables
                   9703: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
                   9704: a traditional implementation of @code{max}).
1.23      crook    9705: 
1.78      anton    9706: This shows one potential benefit of locals: making Forth programs more
                   9707: readable. Of course, this benefit will only be realized if the
                   9708: programmers continue to honour the principle of factoring instead of
                   9709: using the added latitude to make the words longer.
1.23      crook    9710: 
1.78      anton    9711: @cindex single-assignment style for locals
                   9712: Using @code{TO} can and should be avoided.  Without @code{TO},
                   9713: every value-flavoured local has only a single assignment and many
                   9714: advantages of functional languages apply to Forth. I.e., programs are
                   9715: easier to analyse, to optimize and to read: It is clear from the
                   9716: definition what the local stands for, it does not turn into something
                   9717: different later.
1.23      crook    9718: 
1.78      anton    9719: E.g., a definition using @code{TO} might look like this:
                   9720: @example
                   9721: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9722:  u1 u2 min 0
                   9723:  ?do
                   9724:    addr1 c@@ addr2 c@@ -
                   9725:    ?dup-if
                   9726:      unloop exit
                   9727:    then
                   9728:    addr1 char+ TO addr1
                   9729:    addr2 char+ TO addr2
                   9730:  loop
                   9731:  u1 u2 - ;
1.26      crook    9732: @end example
1.78      anton    9733: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   9734: every loop iteration. @code{strcmp} is a typical example of the
                   9735: readability problems of using @code{TO}. When you start reading
                   9736: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   9737: string. Only near the end of the loop you realize that it is something
                   9738: else.
1.23      crook    9739: 
1.78      anton    9740: This can be avoided by defining two locals at the start of the loop that
                   9741: are initialized with the right value for the current iteration.
                   9742: @example
                   9743: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9744:  addr1 addr2
                   9745:  u1 u2 min 0 
                   9746:  ?do @{ s1 s2 @}
                   9747:    s1 c@@ s2 c@@ -
                   9748:    ?dup-if
                   9749:      unloop exit
                   9750:    then
                   9751:    s1 char+ s2 char+
                   9752:  loop
                   9753:  2drop
                   9754:  u1 u2 - ;
                   9755: @end example
                   9756: Here it is clear from the start that @code{s1} has a different value
                   9757: in every loop iteration.
1.23      crook    9758: 
1.78      anton    9759: @node Locals implementation,  , Locals programming style, Gforth locals
                   9760: @subsubsection Locals implementation
                   9761: @cindex locals implementation
                   9762: @cindex implementation of locals
1.23      crook    9763: 
1.78      anton    9764: @cindex locals stack
                   9765: Gforth uses an extra locals stack. The most compelling reason for
                   9766: this is that the return stack is not float-aligned; using an extra stack
                   9767: also eliminates the problems and restrictions of using the return stack
                   9768: as locals stack. Like the other stacks, the locals stack grows toward
                   9769: lower addresses. A few primitives allow an efficient implementation:
                   9770: 
                   9771: 
                   9772: doc-@local#
                   9773: doc-f@local#
                   9774: doc-laddr#
                   9775: doc-lp+!#
                   9776: doc-lp!
                   9777: doc->l
                   9778: doc-f>l
                   9779: 
                   9780: 
                   9781: In addition to these primitives, some specializations of these
                   9782: primitives for commonly occurring inline arguments are provided for
                   9783: efficiency reasons, e.g., @code{@@local0} as specialization of
                   9784: @code{@@local#} for the inline argument 0. The following compiling words
                   9785: compile the right specialized version, or the general version, as
                   9786: appropriate:
1.23      crook    9787: 
1.5       anton    9788: 
1.107     dvdkhlng 9789: @c doc-compile-@local
                   9790: @c doc-compile-f@local
1.78      anton    9791: doc-compile-lp+!
1.5       anton    9792: 
                   9793: 
1.78      anton    9794: Combinations of conditional branches and @code{lp+!#} like
                   9795: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   9796: is taken) are provided for efficiency and correctness in loops.
1.5       anton    9797: 
1.78      anton    9798: A special area in the dictionary space is reserved for keeping the
                   9799: local variable names. @code{@{} switches the dictionary pointer to this
                   9800: area and @code{@}} switches it back and generates the locals
                   9801: initializing code. @code{W:} etc.@ are normal defining words. This
                   9802: special area is cleared at the start of every colon definition.
1.5       anton    9803: 
1.78      anton    9804: @cindex word list for defining locals
                   9805: A special feature of Gforth's dictionary is used to implement the
                   9806: definition of locals without type specifiers: every word list (aka
                   9807: vocabulary) has its own methods for searching
                   9808: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   9809: with a special search method: When it is searched for a word, it
                   9810: actually creates that word using @code{W:}. @code{@{} changes the search
                   9811: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   9812: and then the word list for defining locals without type specifiers.
1.5       anton    9813: 
1.78      anton    9814: The lifetime rules support a stack discipline within a colon
                   9815: definition: The lifetime of a local is either nested with other locals
                   9816: lifetimes or it does not overlap them.
1.23      crook    9817: 
1.78      anton    9818: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   9819: pointer manipulation is generated. Between control structure words
                   9820: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   9821: is the simplest of the other three control flow words. It has to
                   9822: restore the locals stack depth of the corresponding @code{BEGIN}
                   9823: before branching. The code looks like this:
                   9824: @format
                   9825: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   9826: @code{branch} <begin>
                   9827: @end format
1.26      crook    9828: 
1.78      anton    9829: @code{UNTIL} is a little more complicated: If it branches back, it
                   9830: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   9831: the locals stack must not be changed. The compiler generates the
                   9832: following code:
                   9833: @format
                   9834: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   9835: @end format
                   9836: The locals stack pointer is only adjusted if the branch is taken.
1.44      crook    9837: 
1.78      anton    9838: @code{THEN} can produce somewhat inefficient code:
                   9839: @format
                   9840: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   9841: <orig target>:
                   9842: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   9843: @end format
                   9844: The second @code{lp+!#} adjusts the locals stack pointer from the
                   9845: level at the @i{orig} point to the level after the @code{THEN}. The
                   9846: first @code{lp+!#} adjusts the locals stack pointer from the current
                   9847: level to the level at the orig point, so the complete effect is an
                   9848: adjustment from the current level to the right level after the
                   9849: @code{THEN}.
1.26      crook    9850: 
1.78      anton    9851: @cindex locals information on the control-flow stack
                   9852: @cindex control-flow stack items, locals information
                   9853: In a conventional Forth implementation a dest control-flow stack entry
                   9854: is just the target address and an orig entry is just the address to be
                   9855: patched. Our locals implementation adds a word list to every orig or dest
                   9856: item. It is the list of locals visible (or assumed visible) at the point
                   9857: described by the entry. Our implementation also adds a tag to identify
                   9858: the kind of entry, in particular to differentiate between live and dead
                   9859: (reachable and unreachable) orig entries.
1.26      crook    9860: 
1.78      anton    9861: A few unusual operations have to be performed on locals word lists:
1.44      crook    9862: 
1.5       anton    9863: 
1.78      anton    9864: doc-common-list
                   9865: doc-sub-list?
                   9866: doc-list-size
1.52      anton    9867: 
                   9868: 
1.78      anton    9869: Several features of our locals word list implementation make these
                   9870: operations easy to implement: The locals word lists are organised as
                   9871: linked lists; the tails of these lists are shared, if the lists
                   9872: contain some of the same locals; and the address of a name is greater
                   9873: than the address of the names behind it in the list.
1.5       anton    9874: 
1.78      anton    9875: Another important implementation detail is the variable
                   9876: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   9877: determine if they can be reached directly or only through the branch
                   9878: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   9879: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   9880: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5       anton    9881: 
1.78      anton    9882: Counted loops are similar to other loops in most respects, but
                   9883: @code{LEAVE} requires special attention: It performs basically the same
                   9884: service as @code{AHEAD}, but it does not create a control-flow stack
                   9885: entry. Therefore the information has to be stored elsewhere;
                   9886: traditionally, the information was stored in the target fields of the
                   9887: branches created by the @code{LEAVE}s, by organizing these fields into a
                   9888: linked list. Unfortunately, this clever trick does not provide enough
                   9889: space for storing our extended control flow information. Therefore, we
                   9890: introduce another stack, the leave stack. It contains the control-flow
                   9891: stack entries for all unresolved @code{LEAVE}s.
1.44      crook    9892: 
1.78      anton    9893: Local names are kept until the end of the colon definition, even if
                   9894: they are no longer visible in any control-flow path. In a few cases
                   9895: this may lead to increased space needs for the locals name area, but
                   9896: usually less than reclaiming this space would cost in code size.
1.5       anton    9897: 
1.44      crook    9898: 
1.78      anton    9899: @node ANS Forth locals,  , Gforth locals, Locals
                   9900: @subsection ANS Forth locals
                   9901: @cindex locals, ANS Forth style
1.5       anton    9902: 
1.78      anton    9903: The ANS Forth locals wordset does not define a syntax for locals, but
                   9904: words that make it possible to define various syntaxes. One of the
                   9905: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   9906: wordset, i.e.:
1.29      crook    9907: 
                   9908: @example
1.78      anton    9909: @{ local1 local2 ... -- comment @}
                   9910: @end example
                   9911: @noindent
                   9912: or
                   9913: @example
                   9914: @{ local1 local2 ... @}
1.29      crook    9915: @end example
                   9916: 
1.78      anton    9917: The order of the locals corresponds to the order in a stack comment. The
                   9918: restrictions are:
1.5       anton    9919: 
1.78      anton    9920: @itemize @bullet
                   9921: @item
                   9922: Locals can only be cell-sized values (no type specifiers are allowed).
                   9923: @item
                   9924: Locals can be defined only outside control structures.
                   9925: @item
                   9926: Locals can interfere with explicit usage of the return stack. For the
                   9927: exact (and long) rules, see the standard. If you don't use return stack
                   9928: accessing words in a definition using locals, you will be all right. The
                   9929: purpose of this rule is to make locals implementation on the return
                   9930: stack easier.
                   9931: @item
                   9932: The whole definition must be in one line.
                   9933: @end itemize
1.5       anton    9934: 
1.78      anton    9935: Locals defined in ANS Forth behave like @code{VALUE}s
                   9936: (@pxref{Values}). I.e., they are initialized from the stack. Using their
                   9937: name produces their value. Their value can be changed using @code{TO}.
1.77      anton    9938: 
1.78      anton    9939: Since the syntax above is supported by Gforth directly, you need not do
                   9940: anything to use it. If you want to port a program using this syntax to
                   9941: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   9942: syntax on the other system.
1.5       anton    9943: 
1.78      anton    9944: Note that a syntax shown in the standard, section A.13 looks
                   9945: similar, but is quite different in having the order of locals
                   9946: reversed. Beware!
1.5       anton    9947: 
1.78      anton    9948: The ANS Forth locals wordset itself consists of one word:
1.5       anton    9949: 
1.78      anton    9950: doc-(local)
1.5       anton    9951: 
1.78      anton    9952: The ANS Forth locals extension wordset defines a syntax using
                   9953: @code{locals|}, but it is so awful that we strongly recommend not to use
                   9954: it. We have implemented this syntax to make porting to Gforth easy, but
                   9955: do not document it here. The problem with this syntax is that the locals
                   9956: are defined in an order reversed with respect to the standard stack
                   9957: comment notation, making programs harder to read, and easier to misread
                   9958: and miswrite. The only merit of this syntax is that it is easy to
                   9959: implement using the ANS Forth locals wordset.
1.53      anton    9960: 
                   9961: 
1.78      anton    9962: @c ----------------------------------------------------------
                   9963: @node Structures, Object-oriented Forth, Locals, Words
                   9964: @section  Structures
                   9965: @cindex structures
                   9966: @cindex records
1.53      anton    9967: 
1.78      anton    9968: This section presents the structure package that comes with Gforth. A
                   9969: version of the package implemented in ANS Forth is available in
                   9970: @file{compat/struct.fs}. This package was inspired by a posting on
                   9971: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   9972: possibly John Hayes). A version of this section has been published in
                   9973: M. Anton Ertl,
                   9974: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
                   9975: Another Forth Structures Package}, Forth Dimensions 19(3), pages
                   9976: 13--16. Marcel Hendrix provided helpful comments.
1.53      anton    9977: 
1.78      anton    9978: @menu
                   9979: * Why explicit structure support?::  
                   9980: * Structure Usage::             
                   9981: * Structure Naming Convention::  
                   9982: * Structure Implementation::    
                   9983: * Structure Glossary::          
1.183     anton    9984: * Forth200x Structures::        
1.78      anton    9985: @end menu
1.55      anton    9986: 
1.78      anton    9987: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   9988: @subsection Why explicit structure support?
1.53      anton    9989: 
1.78      anton    9990: @cindex address arithmetic for structures
                   9991: @cindex structures using address arithmetic
                   9992: If we want to use a structure containing several fields, we could simply
                   9993: reserve memory for it, and access the fields using address arithmetic
                   9994: (@pxref{Address arithmetic}). As an example, consider a structure with
                   9995: the following fields
1.57      anton    9996: 
1.78      anton    9997: @table @code
                   9998: @item a
                   9999: is a float
                   10000: @item b
                   10001: is a cell
                   10002: @item c
                   10003: is a float
                   10004: @end table
1.57      anton    10005: 
1.78      anton    10006: Given the (float-aligned) base address of the structure we get the
                   10007: address of the field
1.52      anton    10008: 
1.78      anton    10009: @table @code
                   10010: @item a
                   10011: without doing anything further.
                   10012: @item b
                   10013: with @code{float+}
                   10014: @item c
                   10015: with @code{float+ cell+ faligned}
                   10016: @end table
1.52      anton    10017: 
1.78      anton    10018: It is easy to see that this can become quite tiring. 
1.52      anton    10019: 
1.78      anton    10020: Moreover, it is not very readable, because seeing a
                   10021: @code{cell+} tells us neither which kind of structure is
                   10022: accessed nor what field is accessed; we have to somehow infer the kind
                   10023: of structure, and then look up in the documentation, which field of
                   10024: that structure corresponds to that offset.
1.53      anton    10025: 
1.78      anton    10026: Finally, this kind of address arithmetic also causes maintenance
                   10027: troubles: If you add or delete a field somewhere in the middle of the
                   10028: structure, you have to find and change all computations for the fields
                   10029: afterwards.
1.52      anton    10030: 
1.78      anton    10031: So, instead of using @code{cell+} and friends directly, how
                   10032: about storing the offsets in constants:
1.52      anton    10033: 
1.78      anton    10034: @example
                   10035: 0 constant a-offset
                   10036: 0 float+ constant b-offset
                   10037: 0 float+ cell+ faligned c-offset
                   10038: @end example
1.64      pazsan   10039: 
1.78      anton    10040: Now we can get the address of field @code{x} with @code{x-offset
                   10041: +}. This is much better in all respects. Of course, you still
                   10042: have to change all later offset definitions if you add a field. You can
                   10043: fix this by declaring the offsets in the following way:
1.57      anton    10044: 
1.78      anton    10045: @example
                   10046: 0 constant a-offset
                   10047: a-offset float+ constant b-offset
                   10048: b-offset cell+ faligned constant c-offset
                   10049: @end example
1.57      anton    10050: 
1.78      anton    10051: Since we always use the offsets with @code{+}, we could use a defining
                   10052: word @code{cfield} that includes the @code{+} in the action of the
                   10053: defined word:
1.64      pazsan   10054: 
1.78      anton    10055: @example
                   10056: : cfield ( n "name" -- )
                   10057:     create ,
                   10058: does> ( name execution: addr1 -- addr2 )
                   10059:     @@ + ;
1.64      pazsan   10060: 
1.78      anton    10061: 0 cfield a
                   10062: 0 a float+ cfield b
                   10063: 0 b cell+ faligned cfield c
                   10064: @end example
1.64      pazsan   10065: 
1.78      anton    10066: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64      pazsan   10067: 
1.78      anton    10068: The structure field words now can be used quite nicely. However,
                   10069: their definition is still a bit cumbersome: We have to repeat the
                   10070: name, the information about size and alignment is distributed before
                   10071: and after the field definitions etc.  The structure package presented
                   10072: here addresses these problems.
1.64      pazsan   10073: 
1.78      anton    10074: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   10075: @subsection Structure Usage
                   10076: @cindex structure usage
1.57      anton    10077: 
1.78      anton    10078: @cindex @code{field} usage
                   10079: @cindex @code{struct} usage
                   10080: @cindex @code{end-struct} usage
                   10081: You can define a structure for a (data-less) linked list with:
1.57      anton    10082: @example
1.78      anton    10083: struct
                   10084:     cell% field list-next
                   10085: end-struct list%
1.57      anton    10086: @end example
                   10087: 
1.78      anton    10088: With the address of the list node on the stack, you can compute the
                   10089: address of the field that contains the address of the next node with
                   10090: @code{list-next}. E.g., you can determine the length of a list
                   10091: with:
1.57      anton    10092: 
                   10093: @example
1.78      anton    10094: : list-length ( list -- n )
                   10095: \ "list" is a pointer to the first element of a linked list
                   10096: \ "n" is the length of the list
                   10097:     0 BEGIN ( list1 n1 )
                   10098:         over
                   10099:     WHILE ( list1 n1 )
                   10100:         1+ swap list-next @@ swap
                   10101:     REPEAT
                   10102:     nip ;
1.57      anton    10103: @end example
                   10104: 
1.78      anton    10105: You can reserve memory for a list node in the dictionary with
                   10106: @code{list% %allot}, which leaves the address of the list node on the
                   10107: stack. For the equivalent allocation on the heap you can use @code{list%
                   10108: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   10109: use @code{list% %allocate}). You can get the the size of a list
                   10110: node with @code{list% %size} and its alignment with @code{list%
                   10111: %alignment}.
                   10112: 
                   10113: Note that in ANS Forth the body of a @code{create}d word is
                   10114: @code{aligned} but not necessarily @code{faligned};
                   10115: therefore, if you do a:
1.57      anton    10116: 
                   10117: @example
1.78      anton    10118: create @emph{name} foo% %allot drop
1.57      anton    10119: @end example
                   10120: 
1.78      anton    10121: @noindent
                   10122: then the memory alloted for @code{foo%} is guaranteed to start at the
                   10123: body of @code{@emph{name}} only if @code{foo%} contains only character,
                   10124: cell and double fields.  Therefore, if your structure contains floats,
                   10125: better use
1.57      anton    10126: 
                   10127: @example
1.78      anton    10128: foo% %allot constant @emph{name}
1.57      anton    10129: @end example
                   10130: 
1.78      anton    10131: @cindex structures containing structures
                   10132: You can include a structure @code{foo%} as a field of
                   10133: another structure, like this:
1.65      anton    10134: @example
1.78      anton    10135: struct
                   10136: ...
                   10137:     foo% field ...
                   10138: ...
                   10139: end-struct ...
1.65      anton    10140: @end example
1.52      anton    10141: 
1.78      anton    10142: @cindex structure extension
                   10143: @cindex extended records
                   10144: Instead of starting with an empty structure, you can extend an
                   10145: existing structure. E.g., a plain linked list without data, as defined
                   10146: above, is hardly useful; You can extend it to a linked list of integers,
                   10147: like this:@footnote{This feature is also known as @emph{extended
                   10148: records}. It is the main innovation in the Oberon language; in other
                   10149: words, adding this feature to Modula-2 led Wirth to create a new
                   10150: language, write a new compiler etc.  Adding this feature to Forth just
                   10151: required a few lines of code.}
1.52      anton    10152: 
1.78      anton    10153: @example
                   10154: list%
                   10155:     cell% field intlist-int
                   10156: end-struct intlist%
                   10157: @end example
1.55      anton    10158: 
1.78      anton    10159: @code{intlist%} is a structure with two fields:
                   10160: @code{list-next} and @code{intlist-int}.
1.55      anton    10161: 
1.78      anton    10162: @cindex structures containing arrays
                   10163: You can specify an array type containing @emph{n} elements of
                   10164: type @code{foo%} like this:
1.55      anton    10165: 
                   10166: @example
1.78      anton    10167: foo% @emph{n} *
1.56      anton    10168: @end example
1.55      anton    10169: 
1.78      anton    10170: You can use this array type in any place where you can use a normal
                   10171: type, e.g., when defining a @code{field}, or with
                   10172: @code{%allot}.
                   10173: 
                   10174: @cindex first field optimization
                   10175: The first field is at the base address of a structure and the word for
                   10176: this field (e.g., @code{list-next}) actually does not change the address
                   10177: on the stack. You may be tempted to leave it away in the interest of
                   10178: run-time and space efficiency. This is not necessary, because the
                   10179: structure package optimizes this case: If you compile a first-field
                   10180: words, no code is generated. So, in the interest of readability and
                   10181: maintainability you should include the word for the field when accessing
                   10182: the field.
1.52      anton    10183: 
                   10184: 
1.78      anton    10185: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   10186: @subsection Structure Naming Convention
                   10187: @cindex structure naming convention
1.52      anton    10188: 
1.78      anton    10189: The field names that come to (my) mind are often quite generic, and,
                   10190: if used, would cause frequent name clashes. E.g., many structures
                   10191: probably contain a @code{counter} field. The structure names
                   10192: that come to (my) mind are often also the logical choice for the names
                   10193: of words that create such a structure.
1.52      anton    10194: 
1.78      anton    10195: Therefore, I have adopted the following naming conventions: 
1.52      anton    10196: 
1.78      anton    10197: @itemize @bullet
                   10198: @cindex field naming convention
                   10199: @item
                   10200: The names of fields are of the form
                   10201: @code{@emph{struct}-@emph{field}}, where
                   10202: @code{@emph{struct}} is the basic name of the structure, and
                   10203: @code{@emph{field}} is the basic name of the field. You can
                   10204: think of field words as converting the (address of the)
                   10205: structure into the (address of the) field.
1.52      anton    10206: 
1.78      anton    10207: @cindex structure naming convention
                   10208: @item
                   10209: The names of structures are of the form
                   10210: @code{@emph{struct}%}, where
                   10211: @code{@emph{struct}} is the basic name of the structure.
                   10212: @end itemize
1.52      anton    10213: 
1.78      anton    10214: This naming convention does not work that well for fields of extended
                   10215: structures; e.g., the integer list structure has a field
                   10216: @code{intlist-int}, but has @code{list-next}, not
                   10217: @code{intlist-next}.
1.53      anton    10218: 
1.78      anton    10219: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   10220: @subsection Structure Implementation
                   10221: @cindex structure implementation
                   10222: @cindex implementation of structures
1.52      anton    10223: 
1.78      anton    10224: The central idea in the implementation is to pass the data about the
                   10225: structure being built on the stack, not in some global
                   10226: variable. Everything else falls into place naturally once this design
                   10227: decision is made.
1.53      anton    10228: 
1.78      anton    10229: The type description on the stack is of the form @emph{align
                   10230: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   10231: very simple.
1.53      anton    10232: 
1.78      anton    10233: @code{field} is a defining word that uses @code{Create}
                   10234: and @code{DOES>}. The body of the field contains the offset
                   10235: of the field, and the normal @code{DOES>} action is simply:
1.53      anton    10236: 
                   10237: @example
1.78      anton    10238: @@ +
1.53      anton    10239: @end example
                   10240: 
1.78      anton    10241: @noindent
                   10242: i.e., add the offset to the address, giving the stack effect
                   10243: @i{addr1 -- addr2} for a field.
                   10244: 
                   10245: @cindex first field optimization, implementation
                   10246: This simple structure is slightly complicated by the optimization
                   10247: for fields with offset 0, which requires a different
                   10248: @code{DOES>}-part (because we cannot rely on there being
                   10249: something on the stack if such a field is invoked during
                   10250: compilation). Therefore, we put the different @code{DOES>}-parts
                   10251: in separate words, and decide which one to invoke based on the
                   10252: offset. For a zero offset, the field is basically a noop; it is
                   10253: immediate, and therefore no code is generated when it is compiled.
1.53      anton    10254: 
1.183     anton    10255: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
1.78      anton    10256: @subsection Structure Glossary
                   10257: @cindex structure glossary
1.53      anton    10258: 
1.5       anton    10259: 
1.78      anton    10260: doc-%align
                   10261: doc-%alignment
                   10262: doc-%alloc
                   10263: doc-%allocate
                   10264: doc-%allot
                   10265: doc-cell%
                   10266: doc-char%
                   10267: doc-dfloat%
                   10268: doc-double%
                   10269: doc-end-struct
                   10270: doc-field
                   10271: doc-float%
                   10272: doc-naligned
                   10273: doc-sfloat%
                   10274: doc-%size
                   10275: doc-struct
1.54      anton    10276: 
                   10277: 
1.183     anton    10278: @node Forth200x Structures,  , Structure Glossary, Structures
                   10279: @subsection Forth200x Structures
                   10280: @cindex Structures in Forth200x
                   10281: 
                   10282: The Forth 200x standard defines a slightly less convenient form of
                   10283: structures.  In general (when using @code{field+}, you have to perform
                   10284: the alignment yourself, but there are a number of convenience words
                   10285: (e.g., @code{field:} that perform the alignment for you.
                   10286: 
                   10287: A typical usage example is:
                   10288: 
                   10289: @example
                   10290: 0
                   10291:   field:                   s-a
                   10292:   faligned 2 floats +field s-b
                   10293: constant s-struct
                   10294: @end example
                   10295: 
                   10296: An alternative way of writing this structure is:
                   10297: 
                   10298: @example
                   10299: begin-structure s-struct
                   10300:   field:                   s-a
                   10301:   faligned 2 floats +field s-b
                   10302: end-structure
                   10303: @end example
                   10304: 
                   10305: doc-begin-structure
                   10306: doc-end-structure
                   10307: doc-+field
                   10308: doc-cfield:
                   10309: doc-field:
                   10310: doc-2field:
                   10311: doc-ffield:
                   10312: doc-sffield:
                   10313: doc-dffield:
                   10314: 
1.26      crook    10315: @c -------------------------------------------------------------
1.78      anton    10316: @node Object-oriented Forth, Programming Tools, Structures, Words
                   10317: @section Object-oriented Forth
                   10318: 
                   10319: Gforth comes with three packages for object-oriented programming:
                   10320: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   10321: is preloaded, so you have to @code{include} them before use. The most
                   10322: important differences between these packages (and others) are discussed
                   10323: in @ref{Comparison with other object models}. All packages are written
                   10324: in ANS Forth and can be used with any other ANS Forth.
1.5       anton    10325: 
1.78      anton    10326: @menu
                   10327: * Why object-oriented programming?::  
                   10328: * Object-Oriented Terminology::  
                   10329: * Objects::                     
                   10330: * OOF::                         
                   10331: * Mini-OOF::                    
                   10332: * Comparison with other object models::  
                   10333: @end menu
1.5       anton    10334: 
1.78      anton    10335: @c ----------------------------------------------------------------
                   10336: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
                   10337: @subsection Why object-oriented programming?
                   10338: @cindex object-oriented programming motivation
                   10339: @cindex motivation for object-oriented programming
1.44      crook    10340: 
1.78      anton    10341: Often we have to deal with several data structures (@emph{objects}),
                   10342: that have to be treated similarly in some respects, but differently in
                   10343: others. Graphical objects are the textbook example: circles, triangles,
                   10344: dinosaurs, icons, and others, and we may want to add more during program
                   10345: development. We want to apply some operations to any graphical object,
                   10346: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   10347: has to do something different for every kind of object.
                   10348: @comment TODO add some other operations eg perimeter, area
                   10349: @comment and tie in to concrete examples later..
1.5       anton    10350: 
1.78      anton    10351: We could implement @code{draw} as a big @code{CASE}
                   10352: control structure that executes the appropriate code depending on the
                   10353: kind of object to be drawn. This would be not be very elegant, and,
                   10354: moreover, we would have to change @code{draw} every time we add
                   10355: a new kind of graphical object (say, a spaceship).
1.44      crook    10356: 
1.78      anton    10357: What we would rather do is: When defining spaceships, we would tell
                   10358: the system: ``Here's how you @code{draw} a spaceship; you figure
                   10359: out the rest''.
1.5       anton    10360: 
1.78      anton    10361: This is the problem that all systems solve that (rightfully) call
                   10362: themselves object-oriented; the object-oriented packages presented here
                   10363: solve this problem (and not much else).
                   10364: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44      crook    10365: 
1.78      anton    10366: @c ------------------------------------------------------------------------
                   10367: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
                   10368: @subsection Object-Oriented Terminology
                   10369: @cindex object-oriented terminology
                   10370: @cindex terminology for object-oriented programming
1.5       anton    10371: 
1.78      anton    10372: This section is mainly for reference, so you don't have to understand
                   10373: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   10374: short:
1.44      crook    10375: 
1.78      anton    10376: @table @emph
                   10377: @cindex class
                   10378: @item class
                   10379: a data structure definition with some extras.
1.5       anton    10380: 
1.78      anton    10381: @cindex object
                   10382: @item object
                   10383: an instance of the data structure described by the class definition.
1.5       anton    10384: 
1.78      anton    10385: @cindex instance variables
                   10386: @item instance variables
                   10387: fields of the data structure.
1.5       anton    10388: 
1.78      anton    10389: @cindex selector
                   10390: @cindex method selector
                   10391: @cindex virtual function
                   10392: @item selector
                   10393: (or @emph{method selector}) a word (e.g.,
                   10394: @code{draw}) that performs an operation on a variety of data
                   10395: structures (classes). A selector describes @emph{what} operation to
                   10396: perform. In C++ terminology: a (pure) virtual function.
1.5       anton    10397: 
1.78      anton    10398: @cindex method
                   10399: @item method
                   10400: the concrete definition that performs the operation
                   10401: described by the selector for a specific class. A method specifies
                   10402: @emph{how} the operation is performed for a specific class.
1.5       anton    10403: 
1.78      anton    10404: @cindex selector invocation
                   10405: @cindex message send
                   10406: @cindex invoking a selector
                   10407: @item selector invocation
                   10408: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   10409: is used for determining which method is used. In Smalltalk terminology:
                   10410: a message (consisting of the selector and the other arguments) is sent
                   10411: to the object.
1.5       anton    10412: 
1.78      anton    10413: @cindex receiving object
                   10414: @item receiving object
                   10415: the object used for determining the method executed by a selector
                   10416: invocation. In the @file{objects.fs} model, it is the object that is on
                   10417: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   10418: the Smalltalk @emph{message} terminology.)
1.5       anton    10419: 
1.78      anton    10420: @cindex child class
                   10421: @cindex parent class
                   10422: @cindex inheritance
                   10423: @item child class
                   10424: a class that has (@emph{inherits}) all properties (instance variables,
                   10425: selectors, methods) from a @emph{parent class}. In Smalltalk
                   10426: terminology: The subclass inherits from the superclass. In C++
                   10427: terminology: The derived class inherits from the base class.
1.5       anton    10428: 
1.78      anton    10429: @end table
1.5       anton    10430: 
1.78      anton    10431: @c If you wonder about the message sending terminology, it comes from
                   10432: @c a time when each object had it's own task and objects communicated via
                   10433: @c message passing; eventually the Smalltalk developers realized that
                   10434: @c they can do most things through simple (indirect) calls. They kept the
                   10435: @c terminology.
1.5       anton    10436: 
1.78      anton    10437: @c --------------------------------------------------------------
                   10438: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   10439: @subsection The @file{objects.fs} model
                   10440: @cindex objects
                   10441: @cindex object-oriented programming
1.26      crook    10442: 
1.78      anton    10443: @cindex @file{objects.fs}
                   10444: @cindex @file{oof.fs}
1.26      crook    10445: 
1.78      anton    10446: This section describes the @file{objects.fs} package. This material also
                   10447: has been published in M. Anton Ertl,
                   10448: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
                   10449: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
                   10450: 37--43.
                   10451: @c McKewan's and Zsoter's packages
1.26      crook    10452: 
1.78      anton    10453: This section assumes that you have read @ref{Structures}.
1.5       anton    10454: 
1.78      anton    10455: The techniques on which this model is based have been used to implement
                   10456: the parser generator, Gray, and have also been used in Gforth for
                   10457: implementing the various flavours of word lists (hashed or not,
                   10458: case-sensitive or not, special-purpose word lists for locals etc.).
1.5       anton    10459: 
                   10460: 
1.26      crook    10461: @menu
1.78      anton    10462: * Properties of the Objects model::  
                   10463: * Basic Objects Usage::         
                   10464: * The Objects base class::      
                   10465: * Creating objects::            
                   10466: * Object-Oriented Programming Style::  
                   10467: * Class Binding::               
                   10468: * Method conveniences::         
                   10469: * Classes and Scoping::         
                   10470: * Dividing classes::            
                   10471: * Object Interfaces::           
                   10472: * Objects Implementation::      
                   10473: * Objects Glossary::            
1.26      crook    10474: @end menu
1.5       anton    10475: 
1.78      anton    10476: Marcel Hendrix provided helpful comments on this section.
1.5       anton    10477: 
1.78      anton    10478: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   10479: @subsubsection Properties of the @file{objects.fs} model
                   10480: @cindex @file{objects.fs} properties
1.5       anton    10481: 
1.78      anton    10482: @itemize @bullet
                   10483: @item
                   10484: It is straightforward to pass objects on the stack. Passing
                   10485: selectors on the stack is a little less convenient, but possible.
1.44      crook    10486: 
1.78      anton    10487: @item
                   10488: Objects are just data structures in memory, and are referenced by their
                   10489: address. You can create words for objects with normal defining words
                   10490: like @code{constant}. Likewise, there is no difference between instance
                   10491: variables that contain objects and those that contain other data.
1.5       anton    10492: 
1.78      anton    10493: @item
                   10494: Late binding is efficient and easy to use.
1.44      crook    10495: 
1.78      anton    10496: @item
                   10497: It avoids parsing, and thus avoids problems with state-smartness
                   10498: and reduced extensibility; for convenience there are a few parsing
                   10499: words, but they have non-parsing counterparts. There are also a few
                   10500: defining words that parse. This is hard to avoid, because all standard
                   10501: defining words parse (except @code{:noname}); however, such
                   10502: words are not as bad as many other parsing words, because they are not
                   10503: state-smart.
1.5       anton    10504: 
1.78      anton    10505: @item
                   10506: It does not try to incorporate everything. It does a few things and does
                   10507: them well (IMO). In particular, this model was not designed to support
                   10508: information hiding (although it has features that may help); you can use
                   10509: a separate package for achieving this.
1.5       anton    10510: 
1.78      anton    10511: @item
                   10512: It is layered; you don't have to learn and use all features to use this
                   10513: model. Only a few features are necessary (@pxref{Basic Objects Usage},
                   10514: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
                   10515: are optional and independent of each other.
1.5       anton    10516: 
1.78      anton    10517: @item
                   10518: An implementation in ANS Forth is available.
1.5       anton    10519: 
1.78      anton    10520: @end itemize
1.5       anton    10521: 
1.44      crook    10522: 
1.78      anton    10523: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   10524: @subsubsection Basic @file{objects.fs} Usage
                   10525: @cindex basic objects usage
                   10526: @cindex objects, basic usage
1.5       anton    10527: 
1.78      anton    10528: You can define a class for graphical objects like this:
1.44      crook    10529: 
1.78      anton    10530: @cindex @code{class} usage
                   10531: @cindex @code{end-class} usage
                   10532: @cindex @code{selector} usage
1.5       anton    10533: @example
1.78      anton    10534: object class \ "object" is the parent class
                   10535:   selector draw ( x y graphical -- )
                   10536: end-class graphical
                   10537: @end example
                   10538: 
                   10539: This code defines a class @code{graphical} with an
                   10540: operation @code{draw}.  We can perform the operation
                   10541: @code{draw} on any @code{graphical} object, e.g.:
                   10542: 
                   10543: @example
                   10544: 100 100 t-rex draw
1.26      crook    10545: @end example
1.5       anton    10546: 
1.78      anton    10547: @noindent
                   10548: where @code{t-rex} is a word (say, a constant) that produces a
                   10549: graphical object.
                   10550: 
                   10551: @comment TODO add a 2nd operation eg perimeter.. and use for
                   10552: @comment a concrete example
1.5       anton    10553: 
1.78      anton    10554: @cindex abstract class
                   10555: How do we create a graphical object? With the present definitions,
                   10556: we cannot create a useful graphical object. The class
                   10557: @code{graphical} describes graphical objects in general, but not
                   10558: any concrete graphical object type (C++ users would call it an
                   10559: @emph{abstract class}); e.g., there is no method for the selector
                   10560: @code{draw} in the class @code{graphical}.
1.5       anton    10561: 
1.78      anton    10562: For concrete graphical objects, we define child classes of the
                   10563: class @code{graphical}, e.g.:
1.5       anton    10564: 
1.78      anton    10565: @cindex @code{overrides} usage
                   10566: @cindex @code{field} usage in class definition
1.26      crook    10567: @example
1.78      anton    10568: graphical class \ "graphical" is the parent class
                   10569:   cell% field circle-radius
1.5       anton    10570: 
1.78      anton    10571: :noname ( x y circle -- )
                   10572:   circle-radius @@ draw-circle ;
                   10573: overrides draw
1.5       anton    10574: 
1.78      anton    10575: :noname ( n-radius circle -- )
                   10576:   circle-radius ! ;
                   10577: overrides construct
1.5       anton    10578: 
1.78      anton    10579: end-class circle
                   10580: @end example
1.44      crook    10581: 
1.78      anton    10582: Here we define a class @code{circle} as a child of @code{graphical},
                   10583: with field @code{circle-radius} (which behaves just like a field
                   10584: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   10585: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   10586: defined in @code{object}, the parent class of @code{graphical}).
1.5       anton    10587: 
1.78      anton    10588: Now we can create a circle on the heap (i.e.,
                   10589: @code{allocate}d memory) with:
1.44      crook    10590: 
1.78      anton    10591: @cindex @code{heap-new} usage
1.5       anton    10592: @example
1.78      anton    10593: 50 circle heap-new constant my-circle
1.5       anton    10594: @end example
                   10595: 
1.78      anton    10596: @noindent
                   10597: @code{heap-new} invokes @code{construct}, thus
                   10598: initializing the field @code{circle-radius} with 50. We can draw
                   10599: this new circle at (100,100) with:
1.5       anton    10600: 
                   10601: @example
1.78      anton    10602: 100 100 my-circle draw
1.5       anton    10603: @end example
                   10604: 
1.78      anton    10605: @cindex selector invocation, restrictions
                   10606: @cindex class definition, restrictions
                   10607: Note: You can only invoke a selector if the object on the TOS
                   10608: (the receiving object) belongs to the class where the selector was
                   10609: defined or one of its descendents; e.g., you can invoke
                   10610: @code{draw} only for objects belonging to @code{graphical}
                   10611: or its descendents (e.g., @code{circle}).  Immediately before
                   10612: @code{end-class}, the search order has to be the same as
                   10613: immediately after @code{class}.
                   10614: 
                   10615: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   10616: @subsubsection The @file{object.fs} base class
                   10617: @cindex @code{object} class
                   10618: 
                   10619: When you define a class, you have to specify a parent class.  So how do
                   10620: you start defining classes? There is one class available from the start:
                   10621: @code{object}. It is ancestor for all classes and so is the
                   10622: only class that has no parent. It has two selectors: @code{construct}
                   10623: and @code{print}.
                   10624: 
                   10625: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   10626: @subsubsection Creating objects
                   10627: @cindex creating objects
                   10628: @cindex object creation
                   10629: @cindex object allocation options
                   10630: 
                   10631: @cindex @code{heap-new} discussion
                   10632: @cindex @code{dict-new} discussion
                   10633: @cindex @code{construct} discussion
                   10634: You can create and initialize an object of a class on the heap with
                   10635: @code{heap-new} ( ... class -- object ) and in the dictionary
                   10636: (allocation with @code{allot}) with @code{dict-new} (
                   10637: ... class -- object ). Both words invoke @code{construct}, which
                   10638: consumes the stack items indicated by "..." above.
                   10639: 
                   10640: @cindex @code{init-object} discussion
                   10641: @cindex @code{class-inst-size} discussion
                   10642: If you want to allocate memory for an object yourself, you can get its
                   10643: alignment and size with @code{class-inst-size 2@@} ( class --
                   10644: align size ). Once you have memory for an object, you can initialize
                   10645: it with @code{init-object} ( ... class object -- );
                   10646: @code{construct} does only a part of the necessary work.
                   10647: 
                   10648: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   10649: @subsubsection Object-Oriented Programming Style
                   10650: @cindex object-oriented programming style
                   10651: @cindex programming style, object-oriented
1.5       anton    10652: 
1.78      anton    10653: This section is not exhaustive.
1.5       anton    10654: 
1.78      anton    10655: @cindex stack effects of selectors
                   10656: @cindex selectors and stack effects
                   10657: In general, it is a good idea to ensure that all methods for the
                   10658: same selector have the same stack effect: when you invoke a selector,
                   10659: you often have no idea which method will be invoked, so, unless all
                   10660: methods have the same stack effect, you will not know the stack effect
                   10661: of the selector invocation.
1.5       anton    10662: 
1.78      anton    10663: One exception to this rule is methods for the selector
                   10664: @code{construct}. We know which method is invoked, because we
                   10665: specify the class to be constructed at the same place. Actually, I
                   10666: defined @code{construct} as a selector only to give the users a
                   10667: convenient way to specify initialization. The way it is used, a
                   10668: mechanism different from selector invocation would be more natural
                   10669: (but probably would take more code and more space to explain).
1.5       anton    10670: 
1.78      anton    10671: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   10672: @subsubsection Class Binding
                   10673: @cindex class binding
                   10674: @cindex early binding
1.5       anton    10675: 
1.78      anton    10676: @cindex late binding
                   10677: Normal selector invocations determine the method at run-time depending
                   10678: on the class of the receiving object. This run-time selection is called
                   10679: @i{late binding}.
1.5       anton    10680: 
1.78      anton    10681: Sometimes it's preferable to invoke a different method. For example,
                   10682: you might want to use the simple method for @code{print}ing
                   10683: @code{object}s instead of the possibly long-winded @code{print} method
                   10684: of the receiver class. You can achieve this by replacing the invocation
                   10685: of @code{print} with:
1.5       anton    10686: 
1.78      anton    10687: @cindex @code{[bind]} usage
1.5       anton    10688: @example
1.78      anton    10689: [bind] object print
1.5       anton    10690: @end example
                   10691: 
1.78      anton    10692: @noindent
                   10693: in compiled code or:
                   10694: 
                   10695: @cindex @code{bind} usage
1.5       anton    10696: @example
1.78      anton    10697: bind object print
1.5       anton    10698: @end example
                   10699: 
1.78      anton    10700: @cindex class binding, alternative to
                   10701: @noindent
                   10702: in interpreted code. Alternatively, you can define the method with a
                   10703: name (e.g., @code{print-object}), and then invoke it through the
                   10704: name. Class binding is just a (often more convenient) way to achieve
                   10705: the same effect; it avoids name clutter and allows you to invoke
                   10706: methods directly without naming them first.
1.5       anton    10707: 
1.78      anton    10708: @cindex superclass binding
                   10709: @cindex parent class binding
                   10710: A frequent use of class binding is this: When we define a method
                   10711: for a selector, we often want the method to do what the selector does
                   10712: in the parent class, and a little more. There is a special word for
                   10713: this purpose: @code{[parent]}; @code{[parent]
                   10714: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   10715: selector}}, where @code{@emph{parent}} is the parent
                   10716: class of the current class. E.g., a method definition might look like:
1.44      crook    10717: 
1.78      anton    10718: @cindex @code{[parent]} usage
                   10719: @example
                   10720: :noname
                   10721:   dup [parent] foo \ do parent's foo on the receiving object
                   10722:   ... \ do some more
                   10723: ; overrides foo
                   10724: @end example
1.6       pazsan   10725: 
1.78      anton    10726: @cindex class binding as optimization
                   10727: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   10728: March 1997), Andrew McKewan presents class binding as an optimization
                   10729: technique. I recommend not using it for this purpose unless you are in
                   10730: an emergency. Late binding is pretty fast with this model anyway, so the
                   10731: benefit of using class binding is small; the cost of using class binding
                   10732: where it is not appropriate is reduced maintainability.
1.44      crook    10733: 
1.78      anton    10734: While we are at programming style questions: You should bind
                   10735: selectors only to ancestor classes of the receiving object. E.g., say,
                   10736: you know that the receiving object is of class @code{foo} or its
                   10737: descendents; then you should bind only to @code{foo} and its
                   10738: ancestors.
1.12      anton    10739: 
1.78      anton    10740: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   10741: @subsubsection Method conveniences
                   10742: @cindex method conveniences
1.44      crook    10743: 
1.78      anton    10744: In a method you usually access the receiving object pretty often.  If
                   10745: you define the method as a plain colon definition (e.g., with
                   10746: @code{:noname}), you may have to do a lot of stack
                   10747: gymnastics. To avoid this, you can define the method with @code{m:
                   10748: ... ;m}. E.g., you could define the method for
                   10749: @code{draw}ing a @code{circle} with
1.6       pazsan   10750: 
1.78      anton    10751: @cindex @code{this} usage
                   10752: @cindex @code{m:} usage
                   10753: @cindex @code{;m} usage
                   10754: @example
                   10755: m: ( x y circle -- )
                   10756:   ( x y ) this circle-radius @@ draw-circle ;m
                   10757: @end example
1.6       pazsan   10758: 
1.78      anton    10759: @cindex @code{exit} in @code{m: ... ;m}
                   10760: @cindex @code{exitm} discussion
                   10761: @cindex @code{catch} in @code{m: ... ;m}
                   10762: When this method is executed, the receiver object is removed from the
                   10763: stack; you can access it with @code{this} (admittedly, in this
                   10764: example the use of @code{m: ... ;m} offers no advantage). Note
                   10765: that I specify the stack effect for the whole method (i.e. including
                   10766: the receiver object), not just for the code between @code{m:}
                   10767: and @code{;m}. You cannot use @code{exit} in
                   10768: @code{m:...;m}; instead, use
                   10769: @code{exitm}.@footnote{Moreover, for any word that calls
                   10770: @code{catch} and was defined before loading
                   10771: @code{objects.fs}, you have to redefine it like I redefined
                   10772: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12      anton    10773: 
1.78      anton    10774: @cindex @code{inst-var} usage
                   10775: You will frequently use sequences of the form @code{this
                   10776: @emph{field}} (in the example above: @code{this
                   10777: circle-radius}). If you use the field only in this way, you can
                   10778: define it with @code{inst-var} and eliminate the
                   10779: @code{this} before the field name. E.g., the @code{circle}
                   10780: class above could also be defined with:
1.6       pazsan   10781: 
1.78      anton    10782: @example
                   10783: graphical class
                   10784:   cell% inst-var radius
1.6       pazsan   10785: 
1.78      anton    10786: m: ( x y circle -- )
                   10787:   radius @@ draw-circle ;m
                   10788: overrides draw
1.6       pazsan   10789: 
1.78      anton    10790: m: ( n-radius circle -- )
                   10791:   radius ! ;m
                   10792: overrides construct
1.6       pazsan   10793: 
1.78      anton    10794: end-class circle
                   10795: @end example
1.6       pazsan   10796: 
1.78      anton    10797: @code{radius} can only be used in @code{circle} and its
                   10798: descendent classes and inside @code{m:...;m}.
1.6       pazsan   10799: 
1.78      anton    10800: @cindex @code{inst-value} usage
                   10801: You can also define fields with @code{inst-value}, which is
                   10802: to @code{inst-var} what @code{value} is to
                   10803: @code{variable}.  You can change the value of such a field with
                   10804: @code{[to-inst]}.  E.g., we could also define the class
                   10805: @code{circle} like this:
1.44      crook    10806: 
1.78      anton    10807: @example
                   10808: graphical class
                   10809:   inst-value radius
1.6       pazsan   10810: 
1.78      anton    10811: m: ( x y circle -- )
                   10812:   radius draw-circle ;m
                   10813: overrides draw
1.44      crook    10814: 
1.78      anton    10815: m: ( n-radius circle -- )
                   10816:   [to-inst] radius ;m
                   10817: overrides construct
1.6       pazsan   10818: 
1.78      anton    10819: end-class circle
                   10820: @end example
1.6       pazsan   10821: 
1.78      anton    10822: @c !! :m is easy to confuse with m:.  Another name would be better.
1.6       pazsan   10823: 
1.78      anton    10824: @c Finally, you can define named methods with @code{:m}.  One use of this
                   10825: @c feature is the definition of words that occur only in one class and are
                   10826: @c not intended to be overridden, but which still need method context
                   10827: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
                   10828: @c would be bound frequently, if defined anonymously.
1.6       pazsan   10829: 
                   10830: 
1.78      anton    10831: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
                   10832: @subsubsection Classes and Scoping
                   10833: @cindex classes and scoping
                   10834: @cindex scoping and classes
1.6       pazsan   10835: 
1.78      anton    10836: Inheritance is frequent, unlike structure extension. This exacerbates
                   10837: the problem with the field name convention (@pxref{Structure Naming
                   10838: Convention}): One always has to remember in which class the field was
                   10839: originally defined; changing a part of the class structure would require
                   10840: changes for renaming in otherwise unaffected code.
1.6       pazsan   10841: 
1.78      anton    10842: @cindex @code{inst-var} visibility
                   10843: @cindex @code{inst-value} visibility
                   10844: To solve this problem, I added a scoping mechanism (which was not in my
                   10845: original charter): A field defined with @code{inst-var} (or
                   10846: @code{inst-value}) is visible only in the class where it is defined and in
                   10847: the descendent classes of this class.  Using such fields only makes
                   10848: sense in @code{m:}-defined methods in these classes anyway.
1.6       pazsan   10849: 
1.78      anton    10850: This scoping mechanism allows us to use the unadorned field name,
                   10851: because name clashes with unrelated words become much less likely.
1.6       pazsan   10852: 
1.78      anton    10853: @cindex @code{protected} discussion
                   10854: @cindex @code{private} discussion
                   10855: Once we have this mechanism, we can also use it for controlling the
                   10856: visibility of other words: All words defined after
                   10857: @code{protected} are visible only in the current class and its
                   10858: descendents. @code{public} restores the compilation
                   10859: (i.e. @code{current}) word list that was in effect before. If you
                   10860: have several @code{protected}s without an intervening
                   10861: @code{public} or @code{set-current}, @code{public}
                   10862: will restore the compilation word list in effect before the first of
                   10863: these @code{protected}s.
1.6       pazsan   10864: 
1.78      anton    10865: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
                   10866: @subsubsection Dividing classes
                   10867: @cindex Dividing classes
                   10868: @cindex @code{methods}...@code{end-methods}
1.6       pazsan   10869: 
1.78      anton    10870: You may want to do the definition of methods separate from the
                   10871: definition of the class, its selectors, fields, and instance variables,
                   10872: i.e., separate the implementation from the definition.  You can do this
                   10873: in the following way:
1.6       pazsan   10874: 
1.78      anton    10875: @example
                   10876: graphical class
                   10877:   inst-value radius
                   10878: end-class circle
1.6       pazsan   10879: 
1.78      anton    10880: ... \ do some other stuff
1.6       pazsan   10881: 
1.78      anton    10882: circle methods \ now we are ready
1.44      crook    10883: 
1.78      anton    10884: m: ( x y circle -- )
                   10885:   radius draw-circle ;m
                   10886: overrides draw
1.6       pazsan   10887: 
1.78      anton    10888: m: ( n-radius circle -- )
                   10889:   [to-inst] radius ;m
                   10890: overrides construct
1.44      crook    10891: 
1.78      anton    10892: end-methods
                   10893: @end example
1.7       pazsan   10894: 
1.78      anton    10895: You can use several @code{methods}...@code{end-methods} sections.  The
                   10896: only things you can do to the class in these sections are: defining
                   10897: methods, and overriding the class's selectors.  You must not define new
                   10898: selectors or fields.
1.7       pazsan   10899: 
1.78      anton    10900: Note that you often have to override a selector before using it.  In
                   10901: particular, you usually have to override @code{construct} with a new
                   10902: method before you can invoke @code{heap-new} and friends.  E.g., you
                   10903: must not create a circle before the @code{overrides construct} sequence
                   10904: in the example above.
1.7       pazsan   10905: 
1.78      anton    10906: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
                   10907: @subsubsection Object Interfaces
                   10908: @cindex object interfaces
                   10909: @cindex interfaces for objects
1.7       pazsan   10910: 
1.78      anton    10911: In this model you can only call selectors defined in the class of the
                   10912: receiving objects or in one of its ancestors. If you call a selector
                   10913: with a receiving object that is not in one of these classes, the
                   10914: result is undefined; if you are lucky, the program crashes
                   10915: immediately.
1.7       pazsan   10916: 
1.78      anton    10917: @cindex selectors common to hardly-related classes
                   10918: Now consider the case when you want to have a selector (or several)
                   10919: available in two classes: You would have to add the selector to a
                   10920: common ancestor class, in the worst case to @code{object}. You
                   10921: may not want to do this, e.g., because someone else is responsible for
                   10922: this ancestor class.
1.7       pazsan   10923: 
1.78      anton    10924: The solution for this problem is interfaces. An interface is a
                   10925: collection of selectors. If a class implements an interface, the
                   10926: selectors become available to the class and its descendents. A class
                   10927: can implement an unlimited number of interfaces. For the problem
                   10928: discussed above, we would define an interface for the selector(s), and
                   10929: both classes would implement the interface.
1.7       pazsan   10930: 
1.78      anton    10931: As an example, consider an interface @code{storage} for
                   10932: writing objects to disk and getting them back, and a class
                   10933: @code{foo} that implements it. The code would look like this:
1.7       pazsan   10934: 
1.78      anton    10935: @cindex @code{interface} usage
                   10936: @cindex @code{end-interface} usage
                   10937: @cindex @code{implementation} usage
                   10938: @example
                   10939: interface
                   10940:   selector write ( file object -- )
                   10941:   selector read1 ( file object -- )
                   10942: end-interface storage
1.13      pazsan   10943: 
1.78      anton    10944: bar class
                   10945:   storage implementation
1.13      pazsan   10946: 
1.78      anton    10947: ... overrides write
                   10948: ... overrides read1
                   10949: ...
                   10950: end-class foo
                   10951: @end example
1.13      pazsan   10952: 
1.78      anton    10953: @noindent
                   10954: (I would add a word @code{read} @i{( file -- object )} that uses
                   10955: @code{read1} internally, but that's beyond the point illustrated
                   10956: here.)
1.13      pazsan   10957: 
1.78      anton    10958: Note that you cannot use @code{protected} in an interface; and
                   10959: of course you cannot define fields.
1.13      pazsan   10960: 
1.78      anton    10961: In the Neon model, all selectors are available for all classes;
                   10962: therefore it does not need interfaces. The price you pay in this model
                   10963: is slower late binding, and therefore, added complexity to avoid late
                   10964: binding.
1.13      pazsan   10965: 
1.78      anton    10966: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   10967: @subsubsection @file{objects.fs} Implementation
                   10968: @cindex @file{objects.fs} implementation
1.13      pazsan   10969: 
1.78      anton    10970: @cindex @code{object-map} discussion
                   10971: An object is a piece of memory, like one of the data structures
                   10972: described with @code{struct...end-struct}. It has a field
                   10973: @code{object-map} that points to the method map for the object's
                   10974: class.
1.13      pazsan   10975: 
1.78      anton    10976: @cindex method map
                   10977: @cindex virtual function table
                   10978: The @emph{method map}@footnote{This is Self terminology; in C++
                   10979: terminology: virtual function table.} is an array that contains the
                   10980: execution tokens (@i{xt}s) of the methods for the object's class. Each
                   10981: selector contains an offset into a method map.
1.13      pazsan   10982: 
1.78      anton    10983: @cindex @code{selector} implementation, class
                   10984: @code{selector} is a defining word that uses
                   10985: @code{CREATE} and @code{DOES>}. The body of the
                   10986: selector contains the offset; the @code{DOES>} action for a
                   10987: class selector is, basically:
1.8       pazsan   10988: 
                   10989: @example
1.78      anton    10990: ( object addr ) @@ over object-map @@ + @@ execute
1.13      pazsan   10991: @end example
                   10992: 
1.78      anton    10993: Since @code{object-map} is the first field of the object, it
                   10994: does not generate any code. As you can see, calling a selector has a
                   10995: small, constant cost.
1.26      crook    10996: 
1.78      anton    10997: @cindex @code{current-interface} discussion
                   10998: @cindex class implementation and representation
                   10999: A class is basically a @code{struct} combined with a method
                   11000: map. During the class definition the alignment and size of the class
                   11001: are passed on the stack, just as with @code{struct}s, so
                   11002: @code{field} can also be used for defining class
                   11003: fields. However, passing more items on the stack would be
                   11004: inconvenient, so @code{class} builds a data structure in memory,
                   11005: which is accessed through the variable
                   11006: @code{current-interface}. After its definition is complete, the
                   11007: class is represented on the stack by a pointer (e.g., as parameter for
                   11008: a child class definition).
1.26      crook    11009: 
1.78      anton    11010: A new class starts off with the alignment and size of its parent,
                   11011: and a copy of the parent's method map. Defining new fields extends the
                   11012: size and alignment; likewise, defining new selectors extends the
                   11013: method map. @code{overrides} just stores a new @i{xt} in the method
                   11014: map at the offset given by the selector.
1.13      pazsan   11015: 
1.78      anton    11016: @cindex class binding, implementation
                   11017: Class binding just gets the @i{xt} at the offset given by the selector
                   11018: from the class's method map and @code{compile,}s (in the case of
                   11019: @code{[bind]}) it.
1.13      pazsan   11020: 
1.78      anton    11021: @cindex @code{this} implementation
                   11022: @cindex @code{catch} and @code{this}
                   11023: @cindex @code{this} and @code{catch}
                   11024: I implemented @code{this} as a @code{value}. At the
                   11025: start of an @code{m:...;m} method the old @code{this} is
                   11026: stored to the return stack and restored at the end; and the object on
                   11027: the TOS is stored @code{TO this}. This technique has one
                   11028: disadvantage: If the user does not leave the method via
                   11029: @code{;m}, but via @code{throw} or @code{exit},
                   11030: @code{this} is not restored (and @code{exit} may
                   11031: crash). To deal with the @code{throw} problem, I have redefined
                   11032: @code{catch} to save and restore @code{this}; the same
                   11033: should be done with any word that can catch an exception. As for
                   11034: @code{exit}, I simply forbid it (as a replacement, there is
                   11035: @code{exitm}).
1.13      pazsan   11036: 
1.78      anton    11037: @cindex @code{inst-var} implementation
                   11038: @code{inst-var} is just the same as @code{field}, with
                   11039: a different @code{DOES>} action:
1.13      pazsan   11040: @example
1.78      anton    11041: @@ this +
1.8       pazsan   11042: @end example
1.78      anton    11043: Similar for @code{inst-value}.
1.8       pazsan   11044: 
1.78      anton    11045: @cindex class scoping implementation
                   11046: Each class also has a word list that contains the words defined with
                   11047: @code{inst-var} and @code{inst-value}, and its protected
                   11048: words. It also has a pointer to its parent. @code{class} pushes
                   11049: the word lists of the class and all its ancestors onto the search order stack,
                   11050: and @code{end-class} drops them.
1.20      pazsan   11051: 
1.78      anton    11052: @cindex interface implementation
                   11053: An interface is like a class without fields, parent and protected
                   11054: words; i.e., it just has a method map. If a class implements an
                   11055: interface, its method map contains a pointer to the method map of the
                   11056: interface. The positive offsets in the map are reserved for class
                   11057: methods, therefore interface map pointers have negative
                   11058: offsets. Interfaces have offsets that are unique throughout the
                   11059: system, unlike class selectors, whose offsets are only unique for the
                   11060: classes where the selector is available (invokable).
1.20      pazsan   11061: 
1.78      anton    11062: This structure means that interface selectors have to perform one
                   11063: indirection more than class selectors to find their method. Their body
                   11064: contains the interface map pointer offset in the class method map, and
                   11065: the method offset in the interface method map. The
                   11066: @code{does>} action for an interface selector is, basically:
1.20      pazsan   11067: 
                   11068: @example
1.78      anton    11069: ( object selector-body )
                   11070: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   11071: swap object-map @@ + @@ ( object selector-body map )
                   11072: swap selector-offset @@ + @@ execute
1.20      pazsan   11073: @end example
                   11074: 
1.78      anton    11075: where @code{object-map} and @code{selector-offset} are
                   11076: first fields and generate no code.
1.20      pazsan   11077: 
1.78      anton    11078: As a concrete example, consider the following code:
1.20      pazsan   11079: 
                   11080: @example
1.78      anton    11081: interface
                   11082:   selector if1sel1
                   11083:   selector if1sel2
                   11084: end-interface if1
1.20      pazsan   11085: 
1.78      anton    11086: object class
                   11087:   if1 implementation
                   11088:   selector cl1sel1
                   11089:   cell% inst-var cl1iv1
1.20      pazsan   11090: 
1.78      anton    11091: ' m1 overrides construct
                   11092: ' m2 overrides if1sel1
                   11093: ' m3 overrides if1sel2
                   11094: ' m4 overrides cl1sel2
                   11095: end-class cl1
1.20      pazsan   11096: 
1.78      anton    11097: create obj1 object dict-new drop
                   11098: create obj2 cl1    dict-new drop
                   11099: @end example
1.20      pazsan   11100: 
1.78      anton    11101: The data structure created by this code (including the data structure
                   11102: for @code{object}) is shown in the
                   11103: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
                   11104: @comment TODO add this diagram..
1.20      pazsan   11105: 
1.78      anton    11106: @node Objects Glossary,  , Objects Implementation, Objects
                   11107: @subsubsection @file{objects.fs} Glossary
                   11108: @cindex @file{objects.fs} Glossary
1.20      pazsan   11109: 
                   11110: 
1.78      anton    11111: doc---objects-bind
                   11112: doc---objects-<bind>
                   11113: doc---objects-bind'
                   11114: doc---objects-[bind]
                   11115: doc---objects-class
                   11116: doc---objects-class->map
                   11117: doc---objects-class-inst-size
                   11118: doc---objects-class-override!
1.79      anton    11119: doc---objects-class-previous
                   11120: doc---objects-class>order
1.78      anton    11121: doc---objects-construct
                   11122: doc---objects-current'
                   11123: doc---objects-[current]
                   11124: doc---objects-current-interface
                   11125: doc---objects-dict-new
                   11126: doc---objects-end-class
                   11127: doc---objects-end-class-noname
                   11128: doc---objects-end-interface
                   11129: doc---objects-end-interface-noname
                   11130: doc---objects-end-methods
                   11131: doc---objects-exitm
                   11132: doc---objects-heap-new
                   11133: doc---objects-implementation
                   11134: doc---objects-init-object
                   11135: doc---objects-inst-value
                   11136: doc---objects-inst-var
                   11137: doc---objects-interface
                   11138: doc---objects-m:
                   11139: doc---objects-:m
                   11140: doc---objects-;m
                   11141: doc---objects-method
                   11142: doc---objects-methods
                   11143: doc---objects-object
                   11144: doc---objects-overrides
                   11145: doc---objects-[parent]
                   11146: doc---objects-print
                   11147: doc---objects-protected
                   11148: doc---objects-public
                   11149: doc---objects-selector
                   11150: doc---objects-this
                   11151: doc---objects-<to-inst>
                   11152: doc---objects-[to-inst]
                   11153: doc---objects-to-this
                   11154: doc---objects-xt-new
1.20      pazsan   11155: 
                   11156: 
1.78      anton    11157: @c -------------------------------------------------------------
                   11158: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   11159: @subsection The @file{oof.fs} model
                   11160: @cindex oof
                   11161: @cindex object-oriented programming
1.20      pazsan   11162: 
1.78      anton    11163: @cindex @file{objects.fs}
                   11164: @cindex @file{oof.fs}
1.20      pazsan   11165: 
1.78      anton    11166: This section describes the @file{oof.fs} package.
1.20      pazsan   11167: 
1.78      anton    11168: The package described in this section has been used in bigFORTH since 1991, and
                   11169: used for two large applications: a chromatographic system used to
                   11170: create new medicaments, and a graphic user interface library (MINOS).
1.20      pazsan   11171: 
1.78      anton    11172: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   11173: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   11174: 10(2), 1994.
1.20      pazsan   11175: 
1.78      anton    11176: @menu
                   11177: * Properties of the OOF model::  
                   11178: * Basic OOF Usage::             
                   11179: * The OOF base class::          
                   11180: * Class Declaration::           
                   11181: * Class Implementation::        
                   11182: @end menu
1.20      pazsan   11183: 
1.78      anton    11184: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   11185: @subsubsection Properties of the @file{oof.fs} model
                   11186: @cindex @file{oof.fs} properties
1.20      pazsan   11187: 
1.78      anton    11188: @itemize @bullet
                   11189: @item
                   11190: This model combines object oriented programming with information
                   11191: hiding. It helps you writing large application, where scoping is
                   11192: necessary, because it provides class-oriented scoping.
1.20      pazsan   11193: 
1.78      anton    11194: @item
                   11195: Named objects, object pointers, and object arrays can be created,
                   11196: selector invocation uses the ``object selector'' syntax. Selector invocation
                   11197: to objects and/or selectors on the stack is a bit less convenient, but
                   11198: possible.
1.44      crook    11199: 
1.78      anton    11200: @item
                   11201: Selector invocation and instance variable usage of the active object is
                   11202: straightforward, since both make use of the active object.
1.44      crook    11203: 
1.78      anton    11204: @item
                   11205: Late binding is efficient and easy to use.
1.20      pazsan   11206: 
1.78      anton    11207: @item
                   11208: State-smart objects parse selectors. However, extensibility is provided
                   11209: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20      pazsan   11210: 
1.78      anton    11211: @item
                   11212: An implementation in ANS Forth is available.
1.20      pazsan   11213: 
1.78      anton    11214: @end itemize
1.23      crook    11215: 
                   11216: 
1.78      anton    11217: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   11218: @subsubsection Basic @file{oof.fs} Usage
                   11219: @cindex @file{oof.fs} usage
1.23      crook    11220: 
1.78      anton    11221: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23      crook    11222: 
1.78      anton    11223: You can define a class for graphical objects like this:
1.23      crook    11224: 
1.78      anton    11225: @cindex @code{class} usage
                   11226: @cindex @code{class;} usage
                   11227: @cindex @code{method} usage
                   11228: @example
                   11229: object class graphical \ "object" is the parent class
1.139     pazsan   11230:   method draw ( x y -- )
1.78      anton    11231: class;
                   11232: @end example
1.23      crook    11233: 
1.78      anton    11234: This code defines a class @code{graphical} with an
                   11235: operation @code{draw}.  We can perform the operation
                   11236: @code{draw} on any @code{graphical} object, e.g.:
1.23      crook    11237: 
1.78      anton    11238: @example
                   11239: 100 100 t-rex draw
                   11240: @end example
1.23      crook    11241: 
1.78      anton    11242: @noindent
                   11243: where @code{t-rex} is an object or object pointer, created with e.g.
                   11244: @code{graphical : t-rex}.
1.23      crook    11245: 
1.78      anton    11246: @cindex abstract class
                   11247: How do we create a graphical object? With the present definitions,
                   11248: we cannot create a useful graphical object. The class
                   11249: @code{graphical} describes graphical objects in general, but not
                   11250: any concrete graphical object type (C++ users would call it an
                   11251: @emph{abstract class}); e.g., there is no method for the selector
                   11252: @code{draw} in the class @code{graphical}.
1.23      crook    11253: 
1.78      anton    11254: For concrete graphical objects, we define child classes of the
                   11255: class @code{graphical}, e.g.:
1.23      crook    11256: 
1.78      anton    11257: @example
                   11258: graphical class circle \ "graphical" is the parent class
                   11259:   cell var circle-radius
                   11260: how:
                   11261:   : draw ( x y -- )
                   11262:     circle-radius @@ draw-circle ;
1.23      crook    11263: 
1.139     pazsan   11264:   : init ( n-radius -- )
1.78      anton    11265:     circle-radius ! ;
                   11266: class;
                   11267: @end example
1.1       anton    11268: 
1.78      anton    11269: Here we define a class @code{circle} as a child of @code{graphical},
                   11270: with a field @code{circle-radius}; it defines new methods for the
                   11271: selectors @code{draw} and @code{init} (@code{init} is defined in
                   11272: @code{object}, the parent class of @code{graphical}).
1.1       anton    11273: 
1.78      anton    11274: Now we can create a circle in the dictionary with:
1.1       anton    11275: 
1.78      anton    11276: @example
                   11277: 50 circle : my-circle
                   11278: @end example
1.21      crook    11279: 
1.78      anton    11280: @noindent
                   11281: @code{:} invokes @code{init}, thus initializing the field
                   11282: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   11283: with:
1.1       anton    11284: 
1.78      anton    11285: @example
                   11286: 100 100 my-circle draw
                   11287: @end example
1.1       anton    11288: 
1.78      anton    11289: @cindex selector invocation, restrictions
                   11290: @cindex class definition, restrictions
                   11291: Note: You can only invoke a selector if the receiving object belongs to
                   11292: the class where the selector was defined or one of its descendents;
                   11293: e.g., you can invoke @code{draw} only for objects belonging to
                   11294: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   11295: mechanism will check if you try to invoke a selector that is not
                   11296: defined in this class hierarchy, so you'll get an error at compilation
                   11297: time.
1.1       anton    11298: 
                   11299: 
1.78      anton    11300: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   11301: @subsubsection The @file{oof.fs} base class
                   11302: @cindex @file{oof.fs} base class
1.1       anton    11303: 
1.78      anton    11304: When you define a class, you have to specify a parent class.  So how do
                   11305: you start defining classes? There is one class available from the start:
                   11306: @code{object}. You have to use it as ancestor for all classes. It is the
                   11307: only class that has no parent. Classes are also objects, except that
                   11308: they don't have instance variables; class manipulation such as
                   11309: inheritance or changing definitions of a class is handled through
                   11310: selectors of the class @code{object}.
1.1       anton    11311: 
1.78      anton    11312: @code{object} provides a number of selectors:
1.1       anton    11313: 
1.78      anton    11314: @itemize @bullet
                   11315: @item
                   11316: @code{class} for subclassing, @code{definitions} to add definitions
                   11317: later on, and @code{class?} to get type informations (is the class a
                   11318: subclass of the class passed on the stack?).
1.1       anton    11319: 
1.78      anton    11320: doc---object-class
                   11321: doc---object-definitions
                   11322: doc---object-class?
1.1       anton    11323: 
                   11324: 
1.26      crook    11325: @item
1.78      anton    11326: @code{init} and @code{dispose} as constructor and destructor of the
                   11327: object. @code{init} is invocated after the object's memory is allocated,
                   11328: while @code{dispose} also handles deallocation. Thus if you redefine
                   11329: @code{dispose}, you have to call the parent's dispose with @code{super
                   11330: dispose}, too.
                   11331: 
                   11332: doc---object-init
                   11333: doc---object-dispose
                   11334: 
1.1       anton    11335: 
1.26      crook    11336: @item
1.78      anton    11337: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   11338: @code{[]} to create named and unnamed objects and object arrays or
                   11339: object pointers.
                   11340: 
                   11341: doc---object-new
                   11342: doc---object-new[]
                   11343: doc---object-:
                   11344: doc---object-ptr
                   11345: doc---object-asptr
                   11346: doc---object-[]
                   11347: 
1.1       anton    11348: 
1.26      crook    11349: @item
1.78      anton    11350: @code{::} and @code{super} for explicit scoping. You should use explicit
                   11351: scoping only for super classes or classes with the same set of instance
                   11352: variables. Explicitly-scoped selectors use early binding.
1.21      crook    11353: 
1.78      anton    11354: doc---object-::
                   11355: doc---object-super
1.21      crook    11356: 
                   11357: 
1.26      crook    11358: @item
1.78      anton    11359: @code{self} to get the address of the object
1.21      crook    11360: 
1.78      anton    11361: doc---object-self
1.21      crook    11362: 
                   11363: 
1.78      anton    11364: @item
                   11365: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   11366: pointers and instance defers.
1.21      crook    11367: 
1.78      anton    11368: doc---object-bind
                   11369: doc---object-bound
                   11370: doc---object-link
                   11371: doc---object-is
1.21      crook    11372: 
                   11373: 
1.78      anton    11374: @item
                   11375: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   11376: form the stack, and @code{postpone} to generate selector invocation code.
1.21      crook    11377: 
1.78      anton    11378: doc---object-'
                   11379: doc---object-postpone
1.21      crook    11380: 
                   11381: 
1.78      anton    11382: @item
                   11383: @code{with} and @code{endwith} to select the active object from the
                   11384: stack, and enable its scope. Using @code{with} and @code{endwith}
                   11385: also allows you to create code using selector @code{postpone} without being
                   11386: trapped by the state-smart objects.
1.21      crook    11387: 
1.78      anton    11388: doc---object-with
                   11389: doc---object-endwith
1.21      crook    11390: 
                   11391: 
1.78      anton    11392: @end itemize
1.21      crook    11393: 
1.78      anton    11394: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   11395: @subsubsection Class Declaration
                   11396: @cindex class declaration
1.21      crook    11397: 
1.78      anton    11398: @itemize @bullet
                   11399: @item
                   11400: Instance variables
1.21      crook    11401: 
1.78      anton    11402: doc---oof-var
1.21      crook    11403: 
                   11404: 
1.78      anton    11405: @item
                   11406: Object pointers
1.21      crook    11407: 
1.78      anton    11408: doc---oof-ptr
                   11409: doc---oof-asptr
1.21      crook    11410: 
                   11411: 
1.78      anton    11412: @item
                   11413: Instance defers
1.21      crook    11414: 
1.78      anton    11415: doc---oof-defer
1.21      crook    11416: 
                   11417: 
1.78      anton    11418: @item
                   11419: Method selectors
1.21      crook    11420: 
1.78      anton    11421: doc---oof-early
                   11422: doc---oof-method
1.21      crook    11423: 
                   11424: 
1.78      anton    11425: @item
                   11426: Class-wide variables
1.21      crook    11427: 
1.78      anton    11428: doc---oof-static
1.21      crook    11429: 
                   11430: 
1.78      anton    11431: @item
                   11432: End declaration
1.1       anton    11433: 
1.78      anton    11434: doc---oof-how:
                   11435: doc---oof-class;
1.21      crook    11436: 
                   11437: 
1.78      anton    11438: @end itemize
1.21      crook    11439: 
1.78      anton    11440: @c -------------------------------------------------------------
                   11441: @node Class Implementation,  , Class Declaration, OOF
                   11442: @subsubsection Class Implementation
                   11443: @cindex class implementation
1.21      crook    11444: 
1.78      anton    11445: @c -------------------------------------------------------------
                   11446: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   11447: @subsection The @file{mini-oof.fs} model
                   11448: @cindex mini-oof
1.21      crook    11449: 
1.78      anton    11450: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79      anton    11451: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78      anton    11452: and reduces to the bare minimum of features. This is based on a posting
                   11453: of Bernd Paysan in comp.lang.forth.
1.21      crook    11454: 
1.78      anton    11455: @menu
                   11456: * Basic Mini-OOF Usage::        
                   11457: * Mini-OOF Example::            
                   11458: * Mini-OOF Implementation::     
                   11459: @end menu
1.21      crook    11460: 
1.78      anton    11461: @c -------------------------------------------------------------
                   11462: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
                   11463: @subsubsection Basic @file{mini-oof.fs} Usage
                   11464: @cindex mini-oof usage
1.21      crook    11465: 
1.78      anton    11466: There is a base class (@code{class}, which allocates one cell for the
                   11467: object pointer) plus seven other words: to define a method, a variable,
                   11468: a class; to end a class, to resolve binding, to allocate an object and
                   11469: to compile a class method.
                   11470: @comment TODO better description of the last one
1.26      crook    11471: 
1.21      crook    11472: 
1.78      anton    11473: doc-object
                   11474: doc-method
                   11475: doc-var
                   11476: doc-class
                   11477: doc-end-class
                   11478: doc-defines
                   11479: doc-new
                   11480: doc-::
1.21      crook    11481: 
                   11482: 
                   11483: 
1.78      anton    11484: @c -------------------------------------------------------------
                   11485: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   11486: @subsubsection Mini-OOF Example
                   11487: @cindex mini-oof example
1.1       anton    11488: 
1.78      anton    11489: A short example shows how to use this package. This example, in slightly
                   11490: extended form, is supplied as @file{moof-exm.fs}
                   11491: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20      pazsan   11492: 
1.26      crook    11493: @example
1.78      anton    11494: object class
                   11495:   method init
                   11496:   method draw
                   11497: end-class graphical
1.26      crook    11498: @end example
1.20      pazsan   11499: 
1.78      anton    11500: This code defines a class @code{graphical} with an
                   11501: operation @code{draw}.  We can perform the operation
                   11502: @code{draw} on any @code{graphical} object, e.g.:
1.20      pazsan   11503: 
1.26      crook    11504: @example
1.78      anton    11505: 100 100 t-rex draw
1.26      crook    11506: @end example
1.12      anton    11507: 
1.78      anton    11508: where @code{t-rex} is an object or object pointer, created with e.g.
                   11509: @code{graphical new Constant t-rex}.
1.12      anton    11510: 
1.78      anton    11511: For concrete graphical objects, we define child classes of the
                   11512: class @code{graphical}, e.g.:
1.12      anton    11513: 
1.26      crook    11514: @example
                   11515: graphical class
1.78      anton    11516:   cell var circle-radius
                   11517: end-class circle \ "graphical" is the parent class
1.12      anton    11518: 
1.78      anton    11519: :noname ( x y -- )
                   11520:   circle-radius @@ draw-circle ; circle defines draw
                   11521: :noname ( r -- )
                   11522:   circle-radius ! ; circle defines init
                   11523: @end example
1.12      anton    11524: 
1.78      anton    11525: There is no implicit init method, so we have to define one. The creation
                   11526: code of the object now has to call init explicitely.
1.21      crook    11527: 
1.78      anton    11528: @example
                   11529: circle new Constant my-circle
                   11530: 50 my-circle init
1.12      anton    11531: @end example
                   11532: 
1.78      anton    11533: It is also possible to add a function to create named objects with
                   11534: automatic call of @code{init}, given that all objects have @code{init}
                   11535: on the same place:
1.38      anton    11536: 
1.78      anton    11537: @example
                   11538: : new: ( .. o "name" -- )
                   11539:     new dup Constant init ;
                   11540: 80 circle new: large-circle
                   11541: @end example
1.12      anton    11542: 
1.78      anton    11543: We can draw this new circle at (100,100) with:
1.12      anton    11544: 
1.78      anton    11545: @example
                   11546: 100 100 my-circle draw
                   11547: @end example
1.12      anton    11548: 
1.78      anton    11549: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
                   11550: @subsubsection @file{mini-oof.fs} Implementation
1.12      anton    11551: 
1.78      anton    11552: Object-oriented systems with late binding typically use a
                   11553: ``vtable''-approach: the first variable in each object is a pointer to a
                   11554: table, which contains the methods as function pointers. The vtable
                   11555: may also contain other information.
1.12      anton    11556: 
1.79      anton    11557: So first, let's declare selectors:
1.37      anton    11558: 
                   11559: @example
1.79      anton    11560: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
1.78      anton    11561:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
                   11562: @end example
1.37      anton    11563: 
1.79      anton    11564: During selector declaration, the number of selectors and instance
                   11565: variables is on the stack (in address units). @code{method} creates one
                   11566: selector and increments the selector number. To execute a selector, it
1.78      anton    11567: takes the object, fetches the vtable pointer, adds the offset, and
1.79      anton    11568: executes the method @i{xt} stored there. Each selector takes the object
                   11569: it is invoked with as top of stack parameter; it passes the parameters
                   11570: (including the object) unchanged to the appropriate method which should
1.78      anton    11571: consume that object.
1.37      anton    11572: 
1.78      anton    11573: Now, we also have to declare instance variables
1.37      anton    11574: 
1.78      anton    11575: @example
1.79      anton    11576: : var ( m v size "name" -- m v' ) Create  over , +
1.78      anton    11577:   DOES> ( o -- addr ) @@ + ;
1.37      anton    11578: @end example
                   11579: 
1.78      anton    11580: As before, a word is created with the current offset. Instance
                   11581: variables can have different sizes (cells, floats, doubles, chars), so
                   11582: all we do is take the size and add it to the offset. If your machine
                   11583: has alignment restrictions, put the proper @code{aligned} or
                   11584: @code{faligned} before the variable, to adjust the variable
                   11585: offset. That's why it is on the top of stack.
1.37      anton    11586: 
1.78      anton    11587: We need a starting point (the base object) and some syntactic sugar:
1.37      anton    11588: 
1.78      anton    11589: @example
                   11590: Create object  1 cells , 2 cells ,
1.79      anton    11591: : class ( class -- class selectors vars ) dup 2@@ ;
1.78      anton    11592: @end example
1.12      anton    11593: 
1.78      anton    11594: For inheritance, the vtable of the parent object has to be
                   11595: copied when a new, derived class is declared. This gives all the
                   11596: methods of the parent class, which can be overridden, though.
1.12      anton    11597: 
1.78      anton    11598: @example
1.79      anton    11599: : end-class  ( class selectors vars "name" -- )
1.78      anton    11600:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   11601:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
                   11602: @end example
1.12      anton    11603: 
1.78      anton    11604: The first line creates the vtable, initialized with
                   11605: @code{noop}s. The second line is the inheritance mechanism, it
                   11606: copies the xts from the parent vtable.
1.12      anton    11607: 
1.78      anton    11608: We still have no way to define new methods, let's do that now:
1.12      anton    11609: 
1.26      crook    11610: @example
1.79      anton    11611: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78      anton    11612: @end example
1.12      anton    11613: 
1.78      anton    11614: To allocate a new object, we need a word, too:
1.12      anton    11615: 
1.78      anton    11616: @example
                   11617: : new ( class -- o )  here over @@ allot swap over ! ;
1.12      anton    11618: @end example
                   11619: 
1.78      anton    11620: Sometimes derived classes want to access the method of the
                   11621: parent object. There are two ways to achieve this with Mini-OOF:
                   11622: first, you could use named words, and second, you could look up the
                   11623: vtable of the parent object.
1.12      anton    11624: 
1.78      anton    11625: @example
                   11626: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
                   11627: @end example
1.12      anton    11628: 
                   11629: 
1.78      anton    11630: Nothing can be more confusing than a good example, so here is
                   11631: one. First let's declare a text object (called
                   11632: @code{button}), that stores text and position:
1.12      anton    11633: 
1.78      anton    11634: @example
                   11635: object class
                   11636:   cell var text
                   11637:   cell var len
                   11638:   cell var x
                   11639:   cell var y
                   11640:   method init
                   11641:   method draw
                   11642: end-class button
                   11643: @end example
1.12      anton    11644: 
1.78      anton    11645: @noindent
                   11646: Now, implement the two methods, @code{draw} and @code{init}:
1.21      crook    11647: 
1.26      crook    11648: @example
1.78      anton    11649: :noname ( o -- )
                   11650:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
                   11651:  button defines draw
                   11652: :noname ( addr u o -- )
                   11653:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
                   11654:  button defines init
1.26      crook    11655: @end example
1.12      anton    11656: 
1.78      anton    11657: @noindent
                   11658: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79      anton    11659: new data and no new selectors:
1.78      anton    11660: 
                   11661: @example
                   11662: button class
                   11663: end-class bold-button
1.12      anton    11664: 
1.78      anton    11665: : bold   27 emit ." [1m" ;
                   11666: : normal 27 emit ." [0m" ;
                   11667: @end example
1.1       anton    11668: 
1.78      anton    11669: @noindent
                   11670: The class @code{bold-button} has a different draw method to
                   11671: @code{button}, but the new method is defined in terms of the draw method
                   11672: for @code{button}:
1.20      pazsan   11673: 
1.78      anton    11674: @example
                   11675: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   11676: @end example
1.21      crook    11677: 
1.78      anton    11678: @noindent
1.79      anton    11679: Finally, create two objects and apply selectors:
1.21      crook    11680: 
1.26      crook    11681: @example
1.78      anton    11682: button new Constant foo
                   11683: s" thin foo" foo init
                   11684: page
                   11685: foo draw
                   11686: bold-button new Constant bar
                   11687: s" fat bar" bar init
                   11688: 1 bar y !
                   11689: bar draw
1.26      crook    11690: @end example
1.21      crook    11691: 
                   11692: 
1.78      anton    11693: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
                   11694: @subsection Comparison with other object models
                   11695: @cindex comparison of object models
                   11696: @cindex object models, comparison
                   11697: 
                   11698: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   11699: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   11700: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   11701: relation of the object models described here to two well-known and two
                   11702: closely-related (by the use of method maps) models.  Andras Zsoter
                   11703: helped us with this section.
                   11704: 
                   11705: @cindex Neon model
                   11706: The most popular model currently seems to be the Neon model (see
                   11707: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   11708: 1997) by Andrew McKewan) but this model has a number of limitations
                   11709: @footnote{A longer version of this critique can be
                   11710: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   11711: Dimensions, May 1997) by Anton Ertl.}:
                   11712: 
                   11713: @itemize @bullet
                   11714: @item
                   11715: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
                   11716: to pass objects on the stack.
1.21      crook    11717: 
1.78      anton    11718: @item
                   11719: It requires that the selector parses the input stream (at
1.79      anton    11720: compile time); this leads to reduced extensibility and to bugs that are
1.78      anton    11721: hard to find.
1.21      crook    11722: 
1.78      anton    11723: @item
1.79      anton    11724: It allows using every selector on every object; this eliminates the
                   11725: need for interfaces, but makes it harder to create efficient
                   11726: implementations.
1.78      anton    11727: @end itemize
1.21      crook    11728: 
1.78      anton    11729: @cindex Pountain's object-oriented model
                   11730: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   11731: Press, London, 1987) by Dick Pountain. However, it is not really about
                   11732: object-oriented programming, because it hardly deals with late
                   11733: binding. Instead, it focuses on features like information hiding and
                   11734: overloading that are characteristic of modular languages like Ada (83).
1.26      crook    11735: 
1.78      anton    11736: @cindex Zsoter's object-oriented model
1.79      anton    11737: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
                   11738: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
                   11739: describes a model that makes heavy use of an active object (like
                   11740: @code{this} in @file{objects.fs}): The active object is not only used
                   11741: for accessing all fields, but also specifies the receiving object of
                   11742: every selector invocation; you have to change the active object
                   11743: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
                   11744: changes more or less implicitly at @code{m: ... ;m}. Such a change at
                   11745: the method entry point is unnecessary with Zsoter's model, because the
                   11746: receiving object is the active object already. On the other hand, the
                   11747: explicit change is absolutely necessary in that model, because otherwise
                   11748: no one could ever change the active object. An ANS Forth implementation
                   11749: of this model is available through
                   11750: @uref{http://www.forth.org/oopf.html}.
1.21      crook    11751: 
1.78      anton    11752: @cindex @file{oof.fs}, differences to other models
                   11753: The @file{oof.fs} model combines information hiding and overloading
                   11754: resolution (by keeping names in various word lists) with object-oriented
                   11755: programming. It sets the active object implicitly on method entry, but
                   11756: also allows explicit changing (with @code{>o...o>} or with
                   11757: @code{with...endwith}). It uses parsing and state-smart objects and
                   11758: classes for resolving overloading and for early binding: the object or
                   11759: class parses the selector and determines the method from this. If the
                   11760: selector is not parsed by an object or class, it performs a call to the
                   11761: selector for the active object (late binding), like Zsoter's model.
                   11762: Fields are always accessed through the active object. The big
                   11763: disadvantage of this model is the parsing and the state-smartness, which
                   11764: reduces extensibility and increases the opportunities for subtle bugs;
                   11765: essentially, you are only safe if you never tick or @code{postpone} an
                   11766: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21      crook    11767: 
1.78      anton    11768: @cindex @file{mini-oof.fs}, differences to other models
                   11769: The @file{mini-oof.fs} model is quite similar to a very stripped-down
                   11770: version of the @file{objects.fs} model, but syntactically it is a
                   11771: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21      crook    11772: 
                   11773: 
1.78      anton    11774: @c -------------------------------------------------------------
1.150     anton    11775: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78      anton    11776: @section Programming Tools
                   11777: @cindex programming tools
1.21      crook    11778: 
1.78      anton    11779: @c !! move this and assembler down below OO stuff.
1.21      crook    11780: 
1.78      anton    11781: @menu
1.150     anton    11782: * Examining::                   Data and Code.
                   11783: * Forgetting words::            Usually before reloading.
1.78      anton    11784: * Debugging::                   Simple and quick.
                   11785: * Assertions::                  Making your programs self-checking.
                   11786: * Singlestep Debugger::         Executing your program word by word.
                   11787: @end menu
1.21      crook    11788: 
1.78      anton    11789: @node Examining, Forgetting words, Programming Tools, Programming Tools
                   11790: @subsection Examining data and code
                   11791: @cindex examining data and code
                   11792: @cindex data examination
                   11793: @cindex code examination
1.44      crook    11794: 
1.78      anton    11795: The following words inspect the stack non-destructively:
1.21      crook    11796: 
1.78      anton    11797: doc-.s
                   11798: doc-f.s
1.158     anton    11799: doc-maxdepth-.s
1.44      crook    11800: 
1.78      anton    11801: There is a word @code{.r} but it does @i{not} display the return stack!
                   11802: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21      crook    11803: 
1.78      anton    11804: doc-depth
                   11805: doc-fdepth
                   11806: doc-clearstack
1.124     anton    11807: doc-clearstacks
1.21      crook    11808: 
1.78      anton    11809: The following words inspect memory.
1.21      crook    11810: 
1.78      anton    11811: doc-?
                   11812: doc-dump
1.21      crook    11813: 
1.78      anton    11814: And finally, @code{see} allows to inspect code:
1.21      crook    11815: 
1.78      anton    11816: doc-see
                   11817: doc-xt-see
1.111     anton    11818: doc-simple-see
                   11819: doc-simple-see-range
1.182     anton    11820: doc-see-code
                   11821: doc-see-code-range
1.21      crook    11822: 
1.78      anton    11823: @node Forgetting words, Debugging, Examining, Programming Tools
                   11824: @subsection Forgetting words
                   11825: @cindex words, forgetting
                   11826: @cindex forgeting words
1.21      crook    11827: 
1.78      anton    11828: @c  anton: other, maybe better places for this subsection: Defining Words;
                   11829: @c  Dictionary allocation.  At least a reference should be there.
1.21      crook    11830: 
1.78      anton    11831: Forth allows you to forget words (and everything that was alloted in the
                   11832: dictonary after them) in a LIFO manner.
1.21      crook    11833: 
1.78      anton    11834: doc-marker
1.21      crook    11835: 
1.78      anton    11836: The most common use of this feature is during progam development: when
                   11837: you change a source file, forget all the words it defined and load it
                   11838: again (since you also forget everything defined after the source file
                   11839: was loaded, you have to reload that, too).  Note that effects like
                   11840: storing to variables and destroyed system words are not undone when you
                   11841: forget words.  With a system like Gforth, that is fast enough at
                   11842: starting up and compiling, I find it more convenient to exit and restart
                   11843: Gforth, as this gives me a clean slate.
1.21      crook    11844: 
1.78      anton    11845: Here's an example of using @code{marker} at the start of a source file
                   11846: that you are debugging; it ensures that you only ever have one copy of
                   11847: the file's definitions compiled at any time:
1.21      crook    11848: 
1.78      anton    11849: @example
                   11850: [IFDEF] my-code
                   11851:     my-code
                   11852: [ENDIF]
1.26      crook    11853: 
1.78      anton    11854: marker my-code
                   11855: init-included-files
1.21      crook    11856: 
1.78      anton    11857: \ .. definitions start here
                   11858: \ .
                   11859: \ .
                   11860: \ end
                   11861: @end example
1.21      crook    11862: 
1.26      crook    11863: 
1.78      anton    11864: @node Debugging, Assertions, Forgetting words, Programming Tools
                   11865: @subsection Debugging
                   11866: @cindex debugging
1.21      crook    11867: 
1.78      anton    11868: Languages with a slow edit/compile/link/test development loop tend to
                   11869: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21      crook    11870: 
1.78      anton    11871: A much better (faster) way in fast-compiling languages is to add
                   11872: printing code at well-selected places, let the program run, look at
                   11873: the output, see where things went wrong, add more printing code, etc.,
                   11874: until the bug is found.
1.21      crook    11875: 
1.78      anton    11876: The simple debugging aids provided in @file{debugs.fs}
                   11877: are meant to support this style of debugging.
1.21      crook    11878: 
1.78      anton    11879: The word @code{~~} prints debugging information (by default the source
                   11880: location and the stack contents). It is easy to insert. If you use Emacs
                   11881: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   11882: query-replace them with nothing). The deferred words
1.101     anton    11883: @code{printdebugdata} and @code{.debugline} control the output of
1.78      anton    11884: @code{~~}. The default source location output format works well with
                   11885: Emacs' compilation mode, so you can step through the program at the
                   11886: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   11887: is that you can step in any direction and you know where the crash has
                   11888: happened or where the strange data has occurred).
1.21      crook    11889: 
1.78      anton    11890: doc-~~
                   11891: doc-printdebugdata
1.101     anton    11892: doc-.debugline
1.21      crook    11893: 
1.106     anton    11894: @cindex filenames in @code{~~} output
                   11895: @code{~~} (and assertions) will usually print the wrong file name if a
                   11896: marker is executed in the same file after their occurance.  They will
                   11897: print @samp{*somewhere*} as file name if a marker is executed in the
                   11898: same file before their occurance.
                   11899: 
                   11900: 
1.78      anton    11901: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   11902: @subsection Assertions
                   11903: @cindex assertions
1.21      crook    11904: 
1.78      anton    11905: It is a good idea to make your programs self-checking, especially if you
                   11906: make an assumption that may become invalid during maintenance (for
                   11907: example, that a certain field of a data structure is never zero). Gforth
                   11908: supports @dfn{assertions} for this purpose. They are used like this:
1.21      crook    11909: 
                   11910: @example
1.78      anton    11911: assert( @i{flag} )
1.26      crook    11912: @end example
                   11913: 
1.78      anton    11914: The code between @code{assert(} and @code{)} should compute a flag, that
                   11915: should be true if everything is alright and false otherwise. It should
                   11916: not change anything else on the stack. The overall stack effect of the
                   11917: assertion is @code{( -- )}. E.g.
1.21      crook    11918: 
1.26      crook    11919: @example
1.78      anton    11920: assert( 1 1 + 2 = ) \ what we learn in school
                   11921: assert( dup 0<> ) \ assert that the top of stack is not zero
                   11922: assert( false ) \ this code should not be reached
1.21      crook    11923: @end example
                   11924: 
1.78      anton    11925: The need for assertions is different at different times. During
                   11926: debugging, we want more checking, in production we sometimes care more
                   11927: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   11928: becomes a comment. Depending on the importance of an assertion and the
                   11929: time it takes to check it, you may want to turn off some assertions and
                   11930: keep others turned on. Gforth provides several levels of assertions for
                   11931: this purpose:
                   11932: 
                   11933: 
                   11934: doc-assert0(
                   11935: doc-assert1(
                   11936: doc-assert2(
                   11937: doc-assert3(
                   11938: doc-assert(
                   11939: doc-)
1.21      crook    11940: 
                   11941: 
1.78      anton    11942: The variable @code{assert-level} specifies the highest assertions that
                   11943: are turned on. I.e., at the default @code{assert-level} of one,
                   11944: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   11945: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26      crook    11946: 
1.78      anton    11947: The value of @code{assert-level} is evaluated at compile-time, not at
                   11948: run-time. Therefore you cannot turn assertions on or off at run-time;
                   11949: you have to set the @code{assert-level} appropriately before compiling a
                   11950: piece of code. You can compile different pieces of code at different
                   11951: @code{assert-level}s (e.g., a trusted library at level 1 and
                   11952: newly-written code at level 3).
1.26      crook    11953: 
                   11954: 
1.78      anton    11955: doc-assert-level
1.26      crook    11956: 
                   11957: 
1.78      anton    11958: If an assertion fails, a message compatible with Emacs' compilation mode
                   11959: is produced and the execution is aborted (currently with @code{ABORT"}.
                   11960: If there is interest, we will introduce a special throw code. But if you
                   11961: intend to @code{catch} a specific condition, using @code{throw} is
                   11962: probably more appropriate than an assertion).
1.106     anton    11963: 
                   11964: @cindex filenames in assertion output
                   11965: Assertions (and @code{~~}) will usually print the wrong file name if a
                   11966: marker is executed in the same file after their occurance.  They will
                   11967: print @samp{*somewhere*} as file name if a marker is executed in the
                   11968: same file before their occurance.
1.44      crook    11969: 
1.78      anton    11970: Definitions in ANS Forth for these assertion words are provided
                   11971: in @file{compat/assert.fs}.
1.26      crook    11972: 
1.44      crook    11973: 
1.78      anton    11974: @node Singlestep Debugger,  , Assertions, Programming Tools
                   11975: @subsection Singlestep Debugger
                   11976: @cindex singlestep Debugger
                   11977: @cindex debugging Singlestep
1.44      crook    11978: 
1.189     anton    11979: The singlestep debugger works only with the engine @code{gforth-itc}.
1.112     anton    11980: 
1.78      anton    11981: When you create a new word there's often the need to check whether it
                   11982: behaves correctly or not. You can do this by typing @code{dbg
                   11983: badword}. A debug session might look like this:
1.26      crook    11984: 
1.78      anton    11985: @example
                   11986: : badword 0 DO i . LOOP ;  ok
                   11987: 2 dbg badword 
                   11988: : badword  
                   11989: Scanning code...
1.44      crook    11990: 
1.78      anton    11991: Nesting debugger ready!
1.44      crook    11992: 
1.78      anton    11993: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   11994: 400D4740  8049F68 DO             -> [ 0 ] 
                   11995: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   11996: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   11997: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   11998: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   11999: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   12000: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   12001: 400D4758  804B384 ;              ->  ok
                   12002: @end example
1.21      crook    12003: 
1.78      anton    12004: Each line displayed is one step. You always have to hit return to
                   12005: execute the next word that is displayed. If you don't want to execute
                   12006: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   12007: an overview what keys are available:
1.44      crook    12008: 
1.78      anton    12009: @table @i
1.44      crook    12010: 
1.78      anton    12011: @item @key{RET}
                   12012: Next; Execute the next word.
1.21      crook    12013: 
1.78      anton    12014: @item n
                   12015: Nest; Single step through next word.
1.44      crook    12016: 
1.78      anton    12017: @item u
                   12018: Unnest; Stop debugging and execute rest of word. If we got to this word
                   12019: with nest, continue debugging with the calling word.
1.44      crook    12020: 
1.78      anton    12021: @item d
                   12022: Done; Stop debugging and execute rest.
1.21      crook    12023: 
1.78      anton    12024: @item s
                   12025: Stop; Abort immediately.
1.44      crook    12026: 
1.78      anton    12027: @end table
1.44      crook    12028: 
1.78      anton    12029: Debugging large application with this mechanism is very difficult, because
                   12030: you have to nest very deeply into the program before the interesting part
                   12031: begins. This takes a lot of time. 
1.26      crook    12032: 
1.78      anton    12033: To do it more directly put a @code{BREAK:} command into your source code.
                   12034: When program execution reaches @code{BREAK:} the single step debugger is
                   12035: invoked and you have all the features described above.
1.44      crook    12036: 
1.78      anton    12037: If you have more than one part to debug it is useful to know where the
                   12038: program has stopped at the moment. You can do this by the 
                   12039: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   12040: string is typed out when the ``breakpoint'' is reached.
1.44      crook    12041: 
1.26      crook    12042: 
1.78      anton    12043: doc-dbg
                   12044: doc-break:
                   12045: doc-break"
1.44      crook    12046: 
1.150     anton    12047: @c ------------------------------------------------------------
                   12048: @node C Interface, Assembler and Code Words, Programming Tools, Words
                   12049: @section C Interface
                   12050: @cindex C interface
                   12051: @cindex foreign language interface
                   12052: @cindex interface to C functions
                   12053: 
1.178     anton    12054: Note that the C interface is not yet complete; callbacks are missing,
                   12055: as well as a way of declaring structs, unions, and their fields.
1.150     anton    12056: 
                   12057: @menu
                   12058: * Calling C Functions::         
                   12059: * Declaring C Functions::       
1.180     anton    12060: * Calling C function pointers::  
1.196   ! anton    12061: * Defining library interfaces::  
        !          12062: * Declaring OS-level libraries::  
1.150     anton    12063: * Callbacks::                   
1.178     anton    12064: * C interface internals::       
1.155     anton    12065: * Low-Level C Interface Words::  
1.150     anton    12066: @end menu
                   12067: 
1.151     pazsan   12068: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150     anton    12069: @subsection Calling C functions
1.155     anton    12070: @cindex C functions, calls to
                   12071: @cindex calling C functions
1.150     anton    12072: 
1.151     pazsan   12073: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150     anton    12074: can call it as follows: You push the arguments on the stack(s), and
                   12075: then call the word for the C function.  The arguments have to be
                   12076: pushed in the same order as the arguments appear in the C
                   12077: documentation (i.e., the first argument is deepest on the stack).
                   12078: Integer and pointer arguments have to be pushed on the data stack,
                   12079: floating-point arguments on the FP stack; these arguments are consumed
1.155     anton    12080: by the called C function.
1.150     anton    12081: 
1.155     anton    12082: On returning from the C function, the return value, if any, resides on
                   12083: the appropriate stack: an integer return value is pushed on the data
                   12084: stack, an FP return value on the FP stack, and a void return value
                   12085: results in not pushing anything.  Note that most C functions have a
                   12086: return value, even if that is often not used in C; in Forth, you have
                   12087: to @code{drop} this return value explicitly if you do not use it.
1.150     anton    12088: 
1.177     anton    12089: The C interface automatically converts between the C type and the
                   12090: Forth type as necessary, on a best-effort basis (in some cases, there
                   12091: may be some loss).
1.150     anton    12092: 
                   12093: As an example, consider the POSIX function @code{lseek()}:
                   12094: 
                   12095: @example
                   12096: off_t lseek(int fd, off_t offset, int whence);
                   12097: @end example
                   12098: 
                   12099: This function takes three integer arguments, and returns an integer
                   12100: argument, so a Forth call for setting the current file offset to the
                   12101: start of the file could look like this:
                   12102: 
                   12103: @example
                   12104: fd @@ 0 SEEK_SET lseek -1 = if
                   12105:   ... \ error handling
                   12106: then
                   12107: @end example
                   12108: 
                   12109: You might be worried that an @code{off_t} does not fit into a cell, so
                   12110: you could not pass larger offsets to lseek, and might get only a part
1.155     anton    12111: of the return values.  In that case, in your declaration of the
                   12112: function (@pxref{Declaring C Functions}) you should declare it to use
                   12113: double-cells for the off_t argument and return value, and maybe give
                   12114: the resulting Forth word a different name, like @code{dlseek}; the
                   12115: result could be called like this:
1.150     anton    12116: 
                   12117: @example
                   12118: fd @@ 0. SEEK_SET dlseek -1. d= if
                   12119:   ... \ error handling
                   12120: then
                   12121: @end example
                   12122: 
                   12123: Passing and returning structs or unions is currently not supported by
                   12124: our interface@footnote{If you know the calling convention of your C
                   12125: compiler, you usually can call such functions in some way, but that
                   12126: way is usually not portable between platforms, and sometimes not even
                   12127: between C compilers.}.
                   12128: 
1.177     anton    12129: Calling functions with a variable number of arguments (@emph{variadic}
                   12130: functions, e.g., @code{printf()}) is only supported by having you
                   12131: declare one function-calling word for each argument pattern, and
                   12132: calling the appropriate word for the desired pattern.
                   12133: 
1.150     anton    12134: 
1.155     anton    12135: 
1.180     anton    12136: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
1.150     anton    12137: @subsection Declaring C Functions
1.155     anton    12138: @cindex C functions, declarations
                   12139: @cindex declaring C functions
1.150     anton    12140: 
                   12141: Before you can call @code{lseek} or @code{dlseek}, you have to declare
1.177     anton    12142: it.  The declaration consists of two parts: 
                   12143: 
                   12144: @table @b
                   12145: 
                   12146: @item The C part
1.179     anton    12147: is the C declaration of the function, or more typically and portably,
                   12148: a C-style @code{#include} of a file that contains the declaration of
                   12149: the C function.
1.177     anton    12150: 
                   12151: @item The Forth part
                   12152: declares the Forth types of the parameters and the Forth word name
                   12153: corresponding to the C function.
                   12154: 
                   12155: @end table
                   12156: 
                   12157: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
                   12158: declarations are:
                   12159: 
                   12160: @example
                   12161: \c #define _FILE_OFFSET_BITS 64
                   12162: \c #include <sys/types.h>
                   12163: \c #include <unistd.h>
                   12164: c-function lseek lseek n n n -- n
                   12165: c-function dlseek lseek n d n -- d
                   12166: @end example
                   12167: 
1.178     anton    12168: The C part of the declarations is prefixed by @code{\c}, and the rest
1.177     anton    12169: of the line is ordinary C code.  You can use as many lines of C
                   12170: declarations as you like, and they are visible for all further
                   12171: function declarations.
                   12172: 
                   12173: The Forth part declares each interface word with @code{c-function},
                   12174: followed by the Forth name of the word, the C name of the called
                   12175: function, and the stack effect of the word.  The stack effect contains
1.178     anton    12176: an arbitrary number of types of parameters, then @code{--}, and then
1.177     anton    12177: exactly one type for the return value.  The possible types are:
                   12178: 
                   12179: @table @code
                   12180: 
                   12181: @item n
                   12182: single-cell integer
                   12183: 
                   12184: @item a
                   12185: address (single-cell)
                   12186: 
                   12187: @item d
                   12188: double-cell integer
                   12189: 
                   12190: @item r
                   12191: floating-point value
                   12192: 
                   12193: @item func
                   12194: C function pointer
                   12195: 
                   12196: @item void
                   12197: no value (used as return type for void functions)
                   12198: 
                   12199: @end table
                   12200: 
                   12201: @cindex variadic C functions
                   12202: 
                   12203: To deal with variadic C functions, you can declare one Forth word for
                   12204: every pattern you want to use, e.g.:
                   12205: 
                   12206: @example
                   12207: \c #include <stdio.h>
                   12208: c-function printf-nr printf a n r -- n
                   12209: c-function printf-rn printf a r n -- n
                   12210: @end example
                   12211: 
                   12212: Note that with C functions declared as variadic (or if you don't
                   12213: provide a prototype), the C interface has no C type to convert to, so
                   12214: no automatic conversion happens, which may lead to portability
                   12215: problems in some cases.  In such cases you can perform the conversion
                   12216: explicitly on the C level, e.g., as follows:
                   12217: 
                   12218: @example
1.178     anton    12219: \c #define printfll(s,ll) printf(s,(long long)ll)
                   12220: c-function printfll printfll a n -- n
1.177     anton    12221: @end example
                   12222: 
                   12223: Here, instead of calling @code{printf()} directly, we define a macro
1.178     anton    12224: that casts (converts) the Forth single-cell integer into a
                   12225: C @code{long long} before calling @code{printf()}.
1.177     anton    12226: 
                   12227: doc-\c
                   12228: doc-c-function
                   12229: 
                   12230: In order to work, this C interface invokes GCC at run-time and uses
1.178     anton    12231: dynamic linking.  If these features are not available, there are
                   12232: other, less convenient and less portable C interfaces in @file{lib.fs}
                   12233: and @file{oldlib.fs}.  These interfaces are mostly undocumented and
                   12234: mostly incompatible with each other and with the documented C
                   12235: interface; you can find some examples for the @file{lib.fs} interface
                   12236: in @file{lib.fs}.
1.177     anton    12237: 
                   12238: 
1.196   ! anton    12239: @node Calling C function pointers, Defining library interfaces, Declaring C Functions, C Interface
1.180     anton    12240: @subsection Calling C function pointers from Forth
                   12241: @cindex C function pointers, calling from Forth
1.177     anton    12242: 
1.180     anton    12243: If you come across a C function pointer (e.g., in some C-constructed
                   12244: structure) and want to call it from your Forth program, you can also
                   12245: use the features explained until now to achieve that, as follows:
1.150     anton    12246: 
1.180     anton    12247: Let us assume that there is a C function pointer type @code{func1}
                   12248: defined in some header file @file{func1.h}, and you know that these
                   12249: functions take one integer argument and return an integer result; and
                   12250: you want to call functions through such pointers.  Just define
1.155     anton    12251: 
1.180     anton    12252: @example
                   12253: \c #include <func1.h>
                   12254: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
                   12255: c-function call-func1 call_func1 n func -- n
                   12256: @end example
                   12257: 
                   12258: and then you can call a function pointed to by, say @code{func1a} as
                   12259: follows:
                   12260: 
                   12261: @example
                   12262: -5 func1a call-func1 .
                   12263: @end example
                   12264: 
                   12265: In the C part, @code{call_func} is defined as a macro to avoid having
                   12266: to declare the exact parameter and return types, so the C compiler
                   12267: knows them from the declaration of @code{func1}.
                   12268: 
                   12269: The Forth word @code{call-func1} is similar to @code{execute}, except
                   12270: that it takes a C @code{func1} pointer instead of a Forth execution
                   12271: token, and it is specific to @code{func1} pointers.  For each type of
                   12272: function pointer you want to call from Forth, you have to define
                   12273: a separate calling word.
                   12274: 
                   12275: 
1.196   ! anton    12276: @node Defining library interfaces, Declaring OS-level libraries, Calling C function pointers, C Interface
        !          12277: @subsection Defining library interfaces
        !          12278: @cindex giving a name to a library interface
        !          12279: @cindex library interface names
        !          12280: 
        !          12281: You can give a name to a bunch of C function declarations (a library
        !          12282: interface), as follows:
        !          12283: 
        !          12284: @example
        !          12285: c-library lseek-lib
        !          12286: \c #define _FILE_OFFSET_BITS 64
        !          12287: ...
        !          12288: end-c-library
        !          12289: @end example
        !          12290: 
        !          12291: The effect of giving such a name to the interface is that the
        !          12292: generated files will contain that name, and when you use the interface
        !          12293: a second time, it will use the existing files instead of generating
        !          12294: and compiling them again, saving you time.  Note that even if you
        !          12295: change the declarations, the old (stale) files will be used, probably
        !          12296: leading to errors.  So, during development of the declarations we
        !          12297: recommend not using @code{c-library}.
        !          12298: 
        !          12299: Note that the library name is not allocated in the dictionary and
        !          12300: therefore does not shadow dictionary names.  It is used in the file
        !          12301: system, so you have to use naming conventions appropriate for file
        !          12302: systems.  Also, you must not call a function you declare after
        !          12303: @code{c-library} before you perform @code{end-c-library}.
        !          12304: 
        !          12305: A major benefit of these named library interfaces is that, once they
        !          12306: are generated, the tools used to generated them (in particular, the C
        !          12307: compiler and libtool) are no longer needed, so the interface can be
        !          12308: used even on machines that do not have the tools installed.
        !          12309: 
        !          12310: doc-c-library-name
        !          12311: doc-c-library
        !          12312: doc-end-c-library
        !          12313: 
        !          12314: 
        !          12315: @node Declaring OS-level libraries, Callbacks, Defining library interfaces, C Interface
        !          12316: @subsection Declaring OS-level libraries
1.195     anton    12317: @cindex Shared libraries in C interface
                   12318: @cindex Dynamically linked libraries in C interface
                   12319: @cindex Libraries in C interface
                   12320: 
1.196   ! anton    12321: For calling some C functions, you need to link with a specific
        !          12322: OS-level library that contains that function.  E.g., the @code{sin}
        !          12323: function requires linking a special library by using the command line
        !          12324: switch @code{-lm}.  In our C iterface you do the equivalent thing by
        !          12325: calling @code{add-lib} as follows:
1.195     anton    12326: 
                   12327: @example
                   12328: clear-libs
                   12329: s" m" add-lib
                   12330: \c #include <math.h>
                   12331: c-function sin sin r -- r
                   12332: @end example
                   12333: 
                   12334: First, you clear any libraries that may have been declared earlier
                   12335: (you don't need them for @code{sin}); then you add the @code{m}
                   12336: library (actually @code{libm.so} or somesuch) to the currently
                   12337: declared libraries; you can add as many as you need.  Finally you
                   12338: declare the function as shown above.  Typically you will use the same
                   12339: set of library declarations for many function declarations; you need
                   12340: to write only one set for that, right at the beginning.
                   12341: 
1.196   ! anton    12342: Note that you must not call @code{clear-libs} inside
        !          12343: @code{c-library...end-c-library}; however, @code{c-library} performs
        !          12344: the function of @code{clear-libs}, so @code{clear-libs} is not
        !          12345: necessary, and you usually want to put @code{add-lib} calls inside
        !          12346: @code{c-library...end-c-library}.
        !          12347: 
1.195     anton    12348: doc-clear-libs
                   12349: doc-add-lib
                   12350: 
                   12351: 
1.196   ! anton    12352: @node Callbacks, C interface internals, Declaring OS-level libraries, C Interface
1.150     anton    12353: @subsection Callbacks
1.155     anton    12354: @cindex Callback functions written in Forth
                   12355: @cindex C function pointers to Forth words
                   12356: 
1.177     anton    12357: Callbacks are not yet supported by the documented C interface.  You
                   12358: can use the undocumented @file{lib.fs} interface for callbacks.
                   12359: 
1.155     anton    12360: In some cases you have to pass a function pointer to a C function,
                   12361: i.e., the library wants to call back to your application (and the
                   12362: pointed-to function is called a callback function).  You can pass the
                   12363: address of an existing C function (that you get with @code{lib-sym},
                   12364: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
                   12365: function, you probably want to define the function as a Forth word.
                   12366: 
                   12367: @c I don't understand the existing callback interface from the example - anton
                   12368: 
1.165     anton    12369: 
                   12370: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
                   12371: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
                   12372: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
                   12373: @c > > C-Funktionsadresse auf dem TOS).
                   12374: @c >
                   12375: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
                   12376: @c > gesehen habe, wozu das gut ist.
                   12377: @c 
                   12378: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch 
                   12379: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen 
                   12380: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit 
                   12381: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte 
                   12382: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit 
                   12383: @c demselben Prototyp.
                   12384: 
                   12385: 
1.178     anton    12386: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
1.177     anton    12387: @subsection How the C interface works
                   12388: 
                   12389: The documented C interface works by generating a C code out of the
                   12390: declarations.
                   12391: 
                   12392: In particular, for every Forth word declared with @code{c-function},
                   12393: it generates a wrapper function in C that takes the Forth data from
                   12394: the Forth stacks, and calls the target C function with these data as
                   12395: arguments.  The C compiler then performs an implicit conversion
                   12396: between the Forth type from the stack, and the C type for the
                   12397: parameter, which is given by the C function prototype.  After the C
                   12398: function returns, the return value is likewise implicitly converted to
                   12399: a Forth type and written back on the stack.
                   12400: 
                   12401: The @code{\c} lines are literally included in the C code (but without
                   12402: the @code{\c}), and provide the necessary declarations so that the C
                   12403: compiler knows the C types and has enough information to perform the
                   12404: conversion.
                   12405: 
                   12406: These wrapper functions are eventually compiled and dynamically linked
                   12407: into Gforth, and then they can be called.
                   12408: 
1.195     anton    12409: The libraries added with @code{add-lib} are used in the compile
                   12410: command line to specify dependent libraries with @code{-l@var{lib}},
                   12411: causing these libraries to be dynamically linked when the wrapper
                   12412: function is linked.
                   12413: 
1.177     anton    12414: 
1.178     anton    12415: @node Low-Level C Interface Words,  , C interface internals, C Interface
1.155     anton    12416: @subsection Low-Level C Interface Words
1.44      crook    12417: 
1.155     anton    12418: doc-open-lib
                   12419: doc-lib-sym
1.196   ! anton    12420: doc-lib-error
1.177     anton    12421: doc-call-c
1.26      crook    12422: 
1.78      anton    12423: @c -------------------------------------------------------------
1.150     anton    12424: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78      anton    12425: @section Assembler and Code Words
                   12426: @cindex assembler
                   12427: @cindex code words
1.44      crook    12428: 
1.78      anton    12429: @menu
                   12430: * Code and ;code::              
                   12431: * Common Assembler::            Assembler Syntax
                   12432: * Common Disassembler::         
                   12433: * 386 Assembler::               Deviations and special cases
                   12434: * Alpha Assembler::             Deviations and special cases
                   12435: * MIPS assembler::              Deviations and special cases
1.161     anton    12436: * PowerPC assembler::           Deviations and special cases
1.193     dvdkhlng 12437: * ARM Assembler::               Deviations and special cases
1.78      anton    12438: * Other assemblers::            How to write them
                   12439: @end menu
1.21      crook    12440: 
1.78      anton    12441: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
                   12442: @subsection @code{Code} and @code{;code}
1.26      crook    12443: 
1.78      anton    12444: Gforth provides some words for defining primitives (words written in
                   12445: machine code), and for defining the machine-code equivalent of
                   12446: @code{DOES>}-based defining words. However, the machine-independent
                   12447: nature of Gforth poses a few problems: First of all, Gforth runs on
                   12448: several architectures, so it can provide no standard assembler. What's
                   12449: worse is that the register allocation not only depends on the processor,
                   12450: but also on the @code{gcc} version and options used.
1.44      crook    12451: 
1.78      anton    12452: The words that Gforth offers encapsulate some system dependences (e.g.,
                   12453: the header structure), so a system-independent assembler may be used in
                   12454: Gforth. If you do not have an assembler, you can compile machine code
                   12455: directly with @code{,} and @code{c,}@footnote{This isn't portable,
                   12456: because these words emit stuff in @i{data} space; it works because
                   12457: Gforth has unified code/data spaces. Assembler isn't likely to be
                   12458: portable anyway.}.
1.21      crook    12459: 
1.44      crook    12460: 
1.78      anton    12461: doc-assembler
                   12462: doc-init-asm
                   12463: doc-code
                   12464: doc-end-code
                   12465: doc-;code
                   12466: doc-flush-icache
1.44      crook    12467: 
1.21      crook    12468: 
1.78      anton    12469: If @code{flush-icache} does not work correctly, @code{code} words
                   12470: etc. will not work (reliably), either.
1.44      crook    12471: 
1.78      anton    12472: The typical usage of these @code{code} words can be shown most easily by
                   12473: analogy to the equivalent high-level defining words:
1.44      crook    12474: 
1.78      anton    12475: @example
                   12476: : foo                              code foo
                   12477:    <high-level Forth words>              <assembler>
                   12478: ;                                  end-code
                   12479:                                 
                   12480: : bar                              : bar
                   12481:    <high-level Forth words>           <high-level Forth words>
                   12482:    CREATE                             CREATE
                   12483:       <high-level Forth words>           <high-level Forth words>
                   12484:    DOES>                              ;code
                   12485:       <high-level Forth words>           <assembler>
                   12486: ;                                  end-code
                   12487: @end example
1.21      crook    12488: 
1.78      anton    12489: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44      crook    12490: 
1.78      anton    12491: @cindex registers of the inner interpreter
                   12492: In the assembly code you will want to refer to the inner interpreter's
                   12493: registers (e.g., the data stack pointer) and you may want to use other
                   12494: registers for temporary storage. Unfortunately, the register allocation
                   12495: is installation-dependent.
1.44      crook    12496: 
1.78      anton    12497: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100     anton    12498: (return stack pointer) may be in different places in @code{gforth} and
                   12499: @code{gforth-fast}, or different installations.  This means that you
                   12500: cannot write a @code{NEXT} routine that works reliably on both versions
                   12501: or different installations; so for doing @code{NEXT}, I recommend
                   12502: jumping to @code{' noop >code-address}, which contains nothing but a
                   12503: @code{NEXT}.
1.21      crook    12504: 
1.78      anton    12505: For general accesses to the inner interpreter's registers, the easiest
                   12506: solution is to use explicit register declarations (@pxref{Explicit Reg
                   12507: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
                   12508: all of the inner interpreter's registers: You have to compile Gforth
                   12509: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
                   12510: the appropriate declarations must be present in the @code{machine.h}
                   12511: file (see @code{mips.h} for an example; you can find a full list of all
                   12512: declarable register symbols with @code{grep register engine.c}). If you
                   12513: give explicit registers to all variables that are declared at the
                   12514: beginning of @code{engine()}, you should be able to use the other
                   12515: caller-saved registers for temporary storage. Alternatively, you can use
                   12516: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
                   12517: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
                   12518: reserve a register (however, this restriction on register allocation may
                   12519: slow Gforth significantly).
1.44      crook    12520: 
1.78      anton    12521: If this solution is not viable (e.g., because @code{gcc} does not allow
                   12522: you to explicitly declare all the registers you need), you have to find
                   12523: out by looking at the code where the inner interpreter's registers
                   12524: reside and which registers can be used for temporary storage. You can
                   12525: get an assembly listing of the engine's code with @code{make engine.s}.
1.44      crook    12526: 
1.78      anton    12527: In any case, it is good practice to abstract your assembly code from the
                   12528: actual register allocation. E.g., if the data stack pointer resides in
                   12529: register @code{$17}, create an alias for this register called @code{sp},
                   12530: and use that in your assembly code.
1.21      crook    12531: 
1.78      anton    12532: @cindex code words, portable
                   12533: Another option for implementing normal and defining words efficiently
                   12534: is to add the desired functionality to the source of Gforth. For normal
                   12535: words you just have to edit @file{primitives} (@pxref{Automatic
                   12536: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
                   12537: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
                   12538: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44      crook    12539: 
1.78      anton    12540: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
                   12541: @subsection Common Assembler
1.44      crook    12542: 
1.78      anton    12543: The assemblers in Gforth generally use a postfix syntax, i.e., the
                   12544: instruction name follows the operands.
1.21      crook    12545: 
1.78      anton    12546: The operands are passed in the usual order (the same that is used in the
                   12547: manual of the architecture).  Since they all are Forth words, they have
                   12548: to be separated by spaces; you can also use Forth words to compute the
                   12549: operands.
1.44      crook    12550: 
1.78      anton    12551: The instruction names usually end with a @code{,}.  This makes it easier
                   12552: to visually separate instructions if you put several of them on one
                   12553: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21      crook    12554: 
1.78      anton    12555: Registers are usually specified by number; e.g., (decimal) @code{11}
                   12556: specifies registers R11 and F11 on the Alpha architecture (which one,
                   12557: depends on the instruction).  The usual names are also available, e.g.,
                   12558: @code{s2} for R11 on Alpha.
1.21      crook    12559: 
1.78      anton    12560: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
                   12561: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
                   12562: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
                   12563: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
                   12564: conditions are specified in a way specific to each assembler.
1.1       anton    12565: 
1.78      anton    12566: Note that the register assignments of the Gforth engine can change
                   12567: between Gforth versions, or even between different compilations of the
                   12568: same Gforth version (e.g., if you use a different GCC version).  So if
                   12569: you want to refer to Gforth's registers (e.g., the stack pointer or
                   12570: TOS), I recommend defining your own words for refering to these
                   12571: registers, and using them later on; then you can easily adapt to a
                   12572: changed register assignment.  The stability of the register assignment
                   12573: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1       anton    12574: 
1.100     anton    12575: The most common use of these registers is to dispatch to the next word
                   12576: (the @code{next} routine).  A portable way to do this is to jump to
                   12577: @code{' noop >code-address} (of course, this is less efficient than
                   12578: integrating the @code{next} code and scheduling it well).
1.1       anton    12579: 
1.96      anton    12580: Another difference between Gforth version is that the top of stack is
                   12581: kept in memory in @code{gforth} and, on most platforms, in a register in
                   12582: @code{gforth-fast}.
                   12583: 
1.78      anton    12584: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
                   12585: @subsection Common Disassembler
1.127     anton    12586: @cindex disassembler, general
                   12587: @cindex gdb disassembler
1.1       anton    12588: 
1.78      anton    12589: You can disassemble a @code{code} word with @code{see}
                   12590: (@pxref{Debugging}).  You can disassemble a section of memory with
1.1       anton    12591: 
1.127     anton    12592: doc-discode
1.44      crook    12593: 
1.127     anton    12594: There are two kinds of disassembler for Gforth: The Forth disassembler
                   12595: (available on some CPUs) and the gdb disassembler (available on
                   12596: platforms with @command{gdb} and @command{mktemp}).  If both are
                   12597: available, the Forth disassembler is used by default.  If you prefer
                   12598: the gdb disassembler, say
                   12599: 
                   12600: @example
                   12601: ' disasm-gdb is discode
                   12602: @end example
                   12603: 
                   12604: If neither is available, @code{discode} performs @code{dump}.
                   12605: 
                   12606: The Forth disassembler generally produces output that can be fed into the
1.78      anton    12607: assembler (i.e., same syntax, etc.).  It also includes additional
                   12608: information in comments.  In particular, the address of the instruction
                   12609: is given in a comment before the instruction.
1.1       anton    12610: 
1.127     anton    12611: The gdb disassembler produces output in the same format as the gdb
                   12612: @code{disassemble} command (@pxref{Machine Code,,Source and machine
                   12613: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
                   12614: the 386 and AMD64 architectures).
                   12615: 
1.78      anton    12616: @code{See} may display more or less than the actual code of the word,
                   12617: because the recognition of the end of the code is unreliable.  You can
1.127     anton    12618: use @code{discode} if it did not display enough.  It may display more, if
1.78      anton    12619: the code word is not immediately followed by a named word.  If you have
1.116     anton    12620: something else there, you can follow the word with @code{align latest ,}
1.78      anton    12621: to ensure that the end is recognized.
1.21      crook    12622: 
1.78      anton    12623: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
                   12624: @subsection 386 Assembler
1.44      crook    12625: 
1.78      anton    12626: The 386 assembler included in Gforth was written by Bernd Paysan, it's
                   12627: available under GPL, and originally part of bigFORTH.
1.21      crook    12628: 
1.78      anton    12629: The 386 disassembler included in Gforth was written by Andrew McKewan
                   12630: and is in the public domain.
1.21      crook    12631: 
1.91      anton    12632: The disassembler displays code in an Intel-like prefix syntax.
1.21      crook    12633: 
1.78      anton    12634: The assembler uses a postfix syntax with reversed parameters.
1.1       anton    12635: 
1.78      anton    12636: The assembler includes all instruction of the Athlon, i.e. 486 core
                   12637: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
                   12638: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
                   12639: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1       anton    12640: 
1.78      anton    12641: There are several prefixes to switch between different operation sizes,
                   12642: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
                   12643: double-word accesses. Addressing modes can be switched with @code{.wa}
                   12644: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
                   12645: need a prefix for byte register names (@code{AL} et al).
1.1       anton    12646: 
1.78      anton    12647: For floating point operations, the prefixes are @code{.fs} (IEEE
                   12648: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
                   12649: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21      crook    12650: 
1.78      anton    12651: The MMX opcodes don't have size prefixes, they are spelled out like in
                   12652: the Intel assembler. Instead of move from and to memory, there are
                   12653: PLDQ/PLDD and PSTQ/PSTD.
1.21      crook    12654: 
1.78      anton    12655: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
                   12656: ax.  Immediate values are indicated by postfixing them with @code{#},
1.91      anton    12657: e.g., @code{3 #}.  Here are some examples of addressing modes in various
                   12658: syntaxes:
1.21      crook    12659: 
1.26      crook    12660: @example
1.91      anton    12661: Gforth          Intel (NASM)   AT&T (gas)      Name
                   12662: .w ax           ax             %ax             register (16 bit)
                   12663: ax              eax            %eax            register (32 bit)
                   12664: 3 #             offset 3       $3              immediate
                   12665: 1000 #)         byte ptr 1000  1000            displacement
                   12666: bx )            [ebx]          (%ebx)          base
                   12667: 100 di d)       100[edi]       100(%edi)       base+displacement
                   12668: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
                   12669: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
                   12670: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
                   12671: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
                   12672: @end example
                   12673: 
                   12674: You can use @code{L)} and @code{LI)} instead of @code{D)} and
                   12675: @code{DI)} to enforce 32-bit displacement fields (useful for
                   12676: later patching).
1.21      crook    12677: 
1.78      anton    12678: Some example of instructions are:
1.1       anton    12679: 
                   12680: @example
1.78      anton    12681: ax bx mov             \ move ebx,eax
                   12682: 3 # ax mov            \ mov eax,3
1.137     pazsan   12683: 100 di d) ax mov      \ mov eax,100[edi]
1.78      anton    12684: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
                   12685: .w ax bx mov          \ mov bx,ax
1.1       anton    12686: @end example
                   12687: 
1.78      anton    12688: The following forms are supported for binary instructions:
1.1       anton    12689: 
                   12690: @example
1.78      anton    12691: <reg> <reg> <inst>
                   12692: <n> # <reg> <inst>
                   12693: <mem> <reg> <inst>
                   12694: <reg> <mem> <inst>
1.136     pazsan   12695: <n> # <mem> <inst>
1.1       anton    12696: @end example
                   12697: 
1.136     pazsan   12698: The shift/rotate syntax is:
1.1       anton    12699: 
1.26      crook    12700: @example
1.78      anton    12701: <reg/mem> 1 # shl \ shortens to shift without immediate
                   12702: <reg/mem> 4 # shl
                   12703: <reg/mem> cl shl
1.26      crook    12704: @end example
1.1       anton    12705: 
1.78      anton    12706: Precede string instructions (@code{movs} etc.) with @code{.b} to get
                   12707: the byte version.
1.1       anton    12708: 
1.78      anton    12709: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
                   12710: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
                   12711: pc < >= <= >}. (Note that most of these words shadow some Forth words
                   12712: when @code{assembler} is in front of @code{forth} in the search path,
                   12713: e.g., in @code{code} words).  Currently the control structure words use
                   12714: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
                   12715: to shuffle them (you can also use @code{swap} etc.).
1.21      crook    12716: 
1.78      anton    12717: Here is an example of a @code{code} word (assumes that the stack pointer
                   12718: is in esi and the TOS is in ebx):
1.21      crook    12719: 
1.26      crook    12720: @example
1.78      anton    12721: code my+ ( n1 n2 -- n )
                   12722:     4 si D) bx add
                   12723:     4 # si add
                   12724:     Next
                   12725: end-code
1.26      crook    12726: @end example
1.21      crook    12727: 
1.161     anton    12728: 
1.78      anton    12729: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
                   12730: @subsection Alpha Assembler
1.21      crook    12731: 
1.78      anton    12732: The Alpha assembler and disassembler were originally written by Bernd
                   12733: Thallner.
1.26      crook    12734: 
1.78      anton    12735: The register names @code{a0}--@code{a5} are not available to avoid
                   12736: shadowing hex numbers.
1.2       jwilke   12737: 
1.78      anton    12738: Immediate forms of arithmetic instructions are distinguished by a
                   12739: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
                   12740: does not count as arithmetic instruction).
1.2       jwilke   12741: 
1.78      anton    12742: You have to specify all operands to an instruction, even those that
                   12743: other assemblers consider optional, e.g., the destination register for
                   12744: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2       jwilke   12745: 
1.78      anton    12746: You can specify conditions for @code{if,} by removing the first @code{b}
                   12747: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2       jwilke   12748: 
1.26      crook    12749: @example
1.78      anton    12750: 11 fgt if, \ if F11>0e
                   12751:   ...
                   12752: endif,
1.26      crook    12753: @end example
1.2       jwilke   12754: 
1.78      anton    12755: @code{fbgt,} gives @code{fgt}.  
                   12756: 
1.161     anton    12757: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78      anton    12758: @subsection MIPS assembler
1.2       jwilke   12759: 
1.78      anton    12760: The MIPS assembler was originally written by Christian Pirker.
1.2       jwilke   12761: 
1.78      anton    12762: Currently the assembler and disassembler only cover the MIPS-I
                   12763: architecture (R3000), and don't support FP instructions.
1.2       jwilke   12764: 
1.78      anton    12765: The register names @code{$a0}--@code{$a3} are not available to avoid
                   12766: shadowing hex numbers.
1.2       jwilke   12767: 
1.78      anton    12768: Because there is no way to distinguish registers from immediate values,
                   12769: you have to explicitly use the immediate forms of instructions, i.e.,
                   12770: @code{addiu,}, not just @code{addu,} (@command{as} does this
                   12771: implicitly).
1.2       jwilke   12772: 
1.78      anton    12773: If the architecture manual specifies several formats for the instruction
                   12774: (e.g., for @code{jalr,}), you usually have to use the one with more
                   12775: arguments (i.e., two for @code{jalr,}).  When in doubt, see
                   12776: @code{arch/mips/testasm.fs} for an example of correct use.
1.2       jwilke   12777: 
1.78      anton    12778: Branches and jumps in the MIPS architecture have a delay slot.  You have
                   12779: to fill it yourself (the simplest way is to use @code{nop,}), the
                   12780: assembler does not do it for you (unlike @command{as}).  Even
                   12781: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
                   12782: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
                   12783: and @code{then,} just specify branch targets, they are not affected.
1.2       jwilke   12784: 
1.78      anton    12785: Note that you must not put branches, jumps, or @code{li,} into the delay
                   12786: slot: @code{li,} may expand to several instructions, and control flow
                   12787: instructions may not be put into the branch delay slot in any case.
1.2       jwilke   12788: 
1.78      anton    12789: For branches the argument specifying the target is a relative address;
                   12790: You have to add the address of the delay slot to get the absolute
                   12791: address.
1.1       anton    12792: 
1.78      anton    12793: The MIPS architecture also has load delay slots and restrictions on
                   12794: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
                   12795: yourself to satisfy these restrictions, the assembler does not do it for
                   12796: you.
1.1       anton    12797: 
1.78      anton    12798: You can specify the conditions for @code{if,} etc. by taking a
                   12799: conditional branch and leaving away the @code{b} at the start and the
                   12800: @code{,} at the end.  E.g.,
1.1       anton    12801: 
1.26      crook    12802: @example
1.78      anton    12803: 4 5 eq if,
                   12804:   ... \ do something if $4 equals $5
                   12805: then,
1.26      crook    12806: @end example
1.1       anton    12807: 
1.161     anton    12808: 
1.193     dvdkhlng 12809: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
1.161     anton    12810: @subsection PowerPC assembler
                   12811: 
1.162     anton    12812: The PowerPC assembler and disassembler were contributed by Michal
1.161     anton    12813: Revucky.
                   12814: 
1.162     anton    12815: This assembler does not follow the convention of ending mnemonic names
                   12816: with a ``,'', so some mnemonic names shadow regular Forth words (in
                   12817: particular: @code{and or xor fabs}); so if you want to use the Forth
                   12818: words, you have to make them visible first, e.g., with @code{also
                   12819: forth}.
                   12820: 
1.161     anton    12821: Registers are referred to by their number, e.g., @code{9} means the
                   12822: integer register 9 or the FP register 9 (depending on the
                   12823: instruction).
                   12824: 
                   12825: Because there is no way to distinguish registers from immediate values,
                   12826: you have to explicitly use the immediate forms of instructions, i.e.,
1.162     anton    12827: @code{addi,}, not just @code{add,}.
1.161     anton    12828: 
1.162     anton    12829: The assembler and disassembler usually support the most general form
1.161     anton    12830: of an instruction, but usually not the shorter forms (especially for
                   12831: branches).
                   12832: 
                   12833: 
1.193     dvdkhlng 12834: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
                   12835: @subsection ARM Assembler
1.161     anton    12836: 
1.193     dvdkhlng 12837: The ARM assembler included in Gforth was written from scratch by David
                   12838: Kuehling.
                   12839: 
                   12840: The assembler includes all instruction of ARM architecture version 4,
                   12841: but does not (yet) have support for Thumb instructions.  It also lacks
                   12842: support for any co-processors.
                   12843: 
                   12844: The assembler uses a postfix syntax with the target operand specified
                   12845: last.  For load/store instructions the last operand will be the
                   12846: register(s) to be loaded from/stored to.
                   12847: 
                   12848: Registers are specified by their names @code{r0} through @code{r15},
                   12849: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
                   12850: @code{fp} provided for convenience.  Note that @code{ip} means intra
                   12851: procedure call scratch register (@code{r12}) and does not refer to the
                   12852: instruction pointer.
                   12853: 
                   12854: Condition codes can be specified anywhere in the instruction, but will
                   12855: be most readable if specified just in front of the mnemonic.  The 'S'
                   12856: flag is not a separate word, but encoded into instruction mnemonics,
                   12857: ie. just use @code{adds,} instead of @code{add,} if you want the
                   12858: status register to be updated.
                   12859: 
                   12860: The following table lists the syntax of operands for general
                   12861: instructions:
                   12862: 
                   12863: @example
                   12864: Gforth          normal assembler      description
                   12865: 123 #           #123                  immediate
                   12866: r12             r12                   register
                   12867: r12 4 #LSL      r12, LSL #4           shift left by immediate
                   12868: r12 r1 #LSL     r12, LSL r1           shift left by register
                   12869: r12 4 #LSR      r12, LSR #4           shift right by immediate
                   12870: r12 r1 #LSR     r12, LSR r1           shift right by register
                   12871: r12 4 #ASR      r12, ASR #4           arithmetic shift right
                   12872: r12 r1 #ASR     r12, ASR r1           ... by register
                   12873: r12 4 #ROR      r12, ROR #4           rotate right by immediate
                   12874: r12 r1 #ROR     r12, ROR r1           ... by register
                   12875: r12 RRX         r12, RRX              rotate right with extend by 1
                   12876: @end example
                   12877: 
                   12878: Memory operand syntax is listed in this table:
                   12879: 
                   12880: @example
                   12881: Gforth            normal assembler      description
                   12882: r4 ]              [r4]                  register
                   12883: r4 4 #]           [r4, #+4]             register with immediate offset
                   12884: r4 -4 #]          [r4, #-4]             with negative offset
                   12885: r4 r1 +]          [r4, +r1]             register with register offset
                   12886: r4 r1 -]          [r4, -r1]             with negated register offset
                   12887: r4 r1 2 #LSL -]   [r4, -r1, LSL #2]     with negated and shifted offset
                   12888: r4 4 #]!          [r4, #+4]!            immediate preincrement
                   12889: r4 r1 +]!         [r4, +r1]!            register preincrement
                   12890: r4 r1 -]!         [r4, +r1]!            register predecrement
                   12891: r4 r1 2 #LSL +]!  [r4, +r1, LSL #2]!    shifted preincrement
                   12892: r4 -4 ]#          [r4], #-4             immediate postdecrement
                   12893: r4 r1 ]+          [r4], r1              register postincrement
                   12894: r4 r1 ]-          [r4], -r1             register postdecrement
                   12895: r4 r1 2 #LSL ]-   [r4], -r1, LSL #2     shifted postdecrement
                   12896: ' xyz >body [#]   xyz                   PC-relative addressing
                   12897: @end example
                   12898: 
                   12899: Register lists for load/store multiple instructions are started and
                   12900: terminated by using the words @code{@{} and @code{@}}
                   12901: respectivly.  Between braces, register names can be listed one by one,
                   12902: or register ranges can be formed by using the postfix operator
                   12903: @code{r-r}.  The @code{^} flag is not encoded in the register list
                   12904: operand, but instead directly encoded into the instruction mnemonic,
                   12905: ie. use @code{^ldm,} and @code{^stm,}.
                   12906: 
                   12907: Addressing modes for load/store multiple are not encoded as
                   12908: instruction suffixes, but instead specified after the register that
                   12909: supplies the address.  Use one of @code{DA}, @code{IA}, @code{DB},
                   12910: @code{IB}, @code{DA!}, @code{IA!}, @code{DB!} or @code{IB!}.
                   12911: 
                   12912: The following table gives some examples:
                   12913: 
                   12914: @example
                   12915: Gforth                           normal assembler
                   12916: @{ r0 r7 r8 @}  r4 ia  stm,        stmia    @{r0,r7,r8@}, r4
                   12917: @{ r0 r7 r8 @}  r4 db!  ldm,       ldmdb    @{r0,r7,r8@}, r4!
                   12918: @{ r0 r15 r-r @}  sp ia!  ^ldm,    ldmfd    @{r0-r15@}^, sp!
                   12919: @end example
                   12920: 
                   12921: Conditions for control structure words are specified in front of a
                   12922: word:
                   12923: 
                   12924: @example
                   12925: r1 r2 cmp,    \ compare r1 and r2
                   12926: eq if,        \ equal?
                   12927:    ...          \ code executed if r1 == r2
                   12928: then,
                   12929: @end example
                   12930: 
                   12931: Here is an example of a @code{code} word (assumes that the stack
                   12932: pointer is in @code{r9}, and that @code{r2} and @code{r3} can be
                   12933: clobbered):
                   12934: 
                   12935: @example
                   12936: code my+ ( n1 n2 --  n3 )
                   12937:    r9 IA!       @{ r2 r3 @} ldm,  \ pop r2 = n2, r3 = n1
                   12938:    r2   r3      r3        add,  \ r3 = n2+n1
                   12939:    r9 -4 #]!    r3        str,  \ push r3
                   12940:    next,
                   12941: end-code
                   12942: @end example
                   12943: 
                   12944: Look at @file{arch/arm/asm-example.fs} for more examples.
                   12945: 
                   12946: @node Other assemblers,  , ARM Assembler, Assembler and Code Words
1.78      anton    12947: @subsection Other assemblers
                   12948: 
                   12949: If you want to contribute another assembler/disassembler, please contact
1.103     anton    12950: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
                   12951: an assembler already.  If you are writing them from scratch, please use
                   12952: a similar syntax style as the one we use (i.e., postfix, commas at the
                   12953: end of the instruction names, @pxref{Common Assembler}); make the output
                   12954: of the disassembler be valid input for the assembler, and keep the style
1.78      anton    12955: similar to the style we used.
                   12956: 
                   12957: Hints on implementation: The most important part is to have a good test
                   12958: suite that contains all instructions.  Once you have that, the rest is
                   12959: easy.  For actual coding you can take a look at
                   12960: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
                   12961: the assembler and disassembler, avoiding redundancy and some potential
                   12962: bugs.  You can also look at that file (and @pxref{Advanced does> usage
                   12963: example}) to get ideas how to factor a disassembler.
                   12964: 
                   12965: Start with the disassembler, because it's easier to reuse data from the
                   12966: disassembler for the assembler than the other way round.
1.1       anton    12967: 
1.78      anton    12968: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
                   12969: how simple it can be.
1.1       anton    12970: 
1.161     anton    12971: 
                   12972: 
                   12973: 
1.78      anton    12974: @c -------------------------------------------------------------
                   12975: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
                   12976: @section Threading Words
                   12977: @cindex threading words
1.1       anton    12978: 
1.78      anton    12979: @cindex code address
                   12980: These words provide access to code addresses and other threading stuff
                   12981: in Gforth (and, possibly, other interpretive Forths). It more or less
                   12982: abstracts away the differences between direct and indirect threading
                   12983: (and, for direct threading, the machine dependences). However, at
                   12984: present this wordset is still incomplete. It is also pretty low-level;
                   12985: some day it will hopefully be made unnecessary by an internals wordset
                   12986: that abstracts implementation details away completely.
1.1       anton    12987: 
1.78      anton    12988: The terminology used here stems from indirect threaded Forth systems; in
                   12989: such a system, the XT of a word is represented by the CFA (code field
                   12990: address) of a word; the CFA points to a cell that contains the code
                   12991: address.  The code address is the address of some machine code that
                   12992: performs the run-time action of invoking the word (e.g., the
                   12993: @code{dovar:} routine pushes the address of the body of the word (a
                   12994: variable) on the stack
                   12995: ).
1.1       anton    12996: 
1.78      anton    12997: @cindex code address
                   12998: @cindex code field address
                   12999: In an indirect threaded Forth, you can get the code address of @i{name}
                   13000: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
                   13001: >code-address}, independent of the threading method.
1.1       anton    13002: 
1.78      anton    13003: doc-threading-method
                   13004: doc->code-address
                   13005: doc-code-address!
1.1       anton    13006: 
1.78      anton    13007: @cindex @code{does>}-handler
                   13008: @cindex @code{does>}-code
                   13009: For a word defined with @code{DOES>}, the code address usually points to
                   13010: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
                   13011: routine (in Gforth on some platforms, it can also point to the dodoes
                   13012: routine itself).  What you are typically interested in, though, is
                   13013: whether a word is a @code{DOES>}-defined word, and what Forth code it
                   13014: executes; @code{>does-code} tells you that.
1.1       anton    13015: 
1.78      anton    13016: doc->does-code
1.1       anton    13017: 
1.78      anton    13018: To create a @code{DOES>}-defined word with the following basic words,
                   13019: you have to set up a @code{DOES>}-handler with @code{does-handler!};
                   13020: @code{/does-handler} aus behind you have to place your executable Forth
                   13021: code.  Finally you have to create a word and modify its behaviour with
                   13022: @code{does-handler!}.
1.1       anton    13023: 
1.78      anton    13024: doc-does-code!
                   13025: doc-does-handler!
                   13026: doc-/does-handler
1.1       anton    13027: 
1.78      anton    13028: The code addresses produced by various defining words are produced by
                   13029: the following words:
1.1       anton    13030: 
1.78      anton    13031: doc-docol:
                   13032: doc-docon:
                   13033: doc-dovar:
                   13034: doc-douser:
                   13035: doc-dodefer:
                   13036: doc-dofield:
1.1       anton    13037: 
1.99      anton    13038: @cindex definer
                   13039: The following two words generalize @code{>code-address},
                   13040: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
                   13041: 
                   13042: doc->definer
                   13043: doc-definer!
                   13044: 
1.26      crook    13045: @c -------------------------------------------------------------
1.78      anton    13046: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21      crook    13047: @section Passing Commands to the Operating System
                   13048: @cindex operating system - passing commands
                   13049: @cindex shell commands
                   13050: 
                   13051: Gforth allows you to pass an arbitrary string to the host operating
                   13052: system shell (if such a thing exists) for execution.
                   13053: 
                   13054: doc-sh
                   13055: doc-system
                   13056: doc-$?
1.23      crook    13057: doc-getenv
1.44      crook    13058: 
1.26      crook    13059: @c -------------------------------------------------------------
1.47      crook    13060: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
                   13061: @section Keeping track of Time
                   13062: @cindex time-related words
                   13063: 
                   13064: doc-ms
                   13065: doc-time&date
1.79      anton    13066: doc-utime
                   13067: doc-cputime
1.47      crook    13068: 
                   13069: 
                   13070: @c -------------------------------------------------------------
                   13071: @node Miscellaneous Words,  , Keeping track of Time, Words
1.21      crook    13072: @section Miscellaneous Words
                   13073: @cindex miscellaneous words
                   13074: 
1.29      crook    13075: @comment TODO find homes for these
                   13076: 
1.26      crook    13077: These section lists the ANS Forth words that are not documented
1.21      crook    13078: elsewhere in this manual. Ultimately, they all need proper homes.
                   13079: 
1.68      anton    13080: doc-quit
1.44      crook    13081: 
1.26      crook    13082: The following ANS Forth words are not currently supported by Gforth 
1.27      crook    13083: (@pxref{ANS conformance}):
1.21      crook    13084: 
                   13085: @code{EDITOR} 
                   13086: @code{EMIT?} 
                   13087: @code{FORGET} 
                   13088: 
1.24      anton    13089: @c ******************************************************************
                   13090: @node Error messages, Tools, Words, Top
                   13091: @chapter Error messages
                   13092: @cindex error messages
                   13093: @cindex backtrace
                   13094: 
                   13095: A typical Gforth error message looks like this:
                   13096: 
                   13097: @example
1.86      anton    13098: in file included from \evaluated string/:-1
1.24      anton    13099: in file included from ./yyy.fs:1
                   13100: ./xxx.fs:4: Invalid memory address
1.134     anton    13101: >>>bar<<<
1.79      anton    13102: Backtrace:
1.25      anton    13103: $400E664C @@
                   13104: $400E6664 foo
1.24      anton    13105: @end example
                   13106: 
                   13107: The message identifying the error is @code{Invalid memory address}.  The
                   13108: error happened when text-interpreting line 4 of the file
                   13109: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
                   13110: word on the line where the error happened, is pointed out (with
1.134     anton    13111: @code{>>>} and @code{<<<}).
1.24      anton    13112: 
                   13113: The file containing the error was included in line 1 of @file{./yyy.fs},
                   13114: and @file{yyy.fs} was included from a non-file (in this case, by giving
                   13115: @file{yyy.fs} as command-line parameter to Gforth).
                   13116: 
                   13117: At the end of the error message you find a return stack dump that can be
                   13118: interpreted as a backtrace (possibly empty). On top you find the top of
                   13119: the return stack when the @code{throw} happened, and at the bottom you
                   13120: find the return stack entry just above the return stack of the topmost
                   13121: text interpreter.
                   13122: 
                   13123: To the right of most return stack entries you see a guess for the word
                   13124: that pushed that return stack entry as its return address. This gives a
                   13125: backtrace. In our case we see that @code{bar} called @code{foo}, and
                   13126: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
                   13127: address} exception).
                   13128: 
                   13129: Note that the backtrace is not perfect: We don't know which return stack
                   13130: entries are return addresses (so we may get false positives); and in
                   13131: some cases (e.g., for @code{abort"}) we cannot determine from the return
                   13132: address the word that pushed the return address, so for some return
                   13133: addresses you see no names in the return stack dump.
1.25      anton    13134: 
                   13135: @cindex @code{catch} and backtraces
                   13136: The return stack dump represents the return stack at the time when a
                   13137: specific @code{throw} was executed.  In programs that make use of
                   13138: @code{catch}, it is not necessarily clear which @code{throw} should be
                   13139: used for the return stack dump (e.g., consider one @code{throw} that
                   13140: indicates an error, which is caught, and during recovery another error
1.160     anton    13141: happens; which @code{throw} should be used for the stack dump?).
                   13142: Gforth presents the return stack dump for the first @code{throw} after
                   13143: the last executed (not returned-to) @code{catch} or @code{nothrow};
                   13144: this works well in the usual case. To get the right backtrace, you
                   13145: usually want to insert @code{nothrow} or @code{['] false catch drop}
                   13146: after a @code{catch} if the error is not rethrown.
1.25      anton    13147: 
                   13148: @cindex @code{gforth-fast} and backtraces
                   13149: @cindex @code{gforth-fast}, difference from @code{gforth}
                   13150: @cindex backtraces with @code{gforth-fast}
                   13151: @cindex return stack dump with @code{gforth-fast}
1.79      anton    13152: @code{Gforth} is able to do a return stack dump for throws generated
1.25      anton    13153: from primitives (e.g., invalid memory address, stack empty etc.);
                   13154: @code{gforth-fast} is only able to do a return stack dump from a
1.96      anton    13155: directly called @code{throw} (including @code{abort} etc.).  Given an
1.30      anton    13156: exception caused by a primitive in @code{gforth-fast}, you will
                   13157: typically see no return stack dump at all; however, if the exception is
                   13158: caught by @code{catch} (e.g., for restoring some state), and then
                   13159: @code{throw}n again, the return stack dump will be for the first such
                   13160: @code{throw}.
1.2       jwilke   13161: 
1.5       anton    13162: @c ******************************************************************
1.24      anton    13163: @node Tools, ANS conformance, Error messages, Top
1.1       anton    13164: @chapter Tools
                   13165: 
                   13166: @menu
                   13167: * ANS Report::                  Report the words used, sorted by wordset.
1.127     anton    13168: * Stack depth changes::         Where does this stack item come from?
1.1       anton    13169: @end menu
                   13170: 
                   13171: See also @ref{Emacs and Gforth}.
                   13172: 
1.126     pazsan   13173: @node ANS Report, Stack depth changes, Tools, Tools
1.1       anton    13174: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   13175: @cindex @file{ans-report.fs}
                   13176: @cindex report the words used in your program
                   13177: @cindex words used in your program
                   13178: 
                   13179: If you want to label a Forth program as ANS Forth Program, you must
                   13180: document which wordsets the program uses; for extension wordsets, it is
                   13181: helpful to list the words the program requires from these wordsets
                   13182: (because Forth systems are allowed to provide only some words of them).
                   13183: 
                   13184: The @file{ans-report.fs} tool makes it easy for you to determine which
                   13185: words from which wordset and which non-ANS words your application
                   13186: uses. You simply have to include @file{ans-report.fs} before loading the
                   13187: program you want to check. After loading your program, you can get the
                   13188: report with @code{print-ans-report}. A typical use is to run this as
                   13189: batch job like this:
                   13190: @example
                   13191: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   13192: @end example
                   13193: 
                   13194: The output looks like this (for @file{compat/control.fs}):
                   13195: @example
                   13196: The program uses the following words
                   13197: from CORE :
                   13198: : POSTPONE THEN ; immediate ?dup IF 0= 
                   13199: from BLOCK-EXT :
                   13200: \ 
                   13201: from FILE :
                   13202: ( 
                   13203: @end example
                   13204: 
                   13205: @subsection Caveats
                   13206: 
                   13207: Note that @file{ans-report.fs} just checks which words are used, not whether
                   13208: they are used in an ANS Forth conforming way!
                   13209: 
                   13210: Some words are defined in several wordsets in the
                   13211: standard. @file{ans-report.fs} reports them for only one of the
                   13212: wordsets, and not necessarily the one you expect. It depends on usage
                   13213: which wordset is the right one to specify. E.g., if you only use the
                   13214: compilation semantics of @code{S"}, it is a Core word; if you also use
                   13215: its interpretation semantics, it is a File word.
1.124     anton    13216: 
                   13217: 
1.127     anton    13218: @node Stack depth changes,  , ANS Report, Tools
1.124     anton    13219: @section Stack depth changes during interpretation
                   13220: @cindex @file{depth-changes.fs}
                   13221: @cindex depth changes during interpretation
                   13222: @cindex stack depth changes during interpretation
                   13223: @cindex items on the stack after interpretation
                   13224: 
                   13225: Sometimes you notice that, after loading a file, there are items left
                   13226: on the stack.  The tool @file{depth-changes.fs} helps you find out
                   13227: quickly where in the file these stack items are coming from.
                   13228: 
                   13229: The simplest way of using @file{depth-changes.fs} is to include it
                   13230: before the file(s) you want to check, e.g.:
                   13231: 
                   13232: @example
                   13233: gforth depth-changes.fs my-file.fs
                   13234: @end example
                   13235: 
                   13236: This will compare the stack depths of the data and FP stack at every
                   13237: empty line (in interpretation state) against these depths at the last
                   13238: empty line (in interpretation state).  If the depths are not equal,
                   13239: the position in the file and the stack contents are printed with
                   13240: @code{~~} (@pxref{Debugging}).  This indicates that a stack depth
                   13241: change has occured in the paragraph of non-empty lines before the
                   13242: indicated line.  It is a good idea to leave an empty line at the end
                   13243: of the file, so the last paragraph is checked, too.
                   13244: 
                   13245: Checking only at empty lines usually works well, but sometimes you
                   13246: have big blocks of non-empty lines (e.g., when building a big table),
                   13247: and you want to know where in this block the stack depth changed.  You
                   13248: can check all interpreted lines with
                   13249: 
                   13250: @example
                   13251: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
                   13252: @end example
                   13253: 
                   13254: This checks the stack depth at every end-of-line.  So the depth change
                   13255: occured in the line reported by the @code{~~} (not in the line
                   13256: before).
                   13257: 
                   13258: Note that, while this offers better accuracy in indicating where the
                   13259: stack depth changes, it will often report many intentional stack depth
                   13260: changes (e.g., when an interpreted computation stretches across
                   13261: several lines).  You can suppress the checking of some lines by
                   13262: putting backslashes at the end of these lines (not followed by white
                   13263: space), and using
                   13264: 
                   13265: @example
                   13266: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
                   13267: @end example
1.1       anton    13268: 
                   13269: @c ******************************************************************
1.65      anton    13270: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1       anton    13271: @chapter ANS conformance
                   13272: @cindex ANS conformance of Gforth
                   13273: 
                   13274: To the best of our knowledge, Gforth is an
                   13275: 
                   13276: ANS Forth System
                   13277: @itemize @bullet
                   13278: @item providing the Core Extensions word set
                   13279: @item providing the Block word set
                   13280: @item providing the Block Extensions word set
                   13281: @item providing the Double-Number word set
                   13282: @item providing the Double-Number Extensions word set
                   13283: @item providing the Exception word set
                   13284: @item providing the Exception Extensions word set
                   13285: @item providing the Facility word set
1.40      anton    13286: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1       anton    13287: @item providing the File Access word set
                   13288: @item providing the File Access Extensions word set
                   13289: @item providing the Floating-Point word set
                   13290: @item providing the Floating-Point Extensions word set
                   13291: @item providing the Locals word set
                   13292: @item providing the Locals Extensions word set
                   13293: @item providing the Memory-Allocation word set
                   13294: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   13295: @item providing the Programming-Tools word set
                   13296: @item providing @code{;CODE}, @code{AHEAD}, @code{ASSEMBLER}, @code{BYE}, @code{CODE}, @code{CS-PICK}, @code{CS-ROLL}, @code{STATE}, @code{[ELSE]}, @code{[IF]}, @code{[THEN]} from the Programming-Tools Extensions word set
                   13297: @item providing the Search-Order word set
                   13298: @item providing the Search-Order Extensions word set
                   13299: @item providing the String word set
                   13300: @item providing the String Extensions word set (another easy one)
                   13301: @end itemize
                   13302: 
1.118     anton    13303: Gforth has the following environmental restrictions:
                   13304: 
                   13305: @cindex environmental restrictions
                   13306: @itemize @bullet
                   13307: @item
                   13308: While processing the OS command line, if an exception is not caught,
                   13309: Gforth exits with a non-zero exit code instyead of performing QUIT.
                   13310: 
                   13311: @item
                   13312: When an @code{throw} is performed after a @code{query}, Gforth does not
                   13313: allways restore the input source specification in effect at the
                   13314: corresponding catch.
                   13315: 
                   13316: @end itemize
                   13317: 
                   13318: 
1.1       anton    13319: @cindex system documentation
                   13320: In addition, ANS Forth systems are required to document certain
                   13321: implementation choices. This chapter tries to meet these
                   13322: requirements. In many cases it gives a way to ask the system for the
                   13323: information instead of providing the information directly, in
                   13324: particular, if the information depends on the processor, the operating
                   13325: system or the installation options chosen, or if they are likely to
                   13326: change during the maintenance of Gforth.
                   13327: 
                   13328: @comment The framework for the rest has been taken from pfe.
                   13329: 
                   13330: @menu
                   13331: * The Core Words::              
                   13332: * The optional Block word set::  
                   13333: * The optional Double Number word set::  
                   13334: * The optional Exception word set::  
                   13335: * The optional Facility word set::  
                   13336: * The optional File-Access word set::  
                   13337: * The optional Floating-Point word set::  
                   13338: * The optional Locals word set::  
                   13339: * The optional Memory-Allocation word set::  
                   13340: * The optional Programming-Tools word set::  
                   13341: * The optional Search-Order word set::  
                   13342: @end menu
                   13343: 
                   13344: 
                   13345: @c =====================================================================
                   13346: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   13347: @comment  node-name,  next,  previous,  up
                   13348: @section The Core Words
                   13349: @c =====================================================================
                   13350: @cindex core words, system documentation
                   13351: @cindex system documentation, core words
                   13352: 
                   13353: @menu
                   13354: * core-idef::                   Implementation Defined Options                   
                   13355: * core-ambcond::                Ambiguous Conditions                
                   13356: * core-other::                  Other System Documentation                  
                   13357: @end menu
                   13358: 
                   13359: @c ---------------------------------------------------------------------
                   13360: @node core-idef, core-ambcond, The Core Words, The Core Words
                   13361: @subsection Implementation Defined Options
                   13362: @c ---------------------------------------------------------------------
                   13363: @cindex core words, implementation-defined options
                   13364: @cindex implementation-defined options, core words
                   13365: 
                   13366: 
                   13367: @table @i
                   13368: @item (Cell) aligned addresses:
                   13369: @cindex cell-aligned addresses
                   13370: @cindex aligned addresses
                   13371: processor-dependent. Gforth's alignment words perform natural alignment
                   13372: (e.g., an address aligned for a datum of size 8 is divisible by
                   13373: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   13374: 
                   13375: @item @code{EMIT} and non-graphic characters:
                   13376: @cindex @code{EMIT} and non-graphic characters
                   13377: @cindex non-graphic characters and @code{EMIT}
                   13378: The character is output using the C library function (actually, macro)
                   13379: @code{putc}.
                   13380: 
                   13381: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   13382: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   13383: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   13384: @cindex @code{ACCEPT}, editing
                   13385: @cindex @code{EXPECT}, editing
                   13386: This is modeled on the GNU readline library (@pxref{Readline
                   13387: Interaction, , Command Line Editing, readline, The GNU Readline
                   13388: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   13389: producing a full word completion every time you type it (instead of
1.28      crook    13390: producing the common prefix of all completions). @xref{Command-line editing}.
1.1       anton    13391: 
                   13392: @item character set:
                   13393: @cindex character set
                   13394: The character set of your computer and display device. Gforth is
                   13395: 8-bit-clean (but some other component in your system may make trouble).
                   13396: 
                   13397: @item Character-aligned address requirements:
                   13398: @cindex character-aligned address requirements
                   13399: installation-dependent. Currently a character is represented by a C
                   13400: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   13401: (Comments on that requested).
                   13402: 
                   13403: @item character-set extensions and matching of names:
                   13404: @cindex character-set extensions and matching of names
1.26      crook    13405: @cindex case-sensitivity for name lookup
                   13406: @cindex name lookup, case-sensitivity
                   13407: @cindex locale and case-sensitivity
1.21      crook    13408: Any character except the ASCII NUL character can be used in a
1.1       anton    13409: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47      crook    13410: matching is performed using the C library function @code{strncasecmp}, whose
1.1       anton    13411: function is probably influenced by the locale. E.g., the @code{C} locale
                   13412: does not know about accents and umlauts, so they are matched
                   13413: case-sensitively in that locale. For portability reasons it is best to
                   13414: write programs such that they work in the @code{C} locale. Then one can
                   13415: use libraries written by a Polish programmer (who might use words
                   13416: containing ISO Latin-2 encoded characters) and by a French programmer
                   13417: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   13418: funny results for some of the words (which ones, depends on the font you
                   13419: are using)). Also, the locale you prefer may not be available in other
                   13420: operating systems. Hopefully, Unicode will solve these problems one day.
                   13421: 
                   13422: @item conditions under which control characters match a space delimiter:
                   13423: @cindex space delimiters
                   13424: @cindex control characters as delimiters
1.117     anton    13425: If @code{word} is called with the space character as a delimiter, all
1.1       anton    13426: white-space characters (as identified by the C macro @code{isspace()})
1.117     anton    13427: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138     anton    13428: delimiters.  @code{Parse-name}, which is used by the outer
1.1       anton    13429: interpreter (aka text interpreter) by default, treats all white-space
                   13430: characters as delimiters.
                   13431: 
1.26      crook    13432: @item format of the control-flow stack:
                   13433: @cindex control-flow stack, format
                   13434: The data stack is used as control-flow stack. The size of a control-flow
1.1       anton    13435: stack item in cells is given by the constant @code{cs-item-size}. At the
                   13436: time of this writing, an item consists of a (pointer to a) locals list
                   13437: (third), an address in the code (second), and a tag for identifying the
                   13438: item (TOS). The following tags are used: @code{defstart},
                   13439: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   13440: @code{scopestart}.
                   13441: 
                   13442: @item conversion of digits > 35
                   13443: @cindex digits > 35
                   13444: The characters @code{[\]^_'} are the digits with the decimal value
                   13445: 36@minus{}41. There is no way to input many of the larger digits.
                   13446: 
                   13447: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   13448: @cindex @code{EXPECT}, display after end of input
                   13449: @cindex @code{ACCEPT}, display after end of input
                   13450: The cursor is moved to the end of the entered string. If the input is
                   13451: terminated using the @kbd{Return} key, a space is typed.
                   13452: 
                   13453: @item exception abort sequence of @code{ABORT"}:
                   13454: @cindex exception abort sequence of @code{ABORT"}
                   13455: @cindex @code{ABORT"}, exception abort sequence
                   13456: The error string is stored into the variable @code{"error} and a
                   13457: @code{-2 throw} is performed.
                   13458: 
                   13459: @item input line terminator:
                   13460: @cindex input line terminator
                   13461: @cindex line terminator on input
1.26      crook    13462: @cindex newline character on input
1.1       anton    13463: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   13464: lines. One of these characters is typically produced when you type the
                   13465: @kbd{Enter} or @kbd{Return} key.
                   13466: 
                   13467: @item maximum size of a counted string:
                   13468: @cindex maximum size of a counted string
                   13469: @cindex counted string, maximum size
                   13470: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79      anton    13471: on all platforms, but this may change.
1.1       anton    13472: 
                   13473: @item maximum size of a parsed string:
                   13474: @cindex maximum size of a parsed string
                   13475: @cindex parsed string, maximum size
                   13476: Given by the constant @code{/line}. Currently 255 characters.
                   13477: 
                   13478: @item maximum size of a definition name, in characters:
                   13479: @cindex maximum size of a definition name, in characters
                   13480: @cindex name, maximum length
1.113     anton    13481: MAXU/8
1.1       anton    13482: 
                   13483: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   13484: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   13485: @cindex @code{ENVIRONMENT?} string length, maximum
1.113     anton    13486: MAXU/8
1.1       anton    13487: 
                   13488: @item method of selecting the user input device:
                   13489: @cindex user input device, method of selecting
                   13490: The user input device is the standard input. There is currently no way to
                   13491: change it from within Gforth. However, the input can typically be
                   13492: redirected in the command line that starts Gforth.
                   13493: 
                   13494: @item method of selecting the user output device:
                   13495: @cindex user output device, method of selecting
                   13496: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    13497: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   13498: output when the user output device is a terminal, otherwise the output
                   13499: is buffered.
1.1       anton    13500: 
                   13501: @item methods of dictionary compilation:
                   13502: What are we expected to document here?
                   13503: 
                   13504: @item number of bits in one address unit:
                   13505: @cindex number of bits in one address unit
                   13506: @cindex address unit, size in bits
                   13507: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79      anton    13508: platforms.
1.1       anton    13509: 
                   13510: @item number representation and arithmetic:
                   13511: @cindex number representation and arithmetic
1.79      anton    13512: Processor-dependent. Binary two's complement on all current platforms.
1.1       anton    13513: 
                   13514: @item ranges for integer types:
                   13515: @cindex ranges for integer types
                   13516: @cindex integer types, ranges
                   13517: Installation-dependent. Make environmental queries for @code{MAX-N},
                   13518: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   13519: unsigned (and positive) types is 0. The lower bound for signed types on
                   13520: two's complement and one's complement machines machines can be computed
                   13521: by adding 1 to the upper bound.
                   13522: 
                   13523: @item read-only data space regions:
                   13524: @cindex read-only data space regions
                   13525: @cindex data-space, read-only regions
                   13526: The whole Forth data space is writable.
                   13527: 
                   13528: @item size of buffer at @code{WORD}:
                   13529: @cindex size of buffer at @code{WORD}
                   13530: @cindex @code{WORD} buffer size
                   13531: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   13532: shared with the pictured numeric output string. If overwriting
                   13533: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   13534: space, although only as much can be sensibly used as fits in a counted
                   13535: string.
                   13536: 
                   13537: @item size of one cell in address units:
                   13538: @cindex cell size
                   13539: @code{1 cells .}.
                   13540: 
                   13541: @item size of one character in address units:
                   13542: @cindex char size
1.79      anton    13543: @code{1 chars .}. 1 on all current platforms.
1.1       anton    13544: 
                   13545: @item size of the keyboard terminal buffer:
                   13546: @cindex size of the keyboard terminal buffer
                   13547: @cindex terminal buffer, size
                   13548: Varies. You can determine the size at a specific time using @code{lp@@
                   13549: tib - .}. It is shared with the locals stack and TIBs of files that
                   13550: include the current file. You can change the amount of space for TIBs
                   13551: and locals stack at Gforth startup with the command line option
                   13552: @code{-l}.
                   13553: 
                   13554: @item size of the pictured numeric output buffer:
                   13555: @cindex size of the pictured numeric output buffer
                   13556: @cindex pictured numeric output buffer, size
                   13557: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   13558: shared with @code{WORD}.
                   13559: 
                   13560: @item size of the scratch area returned by @code{PAD}:
                   13561: @cindex size of the scratch area returned by @code{PAD}
                   13562: @cindex @code{PAD} size
                   13563: The remainder of dictionary space. @code{unused pad here - - .}.
                   13564: 
                   13565: @item system case-sensitivity characteristics:
                   13566: @cindex case-sensitivity characteristics
1.26      crook    13567: Dictionary searches are case-insensitive (except in
1.1       anton    13568: @code{TABLE}s). However, as explained above under @i{character-set
                   13569: extensions}, the matching for non-ASCII characters is determined by the
                   13570: locale you are using. In the default @code{C} locale all non-ASCII
                   13571: characters are matched case-sensitively.
                   13572: 
                   13573: @item system prompt:
                   13574: @cindex system prompt
                   13575: @cindex prompt
                   13576: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   13577: 
                   13578: @item division rounding:
                   13579: @cindex division rounding
1.166     anton    13580: The ordinary division words @code{/ mod /mod */ */mod} perform floored
                   13581: division (with the default installation of Gforth).  You can check
                   13582: this with @code{s" floored" environment? drop .}.  If you write
                   13583: programs that need a specific division rounding, best use
                   13584: @code{fm/mod} or @code{sm/rem} for portability.
1.1       anton    13585: 
                   13586: @item values of @code{STATE} when true:
                   13587: @cindex @code{STATE} values
                   13588: -1.
                   13589: 
                   13590: @item values returned after arithmetic overflow:
                   13591: On two's complement machines, arithmetic is performed modulo
                   13592: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.164     anton    13593: arithmetic (with appropriate mapping for signed types). Division by
                   13594: zero typically results in a @code{-55 throw} (Floating-point
                   13595: unidentified fault) or @code{-10 throw} (divide by zero).  Integer
1.166     anton    13596: division overflow can result in these throws, or in @code{-11 throw};
                   13597: in @code{gforth-fast} division overflow and divide by zero may also
                   13598: result in returning bogus results without producing an exception.
1.1       anton    13599: 
                   13600: @item whether the current definition can be found after @t{DOES>}:
                   13601: @cindex @t{DOES>}, visibility of current definition
                   13602: No.
                   13603: 
                   13604: @end table
                   13605: 
                   13606: @c ---------------------------------------------------------------------
                   13607: @node core-ambcond, core-other, core-idef, The Core Words
                   13608: @subsection Ambiguous conditions
                   13609: @c ---------------------------------------------------------------------
                   13610: @cindex core words, ambiguous conditions
                   13611: @cindex ambiguous conditions, core words
                   13612: 
                   13613: @table @i
                   13614: 
                   13615: @item a name is neither a word nor a number:
                   13616: @cindex name not found
1.26      crook    13617: @cindex undefined word
1.80      anton    13618: @code{-13 throw} (Undefined word).
1.1       anton    13619: 
                   13620: @item a definition name exceeds the maximum length allowed:
1.26      crook    13621: @cindex word name too long
1.1       anton    13622: @code{-19 throw} (Word name too long)
                   13623: 
                   13624: @item addressing a region not inside the various data spaces of the forth system:
                   13625: @cindex Invalid memory address
1.32      anton    13626: The stacks, code space and header space are accessible. Machine code space is
1.1       anton    13627: typically readable. Accessing other addresses gives results dependent on
                   13628: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   13629: address).
                   13630: 
                   13631: @item argument type incompatible with parameter:
1.26      crook    13632: @cindex argument type mismatch
1.1       anton    13633: This is usually not caught. Some words perform checks, e.g., the control
                   13634: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   13635: mismatch).
                   13636: 
                   13637: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   13638: @cindex Interpreting a compile-only word, for @code{'} etc.
                   13639: @cindex execution token of words with undefined execution semantics
                   13640: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   13641: get an execution token for @code{compile-only-error} (which performs a
                   13642: @code{-14 throw} when executed).
                   13643: 
                   13644: @item dividing by zero:
                   13645: @cindex dividing by zero
                   13646: @cindex floating point unidentified fault, integer division
1.80      anton    13647: On some platforms, this produces a @code{-10 throw} (Division by
1.24      anton    13648: zero); on other systems, this typically results in a @code{-55 throw}
                   13649: (Floating-point unidentified fault).
1.1       anton    13650: 
                   13651: @item insufficient data stack or return stack space:
                   13652: @cindex insufficient data stack or return stack space
                   13653: @cindex stack overflow
1.26      crook    13654: @cindex address alignment exception, stack overflow
1.1       anton    13655: @cindex Invalid memory address, stack overflow
                   13656: Depending on the operating system, the installation, and the invocation
                   13657: of Gforth, this is either checked by the memory management hardware, or
1.24      anton    13658: it is not checked. If it is checked, you typically get a @code{-3 throw}
                   13659: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
                   13660: throw} (Invalid memory address) (depending on the platform and how you
                   13661: achieved the overflow) as soon as the overflow happens. If it is not
                   13662: checked, overflows typically result in mysterious illegal memory
                   13663: accesses, producing @code{-9 throw} (Invalid memory address) or
                   13664: @code{-23 throw} (Address alignment exception); they might also destroy
                   13665: the internal data structure of @code{ALLOCATE} and friends, resulting in
                   13666: various errors in these words.
1.1       anton    13667: 
                   13668: @item insufficient space for loop control parameters:
                   13669: @cindex insufficient space for loop control parameters
1.80      anton    13670: Like other return stack overflows.
1.1       anton    13671: 
                   13672: @item insufficient space in the dictionary:
                   13673: @cindex insufficient space in the dictionary
                   13674: @cindex dictionary overflow
1.12      anton    13675: If you try to allot (either directly with @code{allot}, or indirectly
                   13676: with @code{,}, @code{create} etc.) more memory than available in the
                   13677: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   13678: to access memory beyond the end of the dictionary, the results are
                   13679: similar to stack overflows.
1.1       anton    13680: 
                   13681: @item interpreting a word with undefined interpretation semantics:
                   13682: @cindex interpreting a word with undefined interpretation semantics
                   13683: @cindex Interpreting a compile-only word
                   13684: For some words, we have defined interpretation semantics. For the
                   13685: others: @code{-14 throw} (Interpreting a compile-only word).
                   13686: 
                   13687: @item modifying the contents of the input buffer or a string literal:
                   13688: @cindex modifying the contents of the input buffer or a string literal
                   13689: These are located in writable memory and can be modified.
                   13690: 
                   13691: @item overflow of the pictured numeric output string:
                   13692: @cindex overflow of the pictured numeric output string
                   13693: @cindex pictured numeric output string, overflow
1.24      anton    13694: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1       anton    13695: 
                   13696: @item parsed string overflow:
                   13697: @cindex parsed string overflow
                   13698: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   13699: 
                   13700: @item producing a result out of range:
                   13701: @cindex result out of range
                   13702: On two's complement machines, arithmetic is performed modulo
                   13703: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.166     anton    13704: arithmetic (with appropriate mapping for signed types). Division by
                   13705: zero typically results in a @code{-10 throw} (divide by zero) or
                   13706: @code{-55 throw} (floating point unidentified fault). Overflow on
                   13707: division may result in these errors or in @code{-11 throw} (result out
                   13708: of range).  @code{Gforth-fast} may silently produce bogus results on
                   13709: division overflow or division by zero.  @code{Convert} and
1.24      anton    13710: @code{>number} currently overflow silently.
1.1       anton    13711: 
                   13712: @item reading from an empty data or return stack:
                   13713: @cindex stack empty
                   13714: @cindex stack underflow
1.24      anton    13715: @cindex return stack underflow
1.1       anton    13716: The data stack is checked by the outer (aka text) interpreter after
                   13717: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   13718: underflow) is performed. Apart from that, stacks may be checked or not,
1.24      anton    13719: depending on operating system, installation, and invocation. If they are
                   13720: caught by a check, they typically result in @code{-4 throw} (Stack
                   13721: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
                   13722: (Invalid memory address), depending on the platform and which stack
                   13723: underflows and by how much. Note that even if the system uses checking
                   13724: (through the MMU), your program may have to underflow by a significant
                   13725: number of stack items to trigger the reaction (the reason for this is
                   13726: that the MMU, and therefore the checking, works with a page-size
                   13727: granularity).  If there is no checking, the symptoms resulting from an
                   13728: underflow are similar to those from an overflow.  Unbalanced return
1.80      anton    13729: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24      anton    13730: (Invalid memory address) and Illegal Instruction (typically @code{-260
                   13731: throw}).
1.1       anton    13732: 
                   13733: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   13734: @cindex unexpected end of the input buffer
                   13735: @cindex zero-length string as a name
                   13736: @cindex Attempt to use zero-length string as a name
                   13737: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   13738: use zero-length string as a name). Words like @code{'} probably will not
                   13739: find what they search. Note that it is possible to create zero-length
                   13740: names with @code{nextname} (should it not?).
                   13741: 
                   13742: @item @code{>IN} greater than input buffer:
                   13743: @cindex @code{>IN} greater than input buffer
                   13744: The next invocation of a parsing word returns a string with length 0.
                   13745: 
                   13746: @item @code{RECURSE} appears after @code{DOES>}:
                   13747: @cindex @code{RECURSE} appears after @code{DOES>}
                   13748: Compiles a recursive call to the defining word, not to the defined word.
                   13749: 
                   13750: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   13751: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26      crook    13752: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1       anton    13753: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   13754: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   13755: the end of the file was reached), its source-id may be
                   13756: reused. Therefore, restoring an input source specification referencing a
                   13757: closed file may lead to unpredictable results instead of a @code{-12
                   13758: THROW}.
                   13759: 
                   13760: In the future, Gforth may be able to restore input source specifications
                   13761: from other than the current input source.
                   13762: 
                   13763: @item data space containing definitions gets de-allocated:
                   13764: @cindex data space containing definitions gets de-allocated
                   13765: Deallocation with @code{allot} is not checked. This typically results in
                   13766: memory access faults or execution of illegal instructions.
                   13767: 
                   13768: @item data space read/write with incorrect alignment:
                   13769: @cindex data space read/write with incorrect alignment
                   13770: @cindex alignment faults
1.26      crook    13771: @cindex address alignment exception
1.1       anton    13772: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    13773: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    13774: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   13775: (Invalid memory address). There are reportedly some processors with
1.12      anton    13776: alignment restrictions that do not report violations.
1.1       anton    13777: 
                   13778: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   13779: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   13780: Like other alignment errors.
                   13781: 
                   13782: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   13783: Like other stack underflows.
                   13784: 
                   13785: @item loop control parameters not available:
                   13786: @cindex loop control parameters not available
                   13787: Not checked. The counted loop words simply assume that the top of return
                   13788: stack items are loop control parameters and behave accordingly.
                   13789: 
                   13790: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   13791: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   13792: @cindex last word was headerless
                   13793: @code{abort" last word was headerless"}.
                   13794: 
                   13795: @item name not defined by @code{VALUE} used by @code{TO}:
                   13796: @cindex name not defined by @code{VALUE} used by @code{TO}
                   13797: @cindex @code{TO} on non-@code{VALUE}s
                   13798: @cindex Invalid name argument, @code{TO}
                   13799: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   13800: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   13801: 
                   13802: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   13803: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26      crook    13804: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1       anton    13805: @code{-13 throw} (Undefined word)
                   13806: 
                   13807: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   13808: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   13809: Gforth behaves as if they were of the same type. I.e., you can predict
                   13810: the behaviour by interpreting all parameters as, e.g., signed.
                   13811: 
                   13812: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   13813: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   13814: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   13815: compilation semantics of @code{TO}.
                   13816: 
                   13817: @item String longer than a counted string returned by @code{WORD}:
1.26      crook    13818: @cindex string longer than a counted string returned by @code{WORD}
1.1       anton    13819: @cindex @code{WORD}, string overflow
                   13820: Not checked. The string will be ok, but the count will, of course,
                   13821: contain only the least significant bits of the length.
                   13822: 
                   13823: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   13824: @cindex @code{LSHIFT}, large shift counts
                   13825: @cindex @code{RSHIFT}, large shift counts
                   13826: Processor-dependent. Typical behaviours are returning 0 and using only
                   13827: the low bits of the shift count.
                   13828: 
                   13829: @item word not defined via @code{CREATE}:
                   13830: @cindex @code{>BODY} of non-@code{CREATE}d words
                   13831: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   13832: 
                   13833: @cindex @code{DOES>} of non-@code{CREATE}d words
                   13834: @code{DOES>} changes the execution semantics of the last defined word no
                   13835: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   13836: @code{CREATE , DOES>}.
                   13837: 
                   13838: @item words improperly used outside @code{<#} and @code{#>}:
                   13839: Not checked. As usual, you can expect memory faults.
                   13840: 
                   13841: @end table
                   13842: 
                   13843: 
                   13844: @c ---------------------------------------------------------------------
                   13845: @node core-other,  , core-ambcond, The Core Words
                   13846: @subsection Other system documentation
                   13847: @c ---------------------------------------------------------------------
                   13848: @cindex other system documentation, core words
                   13849: @cindex core words, other system documentation
                   13850: 
                   13851: @table @i
                   13852: @item nonstandard words using @code{PAD}:
                   13853: @cindex @code{PAD} use by nonstandard words
                   13854: None.
                   13855: 
                   13856: @item operator's terminal facilities available:
                   13857: @cindex operator's terminal facilities available
1.80      anton    13858: After processing the OS's command line, Gforth goes into interactive mode,
1.1       anton    13859: and you can give commands to Gforth interactively. The actual facilities
                   13860: available depend on how you invoke Gforth.
                   13861: 
                   13862: @item program data space available:
                   13863: @cindex program data space available
                   13864: @cindex data space available
                   13865: @code{UNUSED .} gives the remaining dictionary space. The total
                   13866: dictionary space can be specified with the @code{-m} switch
                   13867: (@pxref{Invoking Gforth}) when Gforth starts up.
                   13868: 
                   13869: @item return stack space available:
                   13870: @cindex return stack space available
                   13871: You can compute the total return stack space in cells with
                   13872: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   13873: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   13874: 
                   13875: @item stack space available:
                   13876: @cindex stack space available
                   13877: You can compute the total data stack space in cells with
                   13878: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   13879: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   13880: 
                   13881: @item system dictionary space required, in address units:
                   13882: @cindex system dictionary space required, in address units
                   13883: Type @code{here forthstart - .} after startup. At the time of this
                   13884: writing, this gives 80080 (bytes) on a 32-bit system.
                   13885: @end table
                   13886: 
                   13887: 
                   13888: @c =====================================================================
                   13889: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   13890: @section The optional Block word set
                   13891: @c =====================================================================
                   13892: @cindex system documentation, block words
                   13893: @cindex block words, system documentation
                   13894: 
                   13895: @menu
                   13896: * block-idef::                  Implementation Defined Options
                   13897: * block-ambcond::               Ambiguous Conditions               
                   13898: * block-other::                 Other System Documentation                 
                   13899: @end menu
                   13900: 
                   13901: 
                   13902: @c ---------------------------------------------------------------------
                   13903: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   13904: @subsection Implementation Defined Options
                   13905: @c ---------------------------------------------------------------------
                   13906: @cindex implementation-defined options, block words
                   13907: @cindex block words, implementation-defined options
                   13908: 
                   13909: @table @i
                   13910: @item the format for display by @code{LIST}:
                   13911: @cindex @code{LIST} display format
                   13912: First the screen number is displayed, then 16 lines of 64 characters,
                   13913: each line preceded by the line number.
                   13914: 
                   13915: @item the length of a line affected by @code{\}:
                   13916: @cindex length of a line affected by @code{\}
                   13917: @cindex @code{\}, line length in blocks
                   13918: 64 characters.
                   13919: @end table
                   13920: 
                   13921: 
                   13922: @c ---------------------------------------------------------------------
                   13923: @node block-ambcond, block-other, block-idef, The optional Block word set
                   13924: @subsection Ambiguous conditions
                   13925: @c ---------------------------------------------------------------------
                   13926: @cindex block words, ambiguous conditions
                   13927: @cindex ambiguous conditions, block words
                   13928: 
                   13929: @table @i
                   13930: @item correct block read was not possible:
                   13931: @cindex block read not possible
                   13932: Typically results in a @code{throw} of some OS-derived value (between
                   13933: -512 and -2048). If the blocks file was just not long enough, blanks are
                   13934: supplied for the missing portion.
                   13935: 
                   13936: @item I/O exception in block transfer:
                   13937: @cindex I/O exception in block transfer
                   13938: @cindex block transfer, I/O exception
                   13939: Typically results in a @code{throw} of some OS-derived value (between
                   13940: -512 and -2048).
                   13941: 
                   13942: @item invalid block number:
                   13943: @cindex invalid block number
                   13944: @cindex block number invalid
                   13945: @code{-35 throw} (Invalid block number)
                   13946: 
                   13947: @item a program directly alters the contents of @code{BLK}:
                   13948: @cindex @code{BLK}, altering @code{BLK}
                   13949: The input stream is switched to that other block, at the same
                   13950: position. If the storing to @code{BLK} happens when interpreting
                   13951: non-block input, the system will get quite confused when the block ends.
                   13952: 
                   13953: @item no current block buffer for @code{UPDATE}:
                   13954: @cindex @code{UPDATE}, no current block buffer
                   13955: @code{UPDATE} has no effect.
                   13956: 
                   13957: @end table
                   13958: 
                   13959: @c ---------------------------------------------------------------------
                   13960: @node block-other,  , block-ambcond, The optional Block word set
                   13961: @subsection Other system documentation
                   13962: @c ---------------------------------------------------------------------
                   13963: @cindex other system documentation, block words
                   13964: @cindex block words, other system documentation
                   13965: 
                   13966: @table @i
                   13967: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   13968: No restrictions (yet).
                   13969: 
                   13970: @item the number of blocks available for source and data:
                   13971: depends on your disk space.
                   13972: 
                   13973: @end table
                   13974: 
                   13975: 
                   13976: @c =====================================================================
                   13977: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   13978: @section The optional Double Number word set
                   13979: @c =====================================================================
                   13980: @cindex system documentation, double words
                   13981: @cindex double words, system documentation
                   13982: 
                   13983: @menu
                   13984: * double-ambcond::              Ambiguous Conditions              
                   13985: @end menu
                   13986: 
                   13987: 
                   13988: @c ---------------------------------------------------------------------
                   13989: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   13990: @subsection Ambiguous conditions
                   13991: @c ---------------------------------------------------------------------
                   13992: @cindex double words, ambiguous conditions
                   13993: @cindex ambiguous conditions, double words
                   13994: 
                   13995: @table @i
1.29      crook    13996: @item @i{d} outside of range of @i{n} in @code{D>S}:
                   13997: @cindex @code{D>S}, @i{d} out of range of @i{n} 
                   13998: The least significant cell of @i{d} is produced.
1.1       anton    13999: 
                   14000: @end table
                   14001: 
                   14002: 
                   14003: @c =====================================================================
                   14004: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   14005: @section The optional Exception word set
                   14006: @c =====================================================================
                   14007: @cindex system documentation, exception words
                   14008: @cindex exception words, system documentation
                   14009: 
                   14010: @menu
                   14011: * exception-idef::              Implementation Defined Options              
                   14012: @end menu
                   14013: 
                   14014: 
                   14015: @c ---------------------------------------------------------------------
                   14016: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   14017: @subsection Implementation Defined Options
                   14018: @c ---------------------------------------------------------------------
                   14019: @cindex implementation-defined options, exception words
                   14020: @cindex exception words, implementation-defined options
                   14021: 
                   14022: @table @i
                   14023: @item @code{THROW}-codes used in the system:
                   14024: @cindex @code{THROW}-codes used in the system
                   14025: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29      crook    14026: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1       anton    14027: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   14028: allocation operations). The mapping from OS error numbers to throw codes
                   14029: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   14030: undefined OS errors produce a message with a strange number; e.g.,
                   14031: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   14032: @end table
                   14033: 
                   14034: @c =====================================================================
                   14035: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   14036: @section The optional Facility word set
                   14037: @c =====================================================================
                   14038: @cindex system documentation, facility words
                   14039: @cindex facility words, system documentation
                   14040: 
                   14041: @menu
                   14042: * facility-idef::               Implementation Defined Options               
                   14043: * facility-ambcond::            Ambiguous Conditions            
                   14044: @end menu
                   14045: 
                   14046: 
                   14047: @c ---------------------------------------------------------------------
                   14048: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   14049: @subsection Implementation Defined Options
                   14050: @c ---------------------------------------------------------------------
                   14051: @cindex implementation-defined options, facility words
                   14052: @cindex facility words, implementation-defined options
                   14053: 
                   14054: @table @i
                   14055: @item encoding of keyboard events (@code{EKEY}):
                   14056: @cindex keyboard events, encoding in @code{EKEY}
                   14057: @cindex @code{EKEY}, encoding of keyboard events
1.40      anton    14058: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41      anton    14059: Other keys are encoded with the constants @code{k-left}, @code{k-right},
                   14060: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
                   14061: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
                   14062: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40      anton    14063: 
1.1       anton    14064: 
                   14065: @item duration of a system clock tick:
                   14066: @cindex duration of a system clock tick
                   14067: @cindex clock tick duration
                   14068: System dependent. With respect to @code{MS}, the time is specified in
                   14069: microseconds. How well the OS and the hardware implement this, is
                   14070: another question.
                   14071: 
                   14072: @item repeatability to be expected from the execution of @code{MS}:
                   14073: @cindex repeatability to be expected from the execution of @code{MS}
                   14074: @cindex @code{MS}, repeatability to be expected
                   14075: System dependent. On Unix, a lot depends on load. If the system is
                   14076: lightly loaded, and the delay is short enough that Gforth does not get
                   14077: swapped out, the performance should be acceptable. Under MS-DOS and
                   14078: other single-tasking systems, it should be good.
                   14079: 
                   14080: @end table
                   14081: 
                   14082: 
                   14083: @c ---------------------------------------------------------------------
                   14084: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   14085: @subsection Ambiguous conditions
                   14086: @c ---------------------------------------------------------------------
                   14087: @cindex facility words, ambiguous conditions
                   14088: @cindex ambiguous conditions, facility words
                   14089: 
                   14090: @table @i
                   14091: @item @code{AT-XY} can't be performed on user output device:
                   14092: @cindex @code{AT-XY} can't be performed on user output device
                   14093: Largely terminal dependent. No range checks are done on the arguments.
                   14094: No errors are reported. You may see some garbage appearing, you may see
                   14095: simply nothing happen.
                   14096: 
                   14097: @end table
                   14098: 
                   14099: 
                   14100: @c =====================================================================
                   14101: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   14102: @section The optional File-Access word set
                   14103: @c =====================================================================
                   14104: @cindex system documentation, file words
                   14105: @cindex file words, system documentation
                   14106: 
                   14107: @menu
                   14108: * file-idef::                   Implementation Defined Options
                   14109: * file-ambcond::                Ambiguous Conditions                
                   14110: @end menu
                   14111: 
                   14112: @c ---------------------------------------------------------------------
                   14113: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   14114: @subsection Implementation Defined Options
                   14115: @c ---------------------------------------------------------------------
                   14116: @cindex implementation-defined options, file words
                   14117: @cindex file words, implementation-defined options
                   14118: 
                   14119: @table @i
                   14120: @item file access methods used:
                   14121: @cindex file access methods used
                   14122: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   14123: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   14124: @code{wb}): The file is cleared, if it exists, and created, if it does
                   14125: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   14126: @code{create-file} creates a file with 666 permissions modified by your
                   14127: umask.
                   14128: 
                   14129: @item file exceptions:
                   14130: @cindex file exceptions
                   14131: The file words do not raise exceptions (except, perhaps, memory access
                   14132: faults when you pass illegal addresses or file-ids).
                   14133: 
                   14134: @item file line terminator:
                   14135: @cindex file line terminator
                   14136: System-dependent. Gforth uses C's newline character as line
                   14137: terminator. What the actual character code(s) of this are is
                   14138: system-dependent.
                   14139: 
                   14140: @item file name format:
                   14141: @cindex file name format
                   14142: System dependent. Gforth just uses the file name format of your OS.
                   14143: 
                   14144: @item information returned by @code{FILE-STATUS}:
                   14145: @cindex @code{FILE-STATUS}, returned information
                   14146: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   14147: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   14148: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   14149: along with the returned mode.
                   14150: 
                   14151: @item input file state after an exception when including source:
                   14152: @cindex exception when including source
                   14153: All files that are left via the exception are closed.
                   14154: 
1.29      crook    14155: @item @i{ior} values and meaning:
                   14156: @cindex @i{ior} values and meaning
1.68      anton    14157: @cindex @i{wior} values and meaning
1.29      crook    14158: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    14159: intended as throw codes. They typically are in the range
                   14160: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    14161: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    14162: 
                   14163: @item maximum depth of file input nesting:
                   14164: @cindex maximum depth of file input nesting
                   14165: @cindex file input nesting, maximum depth
                   14166: limited by the amount of return stack, locals/TIB stack, and the number
                   14167: of open files available. This should not give you troubles.
                   14168: 
                   14169: @item maximum size of input line:
                   14170: @cindex maximum size of input line
                   14171: @cindex input line size, maximum
                   14172: @code{/line}. Currently 255.
                   14173: 
                   14174: @item methods of mapping block ranges to files:
                   14175: @cindex mapping block ranges to files
                   14176: @cindex files containing blocks
                   14177: @cindex blocks in files
                   14178: By default, blocks are accessed in the file @file{blocks.fb} in the
                   14179: current working directory. The file can be switched with @code{USE}.
                   14180: 
                   14181: @item number of string buffers provided by @code{S"}:
                   14182: @cindex @code{S"}, number of string buffers
                   14183: 1
                   14184: 
                   14185: @item size of string buffer used by @code{S"}:
                   14186: @cindex @code{S"}, size of string buffer
                   14187: @code{/line}. currently 255.
                   14188: 
                   14189: @end table
                   14190: 
                   14191: @c ---------------------------------------------------------------------
                   14192: @node file-ambcond,  , file-idef, The optional File-Access word set
                   14193: @subsection Ambiguous conditions
                   14194: @c ---------------------------------------------------------------------
                   14195: @cindex file words, ambiguous conditions
                   14196: @cindex ambiguous conditions, file words
                   14197: 
                   14198: @table @i
                   14199: @item attempting to position a file outside its boundaries:
                   14200: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   14201: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   14202: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   14203: 
                   14204: @item attempting to read from file positions not yet written:
                   14205: @cindex reading from file positions not yet written
                   14206: End-of-file, i.e., zero characters are read and no error is reported.
                   14207: 
1.29      crook    14208: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
                   14209: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
1.1       anton    14210: An appropriate exception may be thrown, but a memory fault or other
                   14211: problem is more probable.
                   14212: 
1.29      crook    14213: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
                   14214: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
                   14215: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
                   14216: The @i{ior} produced by the operation, that discovered the problem, is
1.1       anton    14217: thrown.
                   14218: 
                   14219: @item named file cannot be opened (@code{INCLUDED}):
                   14220: @cindex @code{INCLUDED}, named file cannot be opened
1.29      crook    14221: The @i{ior} produced by @code{open-file} is thrown.
1.1       anton    14222: 
                   14223: @item requesting an unmapped block number:
                   14224: @cindex unmapped block numbers
                   14225: There are no unmapped legal block numbers. On some operating systems,
                   14226: writing a block with a large number may overflow the file system and
                   14227: have an error message as consequence.
                   14228: 
                   14229: @item using @code{source-id} when @code{blk} is non-zero:
                   14230: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   14231: @code{source-id} performs its function. Typically it will give the id of
                   14232: the source which loaded the block. (Better ideas?)
                   14233: 
                   14234: @end table
                   14235: 
                   14236: 
                   14237: @c =====================================================================
                   14238: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   14239: @section The optional Floating-Point word set
                   14240: @c =====================================================================
                   14241: @cindex system documentation, floating-point words
                   14242: @cindex floating-point words, system documentation
                   14243: 
                   14244: @menu
                   14245: * floating-idef::               Implementation Defined Options
                   14246: * floating-ambcond::            Ambiguous Conditions            
                   14247: @end menu
                   14248: 
                   14249: 
                   14250: @c ---------------------------------------------------------------------
                   14251: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   14252: @subsection Implementation Defined Options
                   14253: @c ---------------------------------------------------------------------
                   14254: @cindex implementation-defined options, floating-point words
                   14255: @cindex floating-point words, implementation-defined options
                   14256: 
                   14257: @table @i
                   14258: @item format and range of floating point numbers:
                   14259: @cindex format and range of floating point numbers
                   14260: @cindex floating point numbers, format and range
                   14261: System-dependent; the @code{double} type of C.
                   14262: 
1.29      crook    14263: @item results of @code{REPRESENT} when @i{float} is out of range:
                   14264: @cindex  @code{REPRESENT}, results when @i{float} is out of range
1.1       anton    14265: System dependent; @code{REPRESENT} is implemented using the C library
                   14266: function @code{ecvt()} and inherits its behaviour in this respect.
                   14267: 
                   14268: @item rounding or truncation of floating-point numbers:
                   14269: @cindex rounding of floating-point numbers
                   14270: @cindex truncation of floating-point numbers
                   14271: @cindex floating-point numbers, rounding or truncation
                   14272: System dependent; the rounding behaviour is inherited from the hosting C
                   14273: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   14274: nearest, and break ties by rounding to even (i.e., such that the last
                   14275: bit of the mantissa is 0).
                   14276: 
                   14277: @item size of floating-point stack:
                   14278: @cindex floating-point stack size
                   14279: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   14280: the floating-point stack (in floats). You can specify this on startup
                   14281: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   14282: 
                   14283: @item width of floating-point stack:
                   14284: @cindex floating-point stack width 
                   14285: @code{1 floats}.
                   14286: 
                   14287: @end table
                   14288: 
                   14289: 
                   14290: @c ---------------------------------------------------------------------
                   14291: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   14292: @subsection Ambiguous conditions
                   14293: @c ---------------------------------------------------------------------
                   14294: @cindex floating-point words, ambiguous conditions
                   14295: @cindex ambiguous conditions, floating-point words
                   14296: 
                   14297: @table @i
                   14298: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   14299: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   14300: System-dependent. Typically results in a @code{-23 THROW} like other
                   14301: alignment violations.
                   14302: 
                   14303: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   14304: @cindex @code{f@@} used with an address that is not float aligned
                   14305: @cindex @code{f!} used with an address that is not float aligned
                   14306: System-dependent. Typically results in a @code{-23 THROW} like other
                   14307: alignment violations.
                   14308: 
                   14309: @item floating-point result out of range:
                   14310: @cindex floating-point result out of range
1.80      anton    14311: System-dependent. Can result in a @code{-43 throw} (floating point
                   14312: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
                   14313: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1       anton    14314: unidentified fault), or can produce a special value representing, e.g.,
                   14315: Infinity.
                   14316: 
                   14317: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   14318: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   14319: System-dependent. Typically results in an alignment fault like other
                   14320: alignment violations.
                   14321: 
1.35      anton    14322: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   14323: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1       anton    14324: The floating-point number is converted into decimal nonetheless.
                   14325: 
                   14326: @item Both arguments are equal to zero (@code{FATAN2}):
                   14327: @cindex @code{FATAN2}, both arguments are equal to zero
                   14328: System-dependent. @code{FATAN2} is implemented using the C library
                   14329: function @code{atan2()}.
                   14330: 
1.29      crook    14331: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
                   14332: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
                   14333: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1       anton    14334: because of small errors and the tan will be a very large (or very small)
                   14335: but finite number.
                   14336: 
1.29      crook    14337: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
                   14338: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1       anton    14339: The result is rounded to the nearest float.
                   14340: 
                   14341: @item dividing by zero:
                   14342: @cindex dividing by zero, floating-point
                   14343: @cindex floating-point dividing by zero
                   14344: @cindex floating-point unidentified fault, FP divide-by-zero
1.80      anton    14345: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
                   14346: (floating point divide by zero) or @code{-55 throw} (Floating-point
                   14347: unidentified fault).
1.1       anton    14348: 
                   14349: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   14350: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   14351: System dependent. On IEEE-FP based systems the number is converted into
                   14352: an infinity.
                   14353: 
1.29      crook    14354: @item @i{float}<1 (@code{FACOSH}):
                   14355: @cindex @code{FACOSH}, @i{float}<1
1.1       anton    14356: @cindex floating-point unidentified fault, @code{FACOSH}
1.80      anton    14357: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1       anton    14358: 
1.29      crook    14359: @item @i{float}=<-1 (@code{FLNP1}):
                   14360: @cindex @code{FLNP1}, @i{float}=<-1
1.1       anton    14361: @cindex floating-point unidentified fault, @code{FLNP1}
1.80      anton    14362: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
                   14363: negative infinity for @i{float}=-1).
1.1       anton    14364: 
1.29      crook    14365: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
                   14366: @cindex @code{FLN}, @i{float}=<0
                   14367: @cindex @code{FLOG}, @i{float}=<0
1.1       anton    14368: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80      anton    14369: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
                   14370: negative infinity for @i{float}=0).
1.1       anton    14371: 
1.29      crook    14372: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
                   14373: @cindex @code{FASINH}, @i{float}<0
                   14374: @cindex @code{FSQRT}, @i{float}<0
1.1       anton    14375: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80      anton    14376: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
                   14377: @code{fasinh} some platforms produce a NaN, others a number (bug in the
                   14378: C library?).
1.1       anton    14379: 
1.29      crook    14380: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
                   14381: @cindex @code{FACOS}, |@i{float}|>1
                   14382: @cindex @code{FASIN}, |@i{float}|>1
                   14383: @cindex @code{FATANH}, |@i{float}|>1
1.1       anton    14384: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80      anton    14385: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1       anton    14386: 
1.29      crook    14387: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
                   14388: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1       anton    14389: @cindex floating-point unidentified fault, @code{F>D}
1.80      anton    14390: Platform-dependent; typically, some double number is produced and no
                   14391: error is reported.
1.1       anton    14392: 
                   14393: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   14394: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80      anton    14395: @code{Precision} characters of the numeric output area are used.  If
                   14396: @code{precision} is too high, these words will smash the data or code
                   14397: close to @code{here}.
1.1       anton    14398: @end table
                   14399: 
                   14400: @c =====================================================================
                   14401: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   14402: @section The optional Locals word set
                   14403: @c =====================================================================
                   14404: @cindex system documentation, locals words
                   14405: @cindex locals words, system documentation
                   14406: 
                   14407: @menu
                   14408: * locals-idef::                 Implementation Defined Options                 
                   14409: * locals-ambcond::              Ambiguous Conditions              
                   14410: @end menu
                   14411: 
                   14412: 
                   14413: @c ---------------------------------------------------------------------
                   14414: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   14415: @subsection Implementation Defined Options
                   14416: @c ---------------------------------------------------------------------
                   14417: @cindex implementation-defined options, locals words
                   14418: @cindex locals words, implementation-defined options
                   14419: 
                   14420: @table @i
                   14421: @item maximum number of locals in a definition:
                   14422: @cindex maximum number of locals in a definition
                   14423: @cindex locals, maximum number in a definition
                   14424: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   14425: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   14426: characters. The number of locals in a definition is bounded by the size
                   14427: of locals-buffer, which contains the names of the locals.
                   14428: 
                   14429: @end table
                   14430: 
                   14431: 
                   14432: @c ---------------------------------------------------------------------
                   14433: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   14434: @subsection Ambiguous conditions
                   14435: @c ---------------------------------------------------------------------
                   14436: @cindex locals words, ambiguous conditions
                   14437: @cindex ambiguous conditions, locals words
                   14438: 
                   14439: @table @i
                   14440: @item executing a named local in interpretation state:
                   14441: @cindex local in interpretation state
                   14442: @cindex Interpreting a compile-only word, for a local
                   14443: Locals have no interpretation semantics. If you try to perform the
                   14444: interpretation semantics, you will get a @code{-14 throw} somewhere
                   14445: (Interpreting a compile-only word). If you perform the compilation
                   14446: semantics, the locals access will be compiled (irrespective of state).
                   14447: 
1.29      crook    14448: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1       anton    14449: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   14450: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   14451: @cindex Invalid name argument, @code{TO}
                   14452: @code{-32 throw} (Invalid name argument)
                   14453: 
                   14454: @end table
                   14455: 
                   14456: 
                   14457: @c =====================================================================
                   14458: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   14459: @section The optional Memory-Allocation word set
                   14460: @c =====================================================================
                   14461: @cindex system documentation, memory-allocation words
                   14462: @cindex memory-allocation words, system documentation
                   14463: 
                   14464: @menu
                   14465: * memory-idef::                 Implementation Defined Options                 
                   14466: @end menu
                   14467: 
                   14468: 
                   14469: @c ---------------------------------------------------------------------
                   14470: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   14471: @subsection Implementation Defined Options
                   14472: @c ---------------------------------------------------------------------
                   14473: @cindex implementation-defined options, memory-allocation words
                   14474: @cindex memory-allocation words, implementation-defined options
                   14475: 
                   14476: @table @i
1.29      crook    14477: @item values and meaning of @i{ior}:
                   14478: @cindex  @i{ior} values and meaning
                   14479: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    14480: intended as throw codes. They typically are in the range
                   14481: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    14482: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    14483: 
                   14484: @end table
                   14485: 
                   14486: @c =====================================================================
                   14487: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   14488: @section The optional Programming-Tools word set
                   14489: @c =====================================================================
                   14490: @cindex system documentation, programming-tools words
                   14491: @cindex programming-tools words, system documentation
                   14492: 
                   14493: @menu
                   14494: * programming-idef::            Implementation Defined Options            
                   14495: * programming-ambcond::         Ambiguous Conditions         
                   14496: @end menu
                   14497: 
                   14498: 
                   14499: @c ---------------------------------------------------------------------
                   14500: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   14501: @subsection Implementation Defined Options
                   14502: @c ---------------------------------------------------------------------
                   14503: @cindex implementation-defined options, programming-tools words
                   14504: @cindex programming-tools words, implementation-defined options
                   14505: 
                   14506: @table @i
                   14507: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   14508: @cindex @code{;CODE} ending sequence
                   14509: @cindex @code{CODE} ending sequence
                   14510: @code{END-CODE}
                   14511: 
                   14512: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   14513: @cindex @code{;CODE}, processing input
                   14514: @cindex @code{CODE}, processing input
                   14515: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   14516: the input is processed by the text interpreter, (starting) in interpret
                   14517: state.
                   14518: 
                   14519: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   14520: @cindex @code{ASSEMBLER}, search order capability
                   14521: The ANS Forth search order word set.
                   14522: 
                   14523: @item source and format of display by @code{SEE}:
                   14524: @cindex @code{SEE}, source and format of output
1.80      anton    14525: The source for @code{see} is the executable code used by the inner
1.1       anton    14526: interpreter.  The current @code{see} tries to output Forth source code
1.80      anton    14527: (and on some platforms, assembly code for primitives) as well as
                   14528: possible.
1.1       anton    14529: 
                   14530: @end table
                   14531: 
                   14532: @c ---------------------------------------------------------------------
                   14533: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   14534: @subsection Ambiguous conditions
                   14535: @c ---------------------------------------------------------------------
                   14536: @cindex programming-tools words, ambiguous conditions
                   14537: @cindex ambiguous conditions, programming-tools words
                   14538: 
                   14539: @table @i
                   14540: 
1.21      crook    14541: @item deleting the compilation word list (@code{FORGET}):
                   14542: @cindex @code{FORGET}, deleting the compilation word list
1.1       anton    14543: Not implemented (yet).
                   14544: 
1.29      crook    14545: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
                   14546: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
                   14547: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1       anton    14548: @cindex control-flow stack underflow
                   14549: This typically results in an @code{abort"} with a descriptive error
                   14550: message (may change into a @code{-22 throw} (Control structure mismatch)
                   14551: in the future). You may also get a memory access error. If you are
                   14552: unlucky, this ambiguous condition is not caught.
                   14553: 
1.29      crook    14554: @item @i{name} can't be found (@code{FORGET}):
                   14555: @cindex @code{FORGET}, @i{name} can't be found
1.1       anton    14556: Not implemented (yet).
                   14557: 
1.29      crook    14558: @item @i{name} not defined via @code{CREATE}:
                   14559: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1       anton    14560: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   14561: the execution semantics of the last defined word no matter how it was
                   14562: defined.
                   14563: 
                   14564: @item @code{POSTPONE} applied to @code{[IF]}:
                   14565: @cindex @code{POSTPONE} applied to @code{[IF]}
                   14566: @cindex @code{[IF]} and @code{POSTPONE}
                   14567: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   14568: equivalent to @code{[IF]}.
                   14569: 
                   14570: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   14571: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   14572: Continue in the same state of conditional compilation in the next outer
                   14573: input source. Currently there is no warning to the user about this.
                   14574: 
                   14575: @item removing a needed definition (@code{FORGET}):
                   14576: @cindex @code{FORGET}, removing a needed definition
                   14577: Not implemented (yet).
                   14578: 
                   14579: @end table
                   14580: 
                   14581: 
                   14582: @c =====================================================================
                   14583: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   14584: @section The optional Search-Order word set
                   14585: @c =====================================================================
                   14586: @cindex system documentation, search-order words
                   14587: @cindex search-order words, system documentation
                   14588: 
                   14589: @menu
                   14590: * search-idef::                 Implementation Defined Options                 
                   14591: * search-ambcond::              Ambiguous Conditions              
                   14592: @end menu
                   14593: 
                   14594: 
                   14595: @c ---------------------------------------------------------------------
                   14596: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   14597: @subsection Implementation Defined Options
                   14598: @c ---------------------------------------------------------------------
                   14599: @cindex implementation-defined options, search-order words
                   14600: @cindex search-order words, implementation-defined options
                   14601: 
                   14602: @table @i
                   14603: @item maximum number of word lists in search order:
                   14604: @cindex maximum number of word lists in search order
                   14605: @cindex search order, maximum depth
                   14606: @code{s" wordlists" environment? drop .}. Currently 16.
                   14607: 
                   14608: @item minimum search order:
                   14609: @cindex minimum search order
                   14610: @cindex search order, minimum
                   14611: @code{root root}.
                   14612: 
                   14613: @end table
                   14614: 
                   14615: @c ---------------------------------------------------------------------
                   14616: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   14617: @subsection Ambiguous conditions
                   14618: @c ---------------------------------------------------------------------
                   14619: @cindex search-order words, ambiguous conditions
                   14620: @cindex ambiguous conditions, search-order words
                   14621: 
                   14622: @table @i
1.21      crook    14623: @item changing the compilation word list (during compilation):
                   14624: @cindex changing the compilation word list (during compilation)
                   14625: @cindex compilation word list, change before definition ends
                   14626: The word is entered into the word list that was the compilation word list
1.1       anton    14627: at the start of the definition. Any changes to the name field (e.g.,
                   14628: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116     anton    14629: are applied to the latest defined word (as reported by @code{latest} or
                   14630: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1       anton    14631: 
                   14632: @item search order empty (@code{previous}):
                   14633: @cindex @code{previous}, search order empty
1.26      crook    14634: @cindex vocstack empty, @code{previous}
1.1       anton    14635: @code{abort" Vocstack empty"}.
                   14636: 
                   14637: @item too many word lists in search order (@code{also}):
                   14638: @cindex @code{also}, too many word lists in search order
1.26      crook    14639: @cindex vocstack full, @code{also}
1.1       anton    14640: @code{abort" Vocstack full"}.
                   14641: 
                   14642: @end table
                   14643: 
                   14644: @c ***************************************************************
1.65      anton    14645: @node Standard vs Extensions, Model, ANS conformance, Top
                   14646: @chapter Should I use Gforth extensions?
                   14647: @cindex Gforth extensions
                   14648: 
                   14649: As you read through the rest of this manual, you will see documentation
                   14650: for @i{Standard} words, and documentation for some appealing Gforth
                   14651: @i{extensions}. You might ask yourself the question: @i{``Should I
                   14652: restrict myself to the standard, or should I use the extensions?''}
                   14653: 
                   14654: The answer depends on the goals you have for the program you are working
                   14655: on:
                   14656: 
                   14657: @itemize @bullet
                   14658: 
                   14659: @item Is it just for yourself or do you want to share it with others?
                   14660: 
                   14661: @item
                   14662: If you want to share it, do the others all use Gforth?
                   14663: 
                   14664: @item
                   14665: If it is just for yourself, do you want to restrict yourself to Gforth?
                   14666: 
                   14667: @end itemize
                   14668: 
                   14669: If restricting the program to Gforth is ok, then there is no reason not
                   14670: to use extensions.  It is still a good idea to keep to the standard
                   14671: where it is easy, in case you want to reuse these parts in another
                   14672: program that you want to be portable.
                   14673: 
                   14674: If you want to be able to port the program to other Forth systems, there
                   14675: are the following points to consider:
                   14676: 
                   14677: @itemize @bullet
                   14678: 
                   14679: @item
                   14680: Most Forth systems that are being maintained support the ANS Forth
                   14681: standard.  So if your program complies with the standard, it will be
                   14682: portable among many systems.
                   14683: 
                   14684: @item
                   14685: A number of the Gforth extensions can be implemented in ANS Forth using
                   14686: public-domain files provided in the @file{compat/} directory. These are
                   14687: mentioned in the text in passing.  There is no reason not to use these
                   14688: extensions, your program will still be ANS Forth compliant; just include
                   14689: the appropriate compat files with your program.
                   14690: 
                   14691: @item
                   14692: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
                   14693: analyse your program and determine what non-Standard words it relies
                   14694: upon.  However, it does not check whether you use standard words in a
                   14695: non-standard way.
                   14696: 
                   14697: @item
                   14698: Some techniques are not standardized by ANS Forth, and are hard or
                   14699: impossible to implement in a standard way, but can be implemented in
                   14700: most Forth systems easily, and usually in similar ways (e.g., accessing
                   14701: word headers).  Forth has a rich historical precedent for programmers
                   14702: taking advantage of implementation-dependent features of their tools
                   14703: (for example, relying on a knowledge of the dictionary
                   14704: structure). Sometimes these techniques are necessary to extract every
                   14705: last bit of performance from the hardware, sometimes they are just a
                   14706: programming shorthand.
                   14707: 
                   14708: @item
                   14709: Does using a Gforth extension save more work than the porting this part
                   14710: to other Forth systems (if any) will cost?
                   14711: 
                   14712: @item
                   14713: Is the additional functionality worth the reduction in portability and
                   14714: the additional porting problems?
                   14715: 
                   14716: @end itemize
                   14717: 
                   14718: In order to perform these consideratios, you need to know what's
                   14719: standard and what's not.  This manual generally states if something is
1.81      anton    14720: non-standard, but the authoritative source is the
                   14721: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65      anton    14722: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
                   14723: into the thought processes of the technical committee.
                   14724: 
                   14725: Note also that portability between Forth systems is not the only
                   14726: portability issue; there is also the issue of portability between
                   14727: different platforms (processor/OS combinations).
                   14728: 
                   14729: @c ***************************************************************
                   14730: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1       anton    14731: @chapter Model
                   14732: 
                   14733: This chapter has yet to be written. It will contain information, on
                   14734: which internal structures you can rely.
                   14735: 
                   14736: @c ***************************************************************
                   14737: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   14738: @chapter Integrating Gforth into C programs
                   14739: 
                   14740: This is not yet implemented.
                   14741: 
                   14742: Several people like to use Forth as scripting language for applications
                   14743: that are otherwise written in C, C++, or some other language.
                   14744: 
                   14745: The Forth system ATLAST provides facilities for embedding it into
                   14746: applications; unfortunately it has several disadvantages: most
                   14747: importantly, it is not based on ANS Forth, and it is apparently dead
                   14748: (i.e., not developed further and not supported). The facilities
1.21      crook    14749: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1       anton    14750: making the switch should not be hard.
                   14751: 
                   14752: We also tried to design the interface such that it can easily be
                   14753: implemented by other Forth systems, so that we may one day arrive at a
                   14754: standardized interface. Such a standard interface would allow you to
                   14755: replace the Forth system without having to rewrite C code.
                   14756: 
                   14757: You embed the Gforth interpreter by linking with the library
                   14758: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   14759: global symbols in this library that belong to the interface, have the
                   14760: prefix @code{forth_}. (Global symbols that are used internally have the
                   14761: prefix @code{gforth_}).
                   14762: 
                   14763: You can include the declarations of Forth types and the functions and
                   14764: variables of the interface with @code{#include <forth.h>}.
                   14765: 
                   14766: Types.
                   14767: 
                   14768: Variables.
                   14769: 
                   14770: Data and FP Stack pointer. Area sizes.
                   14771: 
                   14772: functions.
                   14773: 
                   14774: forth_init(imagefile)
                   14775: forth_evaluate(string) exceptions?
                   14776: forth_goto(address) (or forth_execute(xt)?)
                   14777: forth_continue() (a corountining mechanism)
                   14778: 
                   14779: Adding primitives.
                   14780: 
                   14781: No checking.
                   14782: 
                   14783: Signals?
                   14784: 
                   14785: Accessing the Stacks
                   14786: 
1.26      crook    14787: @c ******************************************************************
1.1       anton    14788: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   14789: @chapter Emacs and Gforth
                   14790: @cindex Emacs and Gforth
                   14791: 
                   14792: @cindex @file{gforth.el}
                   14793: @cindex @file{forth.el}
                   14794: @cindex Rydqvist, Goran
1.107     dvdkhlng 14795: @cindex Kuehling, David
1.1       anton    14796: @cindex comment editing commands
                   14797: @cindex @code{\}, editing with Emacs
                   14798: @cindex debug tracer editing commands
                   14799: @cindex @code{~~}, removal with Emacs
                   14800: @cindex Forth mode in Emacs
1.107     dvdkhlng 14801: 
1.1       anton    14802: Gforth comes with @file{gforth.el}, an improved version of
                   14803: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26      crook    14804: improvements are:
                   14805: 
                   14806: @itemize @bullet
                   14807: @item
1.107     dvdkhlng 14808: A better handling of indentation.
                   14809: @item
                   14810: A custom hilighting engine for Forth-code.
1.26      crook    14811: @item
                   14812: Comment paragraph filling (@kbd{M-q})
                   14813: @item
                   14814: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
                   14815: @item
                   14816: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41      anton    14817: @item
                   14818: Support of the @code{info-lookup} feature for looking up the
                   14819: documentation of a word.
1.107     dvdkhlng 14820: @item
                   14821: Support for reading and writing blocks files.
1.26      crook    14822: @end itemize
                   14823: 
1.107     dvdkhlng 14824: To get a basic description of these features, enter Forth mode and
                   14825: type @kbd{C-h m}.
1.1       anton    14826: 
                   14827: @cindex source location of error or debugging output in Emacs
                   14828: @cindex error output, finding the source location in Emacs
                   14829: @cindex debugging output, finding the source location in Emacs
                   14830: In addition, Gforth supports Emacs quite well: The source code locations
                   14831: given in error messages, debugging output (from @code{~~}) and failed
                   14832: assertion messages are in the right format for Emacs' compilation mode
                   14833: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   14834: Manual}) so the source location corresponding to an error or other
                   14835: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   14836: @kbd{C-c C-c} for the error under the cursor).
                   14837: 
1.107     dvdkhlng 14838: @cindex viewing the documentation of a word in Emacs
                   14839: @cindex context-sensitive help
                   14840: Moreover, for words documented in this manual, you can look up the
                   14841: glossary entry quickly by using @kbd{C-h TAB}
                   14842: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
                   14843: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
                   14844: later and does not work for words containing @code{:}.
                   14845: 
                   14846: @menu
                   14847: * Installing gforth.el::        Making Emacs aware of Forth.
                   14848: * Emacs Tags::                  Viewing the source of a word in Emacs.
                   14849: * Hilighting::                  Making Forth code look prettier.
                   14850: * Auto-Indentation::            Customizing auto-indentation.
                   14851: * Blocks Files::                Reading and writing blocks files.
                   14852: @end menu
                   14853: 
                   14854: @c ----------------------------------
1.109     anton    14855: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107     dvdkhlng 14856: @section Installing gforth.el
                   14857: @cindex @file{.emacs}
                   14858: @cindex @file{gforth.el}, installation
                   14859: To make the features from @file{gforth.el} available in Emacs, add
                   14860: the following lines to your @file{.emacs} file:
                   14861: 
                   14862: @example
                   14863: (autoload 'forth-mode "gforth.el")
                   14864: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) 
                   14865:                            auto-mode-alist))
                   14866: (autoload 'forth-block-mode "gforth.el")
                   14867: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode) 
                   14868:                            auto-mode-alist))
                   14869: (add-hook 'forth-mode-hook (function (lambda ()
                   14870:    ;; customize variables here:
                   14871:    (setq forth-indent-level 4)
                   14872:    (setq forth-minor-indent-level 2)
                   14873:    (setq forth-hilight-level 3)
                   14874:    ;;; ...
                   14875: )))
                   14876: @end example
                   14877: 
                   14878: @c ----------------------------------
                   14879: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
                   14880: @section Emacs Tags
1.1       anton    14881: @cindex @file{TAGS} file
                   14882: @cindex @file{etags.fs}
                   14883: @cindex viewing the source of a word in Emacs
1.43      anton    14884: @cindex @code{require}, placement in files
                   14885: @cindex @code{include}, placement in files
1.107     dvdkhlng 14886: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
                   14887: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1       anton    14888: contains the definitions of all words defined afterwards. You can then
1.107     dvdkhlng 14889: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1       anton    14890: several tags files at the same time (e.g., one for the Gforth sources
                   14891: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   14892: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   14893: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43      anton    14894: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
                   14895: with @file{etags.fs}, you should avoid putting definitions both before
                   14896: and after @code{require} etc., otherwise you will see the same file
                   14897: visited several times by commands like @code{tags-search}.
1.1       anton    14898: 
1.107     dvdkhlng 14899: @c ----------------------------------
                   14900: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
                   14901: @section Hilighting
                   14902: @cindex hilighting Forth code in Emacs
                   14903: @cindex highlighting Forth code in Emacs
                   14904: @file{gforth.el} comes with a custom source hilighting engine.  When
                   14905: you open a file in @code{forth-mode}, it will be completely parsed,
                   14906: assigning faces to keywords, comments, strings etc.  While you edit
                   14907: the file, modified regions get parsed and updated on-the-fly. 
                   14908: 
                   14909: Use the variable `forth-hilight-level' to change the level of
                   14910: decoration from 0 (no hilighting at all) to 3 (the default).  Even if
                   14911: you set the hilighting level to 0, the parser will still work in the
                   14912: background, collecting information about whether regions of text are
                   14913: ``compiled'' or ``interpreted''.  Those information are required for
                   14914: auto-indentation to work properly.  Set `forth-disable-parser' to
                   14915: non-nil if your computer is too slow to handle parsing.  This will
                   14916: have an impact on the smartness of the auto-indentation engine,
                   14917: though.
                   14918: 
                   14919: Sometimes Forth sources define new features that should be hilighted,
                   14920: new control structures, defining-words etc.  You can use the variable
                   14921: `forth-custom-words' to make @code{forth-mode} hilight additional
                   14922: words and constructs.  See the docstring of `forth-words' for details
                   14923: (in Emacs, type @kbd{C-h v forth-words}).
                   14924: 
                   14925: `forth-custom-words' is meant to be customized in your
                   14926: @file{.emacs} file.  To customize hilighing in a file-specific manner,
                   14927: set `forth-local-words' in a local-variables section at the end of
                   14928: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
                   14929: 
                   14930: Example:
                   14931: @example
                   14932: 0 [IF]
                   14933:    Local Variables:
                   14934:    forth-local-words:
                   14935:       ((("t:") definition-starter (font-lock-keyword-face . 1)
                   14936:         "[ \t\n]" t name (font-lock-function-name-face . 3))
                   14937:        ((";t") definition-ender (font-lock-keyword-face . 1)))
                   14938:    End:
                   14939: [THEN]
                   14940: @end example
                   14941: 
                   14942: @c ----------------------------------
                   14943: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
                   14944: @section Auto-Indentation
                   14945: @cindex auto-indentation of Forth code in Emacs
                   14946: @cindex indentation of Forth code in Emacs
                   14947: @code{forth-mode} automatically tries to indent lines in a smart way,
                   14948: whenever you type @key{TAB} or break a line with @kbd{C-m}.
                   14949: 
                   14950: Simple customization can be achieved by setting
                   14951: `forth-indent-level' and `forth-minor-indent-level' in your
                   14952: @file{.emacs} file. For historical reasons @file{gforth.el} indents
                   14953: per default by multiples of 4 columns.  To use the more traditional
                   14954: 3-column indentation, add the following lines to your @file{.emacs}:
                   14955: 
                   14956: @example
                   14957: (add-hook 'forth-mode-hook (function (lambda ()
                   14958:    ;; customize variables here:
                   14959:    (setq forth-indent-level 3)
                   14960:    (setq forth-minor-indent-level 1)
                   14961: )))
                   14962: @end example
                   14963: 
                   14964: If you want indentation to recognize non-default words, customize it
                   14965: by setting `forth-custom-indent-words' in your @file{.emacs}.  See the
                   14966: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
                   14967: v forth-indent-words}).
                   14968: 
                   14969: To customize indentation in a file-specific manner, set
                   14970: `forth-local-indent-words' in a local-variables section at the end of
                   14971: your source file (@pxref{Local Variables in Files, Variables,,emacs,
                   14972: Emacs Manual}).
                   14973: 
                   14974: Example:
                   14975: @example
                   14976: 0 [IF]
                   14977:    Local Variables:
                   14978:    forth-local-indent-words:
                   14979:       ((("t:") (0 . 2) (0 . 2))
                   14980:        ((";t") (-2 . 0) (0 . -2)))
                   14981:    End:
                   14982: [THEN]
                   14983: @end example
                   14984: 
                   14985: @c ----------------------------------
1.109     anton    14986: @node Blocks Files,  , Auto-Indentation, Emacs and Gforth
1.107     dvdkhlng 14987: @section Blocks Files
                   14988: @cindex blocks files, use with Emacs
                   14989: @code{forth-mode} Autodetects blocks files by checking whether the
                   14990: length of the first line exceeds 1023 characters.  It then tries to
                   14991: convert the file into normal text format.  When you save the file, it
                   14992: will be written to disk as normal stream-source file.
                   14993: 
                   14994: If you want to write blocks files, use @code{forth-blocks-mode}.  It
                   14995: inherits all the features from @code{forth-mode}, plus some additions:
1.41      anton    14996: 
1.107     dvdkhlng 14997: @itemize @bullet
                   14998: @item
                   14999: Files are written to disk in blocks file format.
                   15000: @item
                   15001: Screen numbers are displayed in the mode line (enumerated beginning
                   15002: with the value of `forth-block-base')
                   15003: @item
                   15004: Warnings are displayed when lines exceed 64 characters.
                   15005: @item
                   15006: The beginning of the currently edited block is marked with an
                   15007: overlay-arrow. 
                   15008: @end itemize
1.41      anton    15009: 
1.107     dvdkhlng 15010: There are some restrictions you should be aware of.  When you open a
                   15011: blocks file that contains tabulator or newline characters, these
                   15012: characters will be translated into spaces when the file is written
                   15013: back to disk.  If tabs or newlines are encountered during blocks file
                   15014: reading, an error is output to the echo area. So have a look at the
                   15015: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1       anton    15016: 
1.107     dvdkhlng 15017: Please consult the docstring of @code{forth-blocks-mode} for more
                   15018: information by typing @kbd{C-h v forth-blocks-mode}).
1.1       anton    15019: 
1.26      crook    15020: @c ******************************************************************
1.1       anton    15021: @node Image Files, Engine, Emacs and Gforth, Top
                   15022: @chapter Image Files
1.26      crook    15023: @cindex image file
                   15024: @cindex @file{.fi} files
1.1       anton    15025: @cindex precompiled Forth code
                   15026: @cindex dictionary in persistent form
                   15027: @cindex persistent form of dictionary
                   15028: 
                   15029: An image file is a file containing an image of the Forth dictionary,
                   15030: i.e., compiled Forth code and data residing in the dictionary.  By
                   15031: convention, we use the extension @code{.fi} for image files.
                   15032: 
                   15033: @menu
1.18      anton    15034: * Image Licensing Issues::      Distribution terms for images.
                   15035: * Image File Background::       Why have image files?
1.67      anton    15036: * Non-Relocatable Image Files::  don't always work.
1.18      anton    15037: * Data-Relocatable Image Files::  are better.
1.67      anton    15038: * Fully Relocatable Image Files::  better yet.
1.18      anton    15039: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.29      crook    15040: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.18      anton    15041: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    15042: @end menu
                   15043: 
1.18      anton    15044: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   15045: @section Image Licensing Issues
                   15046: @cindex license for images
                   15047: @cindex image license
                   15048: 
                   15049: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   15050: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   15051: original image; i.e., according to copyright law it is a derived work of
                   15052: the original image.
                   15053: 
                   15054: Since Gforth is distributed under the GNU GPL, the newly created image
                   15055: falls under the GNU GPL, too. In particular, this means that if you
                   15056: distribute the image, you have to make all of the sources for the image
1.113     anton    15057: available, including those you wrote.  For details see @ref{Copying, ,
1.18      anton    15058: GNU General Public License (Section 3)}.
                   15059: 
                   15060: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   15061: contains only code compiled from the sources you gave it; if none of
                   15062: these sources is under the GPL, the terms discussed above do not apply
                   15063: to the image. However, if your image needs an engine (a gforth binary)
                   15064: that is under the GPL, you should make sure that you distribute both in
                   15065: a way that is at most a @emph{mere aggregation}, if you don't want the
                   15066: terms of the GPL to apply to the image.
                   15067: 
                   15068: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    15069: @section Image File Background
                   15070: @cindex image file background
                   15071: 
1.80      anton    15072: Gforth consists not only of primitives (in the engine), but also of
1.1       anton    15073: definitions written in Forth. Since the Forth compiler itself belongs to
                   15074: those definitions, it is not possible to start the system with the
1.80      anton    15075: engine and the Forth source alone. Therefore we provide the Forth
1.26      crook    15076: code as an image file in nearly executable form. When Gforth starts up,
                   15077: a C routine loads the image file into memory, optionally relocates the
                   15078: addresses, then sets up the memory (stacks etc.) according to
                   15079: information in the image file, and (finally) starts executing Forth
                   15080: code.
1.1       anton    15081: 
                   15082: The image file variants represent different compromises between the
                   15083: goals of making it easy to generate image files and making them
                   15084: portable.
                   15085: 
                   15086: @cindex relocation at run-time
1.26      crook    15087: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1       anton    15088: run-time. This avoids many of the complications discussed below (image
                   15089: files are data relocatable without further ado), but costs performance
                   15090: (one addition per memory access).
                   15091: 
                   15092: @cindex relocation at load-time
1.26      crook    15093: By contrast, the Gforth loader performs relocation at image load time. The
                   15094: loader also has to replace tokens that represent primitive calls with the
1.1       anton    15095: appropriate code-field addresses (or code addresses in the case of
                   15096: direct threading).
                   15097: 
                   15098: There are three kinds of image files, with different degrees of
                   15099: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   15100: image files.
                   15101: 
                   15102: @cindex image file loader
                   15103: @cindex relocating loader
                   15104: @cindex loader for image files
                   15105: These image file variants have several restrictions in common; they are
                   15106: caused by the design of the image file loader:
                   15107: 
                   15108: @itemize @bullet
                   15109: @item
                   15110: There is only one segment; in particular, this means, that an image file
                   15111: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26      crook    15112: them). The contents of the stacks are not represented, either.
1.1       anton    15113: 
                   15114: @item
                   15115: The only kinds of relocation supported are: adding the same offset to
                   15116: all cells that represent data addresses; and replacing special tokens
                   15117: with code addresses or with pieces of machine code.
                   15118: 
                   15119: If any complex computations involving addresses are performed, the
                   15120: results cannot be represented in the image file. Several applications that
                   15121: use such computations come to mind:
                   15122: @itemize @minus
                   15123: @item
                   15124: Hashing addresses (or data structures which contain addresses) for table
                   15125: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   15126: purpose, you will have no problem, because the hash tables are
                   15127: recomputed automatically when the system is started. If you use your own
                   15128: hash tables, you will have to do something similar.
                   15129: 
                   15130: @item
                   15131: There's a cute implementation of doubly-linked lists that uses
                   15132: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   15133: in the image file, and restore the doubly-linked representation on
                   15134: startup.@footnote{In my opinion, though, you should think thrice before
                   15135: using a doubly-linked list (whatever implementation).}
                   15136: 
                   15137: @item
                   15138: The code addresses of run-time routines like @code{docol:} cannot be
                   15139: represented in the image file (because their tokens would be replaced by
                   15140: machine code in direct threaded implementations). As a workaround,
                   15141: compute these addresses at run-time with @code{>code-address} from the
                   15142: executions tokens of appropriate words (see the definitions of
1.80      anton    15143: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1       anton    15144: 
                   15145: @item
                   15146: On many architectures addresses are represented in machine code in some
                   15147: shifted or mangled form. You cannot put @code{CODE} words that contain
                   15148: absolute addresses in this form in a relocatable image file. Workarounds
                   15149: are representing the address in some relative form (e.g., relative to
                   15150: the CFA, which is present in some register), or loading the address from
                   15151: a place where it is stored in a non-mangled form.
                   15152: @end itemize
                   15153: @end itemize
                   15154: 
                   15155: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   15156: @section Non-Relocatable Image Files
                   15157: @cindex non-relocatable image files
1.26      crook    15158: @cindex image file, non-relocatable
1.1       anton    15159: 
                   15160: These files are simple memory dumps of the dictionary. They are specific
                   15161: to the executable (i.e., @file{gforth} file) they were created
                   15162: with. What's worse, they are specific to the place on which the
                   15163: dictionary resided when the image was created. Now, there is no
                   15164: guarantee that the dictionary will reside at the same place the next
                   15165: time you start Gforth, so there's no guarantee that a non-relocatable
                   15166: image will work the next time (Gforth will complain instead of crashing,
                   15167: though).
                   15168: 
                   15169: You can create a non-relocatable image file with
                   15170: 
1.44      crook    15171: 
1.1       anton    15172: doc-savesystem
                   15173: 
1.44      crook    15174: 
1.1       anton    15175: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   15176: @section Data-Relocatable Image Files
                   15177: @cindex data-relocatable image files
1.26      crook    15178: @cindex image file, data-relocatable
1.1       anton    15179: 
                   15180: These files contain relocatable data addresses, but fixed code addresses
                   15181: (instead of tokens). They are specific to the executable (i.e.,
                   15182: @file{gforth} file) they were created with. For direct threading on some
                   15183: architectures (e.g., the i386), data-relocatable images do not work. You
                   15184: get a data-relocatable image, if you use @file{gforthmi} with a
                   15185: Gforth binary that is not doubly indirect threaded (@pxref{Fully
                   15186: Relocatable Image Files}).
                   15187: 
                   15188: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   15189: @section Fully Relocatable Image Files
                   15190: @cindex fully relocatable image files
1.26      crook    15191: @cindex image file, fully relocatable
1.1       anton    15192: 
                   15193: @cindex @file{kern*.fi}, relocatability
                   15194: @cindex @file{gforth.fi}, relocatability
                   15195: These image files have relocatable data addresses, and tokens for code
                   15196: addresses. They can be used with different binaries (e.g., with and
                   15197: without debugging) on the same machine, and even across machines with
                   15198: the same data formats (byte order, cell size, floating point
                   15199: format). However, they are usually specific to the version of Gforth
                   15200: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
                   15201: are fully relocatable.
                   15202: 
                   15203: There are two ways to create a fully relocatable image file:
                   15204: 
                   15205: @menu
1.29      crook    15206: * gforthmi::                    The normal way
1.1       anton    15207: * cross.fs::                    The hard way
                   15208: @end menu
                   15209: 
                   15210: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   15211: @subsection @file{gforthmi}
                   15212: @cindex @file{comp-i.fs}
                   15213: @cindex @file{gforthmi}
                   15214: 
                   15215: You will usually use @file{gforthmi}. If you want to create an
1.29      crook    15216: image @i{file} that contains everything you would load by invoking
                   15217: Gforth with @code{gforth @i{options}}, you simply say:
1.1       anton    15218: @example
1.29      crook    15219: gforthmi @i{file} @i{options}
1.1       anton    15220: @end example
                   15221: 
                   15222: E.g., if you want to create an image @file{asm.fi} that has the file
                   15223: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   15224: like this:
                   15225: 
                   15226: @example
                   15227: gforthmi asm.fi asm.fs
                   15228: @end example
                   15229: 
1.27      crook    15230: @file{gforthmi} is implemented as a sh script and works like this: It
                   15231: produces two non-relocatable images for different addresses and then
                   15232: compares them. Its output reflects this: first you see the output (if
1.62      crook    15233: any) of the two Gforth invocations that produce the non-relocatable image
1.27      crook    15234: files, then you see the output of the comparing program: It displays the
                   15235: offset used for data addresses and the offset used for code addresses;
1.1       anton    15236: moreover, for each cell that cannot be represented correctly in the
1.44      crook    15237: image files, it displays a line like this:
1.1       anton    15238: 
                   15239: @example
                   15240:      78DC         BFFFFA50         BFFFFA40
                   15241: @end example
                   15242: 
                   15243: This means that at offset $78dc from @code{forthstart}, one input image
                   15244: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   15245: cannot be represented correctly in the output image, you should examine
                   15246: these places in the dictionary and verify that these cells are dead
                   15247: (i.e., not read before they are written).
1.39      anton    15248: 
                   15249: @cindex --application, @code{gforthmi} option
                   15250: If you insert the option @code{--application} in front of the image file
                   15251: name, you will get an image that uses the @code{--appl-image} option
                   15252: instead of the @code{--image-file} option (@pxref{Invoking
                   15253: Gforth}). When you execute such an image on Unix (by typing the image
                   15254: name as command), the Gforth engine will pass all options to the image
                   15255: instead of trying to interpret them as engine options.
1.1       anton    15256: 
1.27      crook    15257: If you type @file{gforthmi} with no arguments, it prints some usage
                   15258: instructions.
                   15259: 
1.1       anton    15260: @cindex @code{savesystem} during @file{gforthmi}
                   15261: @cindex @code{bye} during @file{gforthmi}
                   15262: @cindex doubly indirect threaded code
1.44      crook    15263: @cindex environment variables
                   15264: @cindex @code{GFORTHD} -- environment variable
                   15265: @cindex @code{GFORTH} -- environment variable
1.1       anton    15266: @cindex @code{gforth-ditc}
1.29      crook    15267: There are a few wrinkles: After processing the passed @i{options}, the
1.1       anton    15268: words @code{savesystem} and @code{bye} must be visible. A special doubly
                   15269: indirect threaded version of the @file{gforth} executable is used for
1.62      crook    15270: creating the non-relocatable images; you can pass the exact filename of
1.1       anton    15271: this executable through the environment variable @code{GFORTHD}
                   15272: (default: @file{gforth-ditc}); if you pass a version that is not doubly
                   15273: indirect threaded, you will not get a fully relocatable image, but a
1.27      crook    15274: data-relocatable image (because there is no code address offset). The
                   15275: normal @file{gforth} executable is used for creating the relocatable
                   15276: image; you can pass the exact filename of this executable through the
                   15277: environment variable @code{GFORTH}.
1.1       anton    15278: 
                   15279: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   15280: @subsection @file{cross.fs}
                   15281: @cindex @file{cross.fs}
                   15282: @cindex cross-compiler
                   15283: @cindex metacompiler
1.47      crook    15284: @cindex target compiler
1.1       anton    15285: 
                   15286: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47      crook    15287: programming language (@pxref{Cross Compiler}).
1.1       anton    15288: 
1.47      crook    15289: @code{cross} allows you to create image files for machines with
1.1       anton    15290: different data sizes and data formats than the one used for generating
                   15291: the image file. You can also use it to create an application image that
                   15292: does not contain a Forth compiler. These features are bought with
                   15293: restrictions and inconveniences in programming. E.g., addresses have to
                   15294: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   15295: order to make the code relocatable.
                   15296: 
                   15297: 
                   15298: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   15299: @section Stack and Dictionary Sizes
                   15300: @cindex image file, stack and dictionary sizes
                   15301: @cindex dictionary size default
                   15302: @cindex stack size default
                   15303: 
                   15304: If you invoke Gforth with a command line flag for the size
                   15305: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   15306: dictionary. If you save the dictionary with @code{savesystem} or create
                   15307: an image with @file{gforthmi}, this size will become the default
                   15308: for the resulting image file. E.g., the following will create a
1.21      crook    15309: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1       anton    15310: 
                   15311: @example
                   15312: gforthmi gforth.fi -m 1M
                   15313: @end example
                   15314: 
                   15315: In other words, if you want to set the default size for the dictionary
                   15316: and the stacks of an image, just invoke @file{gforthmi} with the
                   15317: appropriate options when creating the image.
                   15318: 
                   15319: @cindex stack size, cache-friendly
                   15320: Note: For cache-friendly behaviour (i.e., good performance), you should
                   15321: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   15322: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   15323: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   15324: 
                   15325: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   15326: @section Running Image Files
                   15327: @cindex running image files
                   15328: @cindex invoking image files
                   15329: @cindex image file invocation
                   15330: 
                   15331: @cindex -i, invoke image file
                   15332: @cindex --image file, invoke image file
1.29      crook    15333: You can invoke Gforth with an image file @i{image} instead of the
1.1       anton    15334: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   15335: @example
1.29      crook    15336: gforth -i @i{image}
1.1       anton    15337: @end example
                   15338: 
                   15339: @cindex executable image file
1.26      crook    15340: @cindex image file, executable
1.1       anton    15341: If your operating system supports starting scripts with a line of the
                   15342: form @code{#! ...}, you just have to type the image file name to start
                   15343: Gforth with this image file (note that the file extension @code{.fi} is
1.29      crook    15344: just a convention). I.e., to run Gforth with the image file @i{image},
                   15345: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27      crook    15346: This works because every @code{.fi} file starts with a line of this
                   15347: format:
                   15348: 
                   15349: @example
                   15350: #! /usr/local/bin/gforth-0.4.0 -i
                   15351: @end example
                   15352: 
                   15353: The file and pathname for the Gforth engine specified on this line is
                   15354: the specific Gforth executable that it was built against; i.e. the value
                   15355: of the environment variable @code{GFORTH} at the time that
                   15356: @file{gforthmi} was executed.
1.1       anton    15357: 
1.27      crook    15358: You can make use of the same shell capability to make a Forth source
                   15359: file into an executable. For example, if you place this text in a file:
1.26      crook    15360: 
                   15361: @example
                   15362: #! /usr/local/bin/gforth
                   15363: 
                   15364: ." Hello, world" CR
                   15365: bye
                   15366: @end example
                   15367: 
                   15368: @noindent
1.27      crook    15369: and then make the file executable (chmod +x in Unix), you can run it
1.26      crook    15370: directly from the command line. The sequence @code{#!} is used in two
                   15371: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29      crook    15372: system@footnote{The Unix kernel actually recognises two types of files:
                   15373: executable files and files of data, where the data is processed by an
                   15374: interpreter that is specified on the ``interpreter line'' -- the first
                   15375: line of the file, starting with the sequence #!. There may be a small
                   15376: limit (e.g., 32) on the number of characters that may be specified on
                   15377: the interpreter line.} secondly it is treated as a comment character by
                   15378: Gforth. Because of the second usage, a space is required between
1.80      anton    15379: @code{#!} and the path to the executable (moreover, some Unixes
                   15380: require the sequence @code{#! /}).
1.27      crook    15381: 
                   15382: The disadvantage of this latter technique, compared with using
1.80      anton    15383: @file{gforthmi}, is that it is slightly slower; the Forth source code is
                   15384: compiled on-the-fly, each time the program is invoked.
1.26      crook    15385: 
1.1       anton    15386: doc-#!
                   15387: 
1.44      crook    15388: 
1.1       anton    15389: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   15390: @section Modifying the Startup Sequence
                   15391: @cindex startup sequence for image file
                   15392: @cindex image file initialization sequence
                   15393: @cindex initialization sequence of image file
                   15394: 
1.120     anton    15395: You can add your own initialization to the startup sequence of an image
                   15396: through the deferred word @code{'cold}. @code{'cold} is invoked just
                   15397: before the image-specific command line processing (i.e., loading files
                   15398: and evaluating (@code{-e}) strings) starts.
1.1       anton    15399: 
                   15400: A sequence for adding your initialization usually looks like this:
                   15401: 
                   15402: @example
                   15403: :noname
                   15404:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   15405:     ... \ your stuff
                   15406: ; IS 'cold
                   15407: @end example
                   15408: 
1.157     anton    15409: After @code{'cold}, Gforth processes the image options
                   15410: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
                   15411: another deferred word.  This normally prints Gforth's startup message
                   15412: and does nothing else.
                   15413: 
1.1       anton    15414: @cindex turnkey image files
1.26      crook    15415: @cindex image file, turnkey applications
1.157     anton    15416: So, if you want to make a turnkey image (i.e., an image for an
                   15417: application instead of an extended Forth system), you can do this in
                   15418: two ways:
                   15419: 
                   15420: @itemize @bullet
                   15421: 
                   15422: @item
                   15423: If you want to do your interpretation of the OS command-line
                   15424: arguments, hook into @code{'cold}.  In that case you probably also
                   15425: want to build the image with @code{gforthmi --application}
                   15426: (@pxref{gforthmi}) to keep the engine from processing OS command line
                   15427: options.  You can then do your own command-line processing with
                   15428: @code{next-arg} 
                   15429: 
                   15430: @item
                   15431: If you want to have the normal Gforth processing of OS command-line
                   15432: arguments, hook into @code{bootmessage}.
                   15433: 
                   15434: @end itemize
                   15435: 
                   15436: In either case, you probably do not want the word that you execute in
                   15437: these hooks to exit normally, but use @code{bye} or @code{throw}.
                   15438: Otherwise the Gforth startup process would continue and eventually
                   15439: present the Forth command line to the user.
1.26      crook    15440: 
                   15441: doc-'cold
1.157     anton    15442: doc-bootmessage
1.44      crook    15443: 
1.1       anton    15444: @c ******************************************************************
1.113     anton    15445: @node Engine, Cross Compiler, Image Files, Top
1.1       anton    15446: @chapter Engine
                   15447: @cindex engine
                   15448: @cindex virtual machine
                   15449: 
1.26      crook    15450: Reading this chapter is not necessary for programming with Gforth. It
1.1       anton    15451: may be helpful for finding your way in the Gforth sources.
                   15452: 
1.109     anton    15453: The ideas in this section have also been published in the following
                   15454: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
                   15455: Forth-Tagung '93; M. Anton Ertl,
                   15456: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
                   15457: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
                   15458: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
                   15459: Threaded code variations and optimizations (extended version)}},
                   15460: Forth-Tagung '02.
1.1       anton    15461: 
                   15462: @menu
                   15463: * Portability::                 
                   15464: * Threading::                   
                   15465: * Primitives::                  
                   15466: * Performance::                 
                   15467: @end menu
                   15468: 
                   15469: @node Portability, Threading, Engine, Engine
                   15470: @section Portability
                   15471: @cindex engine portability
                   15472: 
1.26      crook    15473: An important goal of the Gforth Project is availability across a wide
                   15474: range of personal machines. fig-Forth, and, to a lesser extent, F83,
                   15475: achieved this goal by manually coding the engine in assembly language
                   15476: for several then-popular processors. This approach is very
                   15477: labor-intensive and the results are short-lived due to progress in
                   15478: computer architecture.
1.1       anton    15479: 
                   15480: @cindex C, using C for the engine
                   15481: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   15482: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   15483: particularly popular for UNIX-based Forths due to the large variety of
                   15484: architectures of UNIX machines. Unfortunately an implementation in C
                   15485: does not mix well with the goals of efficiency and with using
                   15486: traditional techniques: Indirect or direct threading cannot be expressed
                   15487: in C, and switch threading, the fastest technique available in C, is
                   15488: significantly slower. Another problem with C is that it is very
                   15489: cumbersome to express double integer arithmetic.
                   15490: 
                   15491: @cindex GNU C for the engine
                   15492: @cindex long long
                   15493: Fortunately, there is a portable language that does not have these
                   15494: limitations: GNU C, the version of C processed by the GNU C compiler
                   15495: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   15496: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   15497: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   15498: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   15499: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109     anton    15500: double numbers on many systems.  GNU C is freely available on all
1.1       anton    15501: important (and many unimportant) UNIX machines, VMS, 80386s running
                   15502: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   15503: on all these machines.
                   15504: 
                   15505: Writing in a portable language has the reputation of producing code that
                   15506: is slower than assembly. For our Forth engine we repeatedly looked at
                   15507: the code produced by the compiler and eliminated most compiler-induced
                   15508: inefficiencies by appropriate changes in the source code.
                   15509: 
                   15510: @cindex explicit register declarations
                   15511: @cindex --enable-force-reg, configuration flag
                   15512: @cindex -DFORCE_REG
                   15513: However, register allocation cannot be portably influenced by the
                   15514: programmer, leading to some inefficiencies on register-starved
                   15515: machines. We use explicit register declarations (@pxref{Explicit Reg
                   15516: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   15517: improve the speed on some machines. They are turned on by using the
                   15518: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   15519: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   15520: machine, but also on the compiler version: On some machines some
                   15521: compiler versions produce incorrect code when certain explicit register
                   15522: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   15523: 
                   15524: @node Threading, Primitives, Portability, Engine
                   15525: @section Threading
                   15526: @cindex inner interpreter implementation
                   15527: @cindex threaded code implementation
                   15528: 
                   15529: @cindex labels as values
                   15530: GNU C's labels as values extension (available since @code{gcc-2.0},
                   15531: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29      crook    15532: makes it possible to take the address of @i{label} by writing
                   15533: @code{&&@i{label}}.  This address can then be used in a statement like
                   15534: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1       anton    15535: @code{goto x}.
                   15536: 
1.26      crook    15537: @cindex @code{NEXT}, indirect threaded
1.1       anton    15538: @cindex indirect threaded inner interpreter
                   15539: @cindex inner interpreter, indirect threaded
1.26      crook    15540: With this feature an indirect threaded @code{NEXT} looks like:
1.1       anton    15541: @example
                   15542: cfa = *ip++;
                   15543: ca = *cfa;
                   15544: goto *ca;
                   15545: @end example
                   15546: @cindex instruction pointer
                   15547: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   15548: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   15549: execution token and points to the code field of the next word to be
                   15550: executed; The @code{ca} (code address) fetched from there points to some
                   15551: executable code, e.g., a primitive or the colon definition handler
                   15552: @code{docol}.
                   15553: 
1.26      crook    15554: @cindex @code{NEXT}, direct threaded
1.1       anton    15555: @cindex direct threaded inner interpreter
                   15556: @cindex inner interpreter, direct threaded
                   15557: Direct threading is even simpler:
                   15558: @example
                   15559: ca = *ip++;
                   15560: goto *ca;
                   15561: @end example
                   15562: 
                   15563: Of course we have packaged the whole thing neatly in macros called
1.26      crook    15564: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1       anton    15565: 
                   15566: @menu
                   15567: * Scheduling::                  
                   15568: * Direct or Indirect Threaded?::  
1.109     anton    15569: * Dynamic Superinstructions::   
1.1       anton    15570: * DOES>::                       
                   15571: @end menu
                   15572: 
                   15573: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   15574: @subsection Scheduling
                   15575: @cindex inner interpreter optimization
                   15576: 
                   15577: There is a little complication: Pipelined and superscalar processors,
                   15578: i.e., RISC and some modern CISC machines can process independent
                   15579: instructions while waiting for the results of an instruction. The
                   15580: compiler usually reorders (schedules) the instructions in a way that
                   15581: achieves good usage of these delay slots. However, on our first tries
                   15582: the compiler did not do well on scheduling primitives. E.g., for
                   15583: @code{+} implemented as
                   15584: @example
                   15585: n=sp[0]+sp[1];
                   15586: sp++;
                   15587: sp[0]=n;
                   15588: NEXT;
                   15589: @end example
1.81      anton    15590: the @code{NEXT} comes strictly after the other code, i.e., there is
                   15591: nearly no scheduling. After a little thought the problem becomes clear:
                   15592: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21      crook    15593: addresses (and the version of @code{gcc} we used would not know it even
                   15594: if it was possible), so it could not move the load of the cfa above the
                   15595: store to the TOS. Indeed the pointers could be the same, if code on or
                   15596: very near the top of stack were executed. In the interest of speed we
                   15597: chose to forbid this probably unused ``feature'' and helped the compiler
1.81      anton    15598: in scheduling: @code{NEXT} is divided into several parts:
                   15599: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
                   15600: like:
1.1       anton    15601: @example
1.81      anton    15602: NEXT_P0;
1.1       anton    15603: n=sp[0]+sp[1];
                   15604: sp++;
                   15605: NEXT_P1;
                   15606: sp[0]=n;
                   15607: NEXT_P2;
                   15608: @end example
                   15609: 
1.81      anton    15610: There are various schemes that distribute the different operations of
                   15611: NEXT between these parts in several ways; in general, different schemes
                   15612: perform best on different processors.  We use a scheme for most
                   15613: architectures that performs well for most processors of this
1.109     anton    15614: architecture; in the future we may switch to benchmarking and chosing
1.81      anton    15615: the scheme on installation time.
                   15616: 
1.1       anton    15617: 
1.109     anton    15618: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1       anton    15619: @subsection Direct or Indirect Threaded?
                   15620: @cindex threading, direct or indirect?
                   15621: 
1.109     anton    15622: Threaded forth code consists of references to primitives (simple machine
                   15623: code routines like @code{+}) and to non-primitives (e.g., colon
                   15624: definitions, variables, constants); for a specific class of
                   15625: non-primitives (e.g., variables) there is one code routine (e.g.,
                   15626: @code{dovar}), but each variable needs a separate reference to its data.
                   15627: 
                   15628: Traditionally Forth has been implemented as indirect threaded code,
                   15629: because this allows to use only one cell to reference a non-primitive
                   15630: (basically you point to the data, and find the code address there).
                   15631: 
                   15632: @cindex primitive-centric threaded code
                   15633: However, threaded code in Gforth (since 0.6.0) uses two cells for
                   15634: non-primitives, one for the code address, and one for the data address;
                   15635: the data pointer is an immediate argument for the virtual machine
                   15636: instruction represented by the code address.  We call this
                   15637: @emph{primitive-centric} threaded code, because all code addresses point
                   15638: to simple primitives.  E.g., for a variable, the code address is for
                   15639: @code{lit} (also used for integer literals like @code{99}).
                   15640: 
                   15641: Primitive-centric threaded code allows us to use (faster) direct
                   15642: threading as dispatch method, completely portably (direct threaded code
                   15643: in Gforth before 0.6.0 required architecture-specific code).  It also
                   15644: eliminates the performance problems related to I-cache consistency that
                   15645: 386 implementations have with direct threaded code, and allows
                   15646: additional optimizations.
                   15647: 
                   15648: @cindex hybrid direct/indirect threaded code
                   15649: There is a catch, however: the @var{xt} parameter of @code{execute} can
                   15650: occupy only one cell, so how do we pass non-primitives with their code
                   15651: @emph{and} data addresses to them?  Our answer is to use indirect
                   15652: threaded dispatch for @code{execute} and other words that use a
                   15653: single-cell xt.  So, normal threaded code in colon definitions uses
                   15654: direct threading, and @code{execute} and similar words, which dispatch
                   15655: to xts on the data stack, use indirect threaded code.  We call this
                   15656: @emph{hybrid direct/indirect} threaded code.
                   15657: 
                   15658: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
                   15659: @cindex gforth engine
                   15660: @cindex gforth-fast engine
                   15661: The engines @command{gforth} and @command{gforth-fast} use hybrid
                   15662: direct/indirect threaded code.  This means that with these engines you
                   15663: cannot use @code{,} to compile an xt.  Instead, you have to use
                   15664: @code{compile,}.
                   15665: 
                   15666: @cindex gforth-itc engine
1.115     anton    15667: If you want to compile xts with @code{,}, use @command{gforth-itc}.
                   15668: This engine uses plain old indirect threaded code.  It still compiles in
                   15669: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109     anton    15670: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115     anton    15671: ... [}).  If you want to do that, you have to use @command{gforth-itc}
1.109     anton    15672: and execute @code{' , is compile,}.  Your program can check if it is
                   15673: running on a hybrid direct/indirect threaded engine or a pure indirect
                   15674: threaded engine with @code{threading-method} (@pxref{Threading Words}).
                   15675: 
                   15676: 
                   15677: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
                   15678: @subsection Dynamic Superinstructions
                   15679: @cindex Dynamic superinstructions with replication
                   15680: @cindex Superinstructions
                   15681: @cindex Replication
                   15682: 
                   15683: The engines @command{gforth} and @command{gforth-fast} use another
                   15684: optimization: Dynamic superinstructions with replication.  As an
                   15685: example, consider the following colon definition:
                   15686: 
                   15687: @example
                   15688: : squared ( n1 -- n2 )
                   15689:   dup * ;
                   15690: @end example
                   15691: 
                   15692: Gforth compiles this into the threaded code sequence
                   15693: 
                   15694: @example
                   15695: dup
                   15696: *
                   15697: ;s
                   15698: @end example
                   15699: 
                   15700: In normal direct threaded code there is a code address occupying one
                   15701: cell for each of these primitives.  Each code address points to a
                   15702: machine code routine, and the interpreter jumps to this machine code in
                   15703: order to execute the primitive.  The routines for these three
                   15704: primitives are (in @command{gforth-fast} on the 386):
                   15705: 
                   15706: @example
                   15707: Code dup  
                   15708: ( $804B950 )  add     esi , # -4  \ $83 $C6 $FC 
                   15709: ( $804B953 )  add     ebx , # 4  \ $83 $C3 $4 
                   15710: ( $804B956 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
                   15711: ( $804B959 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   15712: end-code
                   15713: Code *  
                   15714: ( $804ACC4 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
                   15715: ( $804ACC7 )  add     esi , # 4  \ $83 $C6 $4 
                   15716: ( $804ACCA )  add     ebx , # 4  \ $83 $C3 $4 
                   15717: ( $804ACCD )  imul    ecx , eax  \ $F $AF $C8 
                   15718: ( $804ACD0 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   15719: end-code
                   15720: Code ;s  
                   15721: ( $804A693 )  mov     eax , dword ptr [edi]  \ $8B $7 
                   15722: ( $804A695 )  add     edi , # 4  \ $83 $C7 $4 
                   15723: ( $804A698 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
                   15724: ( $804A69B )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   15725: end-code
                   15726: @end example
                   15727: 
                   15728: With dynamic superinstructions and replication the compiler does not
                   15729: just lay down the threaded code, but also copies the machine code
                   15730: fragments, usually without the jump at the end.
                   15731: 
                   15732: @example
                   15733: ( $4057D27D )  add     esi , # -4  \ $83 $C6 $FC 
                   15734: ( $4057D280 )  add     ebx , # 4  \ $83 $C3 $4 
                   15735: ( $4057D283 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
                   15736: ( $4057D286 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
                   15737: ( $4057D289 )  add     esi , # 4  \ $83 $C6 $4 
                   15738: ( $4057D28C )  add     ebx , # 4  \ $83 $C3 $4 
                   15739: ( $4057D28F )  imul    ecx , eax  \ $F $AF $C8 
                   15740: ( $4057D292 )  mov     eax , dword ptr [edi]  \ $8B $7 
                   15741: ( $4057D294 )  add     edi , # 4  \ $83 $C7 $4 
                   15742: ( $4057D297 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
                   15743: ( $4057D29A )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   15744: @end example
                   15745: 
                   15746: Only when a threaded-code control-flow change happens (e.g., in
                   15747: @code{;s}), the jump is appended.  This optimization eliminates many of
                   15748: these jumps and makes the rest much more predictable.  The speedup
                   15749: depends on the processor and the application; on the Athlon and Pentium
                   15750: III this optimization typically produces a speedup by a factor of 2.
                   15751: 
                   15752: The code addresses in the direct-threaded code are set to point to the
                   15753: appropriate points in the copied machine code, in this example like
                   15754: this:
1.1       anton    15755: 
1.109     anton    15756: @example
                   15757: primitive  code address
                   15758:    dup       $4057D27D
                   15759:    *         $4057D286
                   15760:    ;s        $4057D292
                   15761: @end example
                   15762: 
                   15763: Thus there can be threaded-code jumps to any place in this piece of
                   15764: code.  This also simplifies decompilation quite a bit.
                   15765: 
                   15766: @cindex --no-dynamic command-line option
                   15767: @cindex --no-super command-line option
                   15768: You can disable this optimization with @option{--no-dynamic}.  You can
                   15769: use the copying without eliminating the jumps (i.e., dynamic
                   15770: replication, but without superinstructions) with @option{--no-super};
                   15771: this gives the branch prediction benefit alone; the effect on
1.110     anton    15772: performance depends on the CPU; on the Athlon and Pentium III the
                   15773: speedup is a little less than for dynamic superinstructions with
                   15774: replication.
                   15775: 
                   15776: @cindex patching threaded code
                   15777: One use of these options is if you want to patch the threaded code.
                   15778: With superinstructions, many of the dispatch jumps are eliminated, so
                   15779: patching often has no effect.  These options preserve all the dispatch
                   15780: jumps.
1.109     anton    15781: 
                   15782: @cindex --dynamic command-line option
1.110     anton    15783: On some machines dynamic superinstructions are disabled by default,
                   15784: because it is unsafe on these machines.  However, if you feel
                   15785: adventurous, you can enable it with @option{--dynamic}.
1.109     anton    15786: 
                   15787: @node DOES>,  , Dynamic Superinstructions, Threading
1.1       anton    15788: @subsection DOES>
                   15789: @cindex @code{DOES>} implementation
                   15790: 
1.26      crook    15791: @cindex @code{dodoes} routine
                   15792: @cindex @code{DOES>}-code
1.1       anton    15793: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   15794: the chunk of code executed by every word defined by a
1.109     anton    15795: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
                   15796: this is only needed if the xt of the word is @code{execute}d. The main
                   15797: problem here is: How to find the Forth code to be executed, i.e. the
                   15798: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
                   15799: solutions:
1.1       anton    15800: 
1.21      crook    15801: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109     anton    15802: @code{DOES>}-code address is stored in the cell after the code address
                   15803: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
                   15804: illegal in the Forth-79 and all later standards, because in fig-Forth
                   15805: this address lies in the body (which is illegal in these
                   15806: standards). However, by making the code field larger for all words this
                   15807: solution becomes legal again.  We use this approach.  Leaving a cell
                   15808: unused in most words is a bit wasteful, but on the machines we are
                   15809: targeting this is hardly a problem.
                   15810: 
1.1       anton    15811: 
                   15812: @node Primitives, Performance, Threading, Engine
                   15813: @section Primitives
                   15814: @cindex primitives, implementation
                   15815: @cindex virtual machine instructions, implementation
                   15816: 
                   15817: @menu
                   15818: * Automatic Generation::        
                   15819: * TOS Optimization::            
                   15820: * Produced code::               
                   15821: @end menu
                   15822: 
                   15823: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   15824: @subsection Automatic Generation
                   15825: @cindex primitives, automatic generation
                   15826: 
                   15827: @cindex @file{prims2x.fs}
1.109     anton    15828: 
1.1       anton    15829: Since the primitives are implemented in a portable language, there is no
                   15830: longer any need to minimize the number of primitives. On the contrary,
                   15831: having many primitives has an advantage: speed. In order to reduce the
                   15832: number of errors in primitives and to make programming them easier, we
1.109     anton    15833: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
                   15834: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
                   15835: generates most (and sometimes all) of the C code for a primitive from
                   15836: the stack effect notation.  The source for a primitive has the following
                   15837: form:
1.1       anton    15838: 
                   15839: @cindex primitive source format
                   15840: @format
1.58      anton    15841: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
1.29      crook    15842: [@code{""}@i{glossary entry}@code{""}]
                   15843: @i{C code}
1.1       anton    15844: [@code{:}
1.29      crook    15845: @i{Forth code}]
1.1       anton    15846: @end format
                   15847: 
                   15848: The items in brackets are optional. The category and glossary fields
                   15849: are there for generating the documentation, the Forth code is there
                   15850: for manual implementations on machines without GNU C. E.g., the source
                   15851: for the primitive @code{+} is:
                   15852: @example
1.58      anton    15853: +    ( n1 n2 -- n )   core    plus
1.1       anton    15854: n = n1+n2;
                   15855: @end example
                   15856: 
                   15857: This looks like a specification, but in fact @code{n = n1+n2} is C
                   15858: code. Our primitive generation tool extracts a lot of information from
                   15859: the stack effect notations@footnote{We use a one-stack notation, even
                   15860: though we have separate data and floating-point stacks; The separate
                   15861: notation can be generated easily from the unified notation.}: The number
                   15862: of items popped from and pushed on the stack, their type, and by what
                   15863: name they are referred to in the C code. It then generates a C code
                   15864: prelude and postlude for each primitive. The final C code for @code{+}
                   15865: looks like this:
                   15866: 
                   15867: @example
1.46      pazsan   15868: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
1.1       anton    15869: /*  */                          /* documentation */
1.81      anton    15870: NAME("+")                       /* debugging output (with -DDEBUG) */
1.1       anton    15871: @{
                   15872: DEF_CA                          /* definition of variable ca (indirect threading) */
                   15873: Cell n1;                        /* definitions of variables */
                   15874: Cell n2;
                   15875: Cell n;
1.81      anton    15876: NEXT_P0;                        /* NEXT part 0 */
1.1       anton    15877: n1 = (Cell) sp[1];              /* input */
                   15878: n2 = (Cell) TOS;
                   15879: sp += 1;                        /* stack adjustment */
                   15880: @{
                   15881: n = n1+n2;                      /* C code taken from the source */
                   15882: @}
                   15883: NEXT_P1;                        /* NEXT part 1 */
                   15884: TOS = (Cell)n;                  /* output */
                   15885: NEXT_P2;                        /* NEXT part 2 */
                   15886: @}
                   15887: @end example
                   15888: 
                   15889: This looks long and inefficient, but the GNU C compiler optimizes quite
                   15890: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   15891: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   15892: using them as intermediate storage also adds no cost.
                   15893: 
1.26      crook    15894: There are also other optimizations that are not illustrated by this
                   15895: example: assignments between simple variables are usually for free (copy
1.1       anton    15896: propagation). If one of the stack items is not used by the primitive
                   15897: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   15898: (dead code elimination). On the other hand, there are some things that
                   15899: the compiler does not do, therefore they are performed by
                   15900: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   15901: a stack item to the place where it just came from (e.g., @code{over}).
                   15902: 
                   15903: While programming a primitive is usually easy, there are a few cases
                   15904: where the programmer has to take the actions of the generator into
                   15905: account, most notably @code{?dup}, but also words that do not (always)
1.26      crook    15906: fall through to @code{NEXT}.
1.109     anton    15907: 
                   15908: For more information
1.1       anton    15909: 
                   15910: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   15911: @subsection TOS Optimization
                   15912: @cindex TOS optimization for primitives
                   15913: @cindex primitives, keeping the TOS in a register
                   15914: 
                   15915: An important optimization for stack machine emulators, e.g., Forth
                   15916: engines, is keeping  one or more of the top stack items in
1.29      crook    15917: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
                   15918: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1       anton    15919: @itemize @bullet
                   15920: @item
1.29      crook    15921: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1       anton    15922: due to fewer loads from and stores to the stack.
1.29      crook    15923: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
                   15924: @i{y<n}, due to additional moves between registers.
1.1       anton    15925: @end itemize
                   15926: 
                   15927: @cindex -DUSE_TOS
                   15928: @cindex -DUSE_NO_TOS
                   15929: In particular, keeping one item in a register is never a disadvantage,
                   15930: if there are enough registers. Keeping two items in registers is a
                   15931: disadvantage for frequent words like @code{?branch}, constants,
                   15932: variables, literals and @code{i}. Therefore our generator only produces
                   15933: code that keeps zero or one items in registers. The generated C code
                   15934: covers both cases; the selection between these alternatives is made at
                   15935: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   15936: code for @code{+} is just a simple variable name in the one-item case,
                   15937: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   15938: GNU C compiler tries to keep simple variables like @code{TOS} in
                   15939: registers, and it usually succeeds, if there are enough registers.
                   15940: 
                   15941: @cindex -DUSE_FTOS
                   15942: @cindex -DUSE_NO_FTOS
                   15943: The primitive generator performs the TOS optimization for the
                   15944: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   15945: operations the benefit of this optimization is even larger:
                   15946: floating-point operations take quite long on most processors, but can be
                   15947: performed in parallel with other operations as long as their results are
                   15948: not used. If the FP-TOS is kept in a register, this works. If
                   15949: it is kept on the stack, i.e., in memory, the store into memory has to
                   15950: wait for the result of the floating-point operation, lengthening the
                   15951: execution time of the primitive considerably.
                   15952: 
                   15953: The TOS optimization makes the automatic generation of primitives a
                   15954: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   15955: @code{TOS} is not sufficient. There are some special cases to
                   15956: consider:
                   15957: @itemize @bullet
                   15958: @item In the case of @code{dup ( w -- w w )} the generator must not
                   15959: eliminate the store to the original location of the item on the stack,
                   15960: if the TOS optimization is turned on.
                   15961: @item Primitives with stack effects of the form @code{--}
1.29      crook    15962: @i{out1}...@i{outy} must store the TOS to the stack at the start.
                   15963: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1       anton    15964: must load the TOS from the stack at the end. But for the null stack
                   15965: effect @code{--} no stores or loads should be generated.
                   15966: @end itemize
                   15967: 
                   15968: @node Produced code,  , TOS Optimization, Primitives
                   15969: @subsection Produced code
                   15970: @cindex primitives, assembly code listing
                   15971: 
                   15972: @cindex @file{engine.s}
                   15973: To see what assembly code is produced for the primitives on your machine
                   15974: with your compiler and your flag settings, type @code{make engine.s} and
1.81      anton    15975: look at the resulting file @file{engine.s}.  Alternatively, you can also
                   15976: disassemble the code of primitives with @code{see} on some architectures.
1.1       anton    15977: 
                   15978: @node  Performance,  , Primitives, Engine
                   15979: @section Performance
                   15980: @cindex performance of some Forth interpreters
                   15981: @cindex engine performance
                   15982: @cindex benchmarking Forth systems
                   15983: @cindex Gforth performance
                   15984: 
                   15985: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112     anton    15986: impossible to write a significantly faster threaded-code engine.
1.1       anton    15987: 
                   15988: On register-starved machines like the 386 architecture processors
                   15989: improvements are possible, because @code{gcc} does not utilize the
                   15990: registers as well as a human, even with explicit register declarations;
                   15991: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   15992: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   15993: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40      anton    15994: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
                   15995: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
                   15996: registers fit in real registers (and we can even afford to use the TOS
                   15997: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112     anton    15998: earlier results.  And dynamic superinstructions provide another speedup
                   15999: (but only around a factor 1.2 on the 486).
1.1       anton    16000: 
                   16001: @cindex Win32Forth performance
                   16002: @cindex NT Forth performance
                   16003: @cindex eforth performance
                   16004: @cindex ThisForth performance
                   16005: @cindex PFE performance
                   16006: @cindex TILE performance
1.81      anton    16007: The potential advantage of assembly language implementations is not
1.112     anton    16008: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81      anton    16009: (direct threaded, compiled with @code{gcc-2.95.1} and
                   16010: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
                   16011: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
                   16012: (with and without peephole (aka pinhole) optimization of the threaded
                   16013: code); all these systems were written in assembly language. We also
                   16014: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
                   16015: with @code{gcc-2.6.3} with the default configuration for Linux:
                   16016: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
                   16017: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
                   16018: employs peephole optimization of the threaded code) and TILE (compiled
                   16019: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
                   16020: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
                   16021: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
                   16022: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
                   16023: then extended it to run the benchmarks, added the peephole optimizer,
                   16024: ran the benchmarks and reported the results.
1.40      anton    16025: 
1.1       anton    16026: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   16027: matrix multiplication come from the Stanford integer benchmarks and have
                   16028: been translated into Forth by Martin Fraeman; we used the versions
                   16029: included in the TILE Forth package, but with bigger data set sizes; and
                   16030: a recursive Fibonacci number computation for benchmarking calling
                   16031: performance. The following table shows the time taken for the benchmarks
                   16032: scaled by the time taken by Gforth (in other words, it shows the speedup
                   16033: factor that Gforth achieved over the other systems).
                   16034: 
                   16035: @example
1.112     anton    16036: relative       Win32-    NT       eforth       This-      
                   16037: time     Gforth Forth Forth eforth  +opt   PFE Forth  TILE
                   16038: sieve      1.00  2.16  1.78   2.16  1.32  2.46  4.96 13.37
                   16039: bubble     1.00  1.93  2.07   2.18  1.29  2.21        5.70
                   16040: matmul     1.00  1.92  1.76   1.90  0.96  2.06        5.32
                   16041: fib        1.00  2.32  2.03   1.86  1.31  2.64  4.55  6.54
1.1       anton    16042: @end example
                   16043: 
1.26      crook    16044: You may be quite surprised by the good performance of Gforth when
                   16045: compared with systems written in assembly language. One important reason
                   16046: for the disappointing performance of these other systems is probably
                   16047: that they are not written optimally for the 486 (e.g., they use the
                   16048: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
                   16049: but costly method for relocating the Forth image: like @code{cforth}, it
                   16050: computes the actual addresses at run time, resulting in two address
                   16051: computations per @code{NEXT} (@pxref{Image File Background}).
                   16052: 
1.1       anton    16053: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   16054: explained with the self-imposed restriction of the latter systems to
                   16055: standard C, which makes efficient threading impossible (however, the
1.4       anton    16056: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    16057: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   16058: Moreover, current C compilers have a hard time optimizing other aspects
                   16059: of the ThisForth and the TILE source.
                   16060: 
1.26      crook    16061: The performance of Gforth on 386 architecture processors varies widely
                   16062: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
                   16063: allocate any of the virtual machine registers into real machine
                   16064: registers by itself and would not work correctly with explicit register
1.112     anton    16065: declarations, giving a significantly slower engine (on a 486DX2/66
                   16066: running the Sieve) than the one measured above.
1.1       anton    16067: 
1.26      crook    16068: Note that there have been several releases of Win32Forth since the
                   16069: release presented here, so the results presented above may have little
1.40      anton    16070: predictive value for the performance of Win32Forth today (results for
                   16071: the current release on an i486DX2/66 are welcome).
1.1       anton    16072: 
                   16073: @cindex @file{Benchres}
1.66      anton    16074: In
                   16075: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
                   16076: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1       anton    16077: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66      anton    16078: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
                   16079: several native code systems; that version of Gforth is slower on a 486
1.112     anton    16080: than the version used here. You can find a newer version of these
                   16081: measurements at
1.47      crook    16082: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1       anton    16083: find numbers for Gforth on various machines in @file{Benchres}.
                   16084: 
1.26      crook    16085: @c ******************************************************************
1.113     anton    16086: @c @node Binding to System Library, Cross Compiler, Engine, Top
                   16087: @c @chapter Binding to System Library
1.13      pazsan   16088: 
1.113     anton    16089: @c ****************************************************************
                   16090: @node Cross Compiler, Bugs, Engine, Top
1.14      pazsan   16091: @chapter Cross Compiler
1.47      crook    16092: @cindex @file{cross.fs}
                   16093: @cindex cross-compiler
                   16094: @cindex metacompiler
                   16095: @cindex target compiler
1.13      pazsan   16096: 
1.46      pazsan   16097: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
                   16098: mostly written in Forth, including crucial parts like the outer
                   16099: interpreter and compiler, it needs compiled Forth code to get
                   16100: started. The cross compiler allows to create new images for other
                   16101: architectures, even running under another Forth system.
1.13      pazsan   16102: 
                   16103: @menu
1.67      anton    16104: * Using the Cross Compiler::    
                   16105: * How the Cross Compiler Works::  
1.13      pazsan   16106: @end menu
                   16107: 
1.21      crook    16108: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14      pazsan   16109: @section Using the Cross Compiler
1.46      pazsan   16110: 
                   16111: The cross compiler uses a language that resembles Forth, but isn't. The
                   16112: main difference is that you can execute Forth code after definition,
                   16113: while you usually can't execute the code compiled by cross, because the
                   16114: code you are compiling is typically for a different computer than the
                   16115: one you are compiling on.
                   16116: 
1.81      anton    16117: @c anton: This chapter is somewhat different from waht I would expect: I
                   16118: @c would expect an explanation of the cross language and how to create an
                   16119: @c application image with it.  The section explains some aspects of
                   16120: @c creating a Gforth kernel.
                   16121: 
1.46      pazsan   16122: The Makefile is already set up to allow you to create kernels for new
                   16123: architectures with a simple make command. The generic kernels using the
                   16124: GCC compiled virtual machine are created in the normal build process
                   16125: with @code{make}. To create a embedded Gforth executable for e.g. the
                   16126: 8086 processor (running on a DOS machine), type
                   16127: 
                   16128: @example
                   16129: make kernl-8086.fi
                   16130: @end example
                   16131: 
                   16132: This will use the machine description from the @file{arch/8086}
                   16133: directory to create a new kernel. A machine file may look like that:
                   16134: 
                   16135: @example
                   16136: \ Parameter for target systems                         06oct92py
                   16137: 
                   16138:     4 Constant cell             \ cell size in bytes
                   16139:     2 Constant cell<<           \ cell shift to bytes
                   16140:     5 Constant cell>bit         \ cell shift to bits
                   16141:     8 Constant bits/char        \ bits per character
                   16142:     8 Constant bits/byte        \ bits per byte [default: 8]
                   16143:     8 Constant float            \ bytes per float
                   16144:     8 Constant /maxalign        \ maximum alignment in bytes
                   16145: false Constant bigendian        \ byte order
                   16146: ( true=big, false=little )
                   16147: 
                   16148: include machpc.fs               \ feature list
                   16149: @end example
                   16150: 
                   16151: This part is obligatory for the cross compiler itself, the feature list
                   16152: is used by the kernel to conditionally compile some features in and out,
                   16153: depending on whether the target supports these features.
                   16154: 
                   16155: There are some optional features, if you define your own primitives,
                   16156: have an assembler, or need special, nonstandard preparation to make the
1.81      anton    16157: boot process work. @code{asm-include} includes an assembler,
1.46      pazsan   16158: @code{prims-include} includes primitives, and @code{>boot} prepares for
                   16159: booting.
                   16160: 
                   16161: @example
                   16162: : asm-include    ." Include assembler" cr
                   16163:   s" arch/8086/asm.fs" included ;
                   16164: 
                   16165: : prims-include  ." Include primitives" cr
                   16166:   s" arch/8086/prim.fs" included ;
                   16167: 
                   16168: : >boot          ." Prepare booting" cr
                   16169:   s" ' boot >body into-forth 1+ !" evaluate ;
                   16170: @end example
                   16171: 
                   16172: These words are used as sort of macro during the cross compilation in
1.81      anton    16173: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46      pazsan   16174: be possible --- but more complicated --- to write a new kernel project
                   16175: file, too.
                   16176: 
                   16177: @file{kernel/main.fs} expects the machine description file name on the
                   16178: stack; the cross compiler itself (@file{cross.fs}) assumes that either
                   16179: @code{mach-file} leaves a counted string on the stack, or
                   16180: @code{machine-file} leaves an address, count pair of the filename on the
                   16181: stack.
                   16182: 
                   16183: The feature list is typically controlled using @code{SetValue}, generic
                   16184: files that are used by several projects can use @code{DefaultValue}
                   16185: instead. Both functions work like @code{Value}, when the value isn't
                   16186: defined, but @code{SetValue} works like @code{to} if the value is
                   16187: defined, and @code{DefaultValue} doesn't set anything, if the value is
                   16188: defined.
                   16189: 
                   16190: @example
                   16191: \ generic mach file for pc gforth                       03sep97jaw
                   16192: 
                   16193: true DefaultValue NIL  \ relocating
                   16194: 
                   16195: >ENVIRON
                   16196: 
                   16197: true DefaultValue file          \ controls the presence of the
                   16198:                                 \ file access wordset
                   16199: true DefaultValue OS            \ flag to indicate a operating system
                   16200: 
                   16201: true DefaultValue prims         \ true: primitives are c-code
                   16202: 
                   16203: true DefaultValue floating      \ floating point wordset is present
                   16204: 
                   16205: true DefaultValue glocals       \ gforth locals are present
                   16206:                                 \ will be loaded
                   16207: true DefaultValue dcomps        \ double number comparisons
                   16208: 
                   16209: true DefaultValue hash          \ hashing primitives are loaded/present
                   16210: 
                   16211: true DefaultValue xconds        \ used together with glocals,
                   16212:                                 \ special conditionals supporting gforths'
                   16213:                                 \ local variables
                   16214: true DefaultValue header        \ save a header information
                   16215: 
                   16216: true DefaultValue backtrace     \ enables backtrace code
                   16217: 
                   16218: false DefaultValue ec
                   16219: false DefaultValue crlf
                   16220: 
                   16221: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
                   16222: 
                   16223: &16 KB          DefaultValue stack-size
                   16224: &15 KB &512 +   DefaultValue fstack-size
                   16225: &15 KB          DefaultValue rstack-size
                   16226: &14 KB &512 +   DefaultValue lstack-size
                   16227: @end example
1.13      pazsan   16228: 
1.48      anton    16229: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
1.14      pazsan   16230: @section How the Cross Compiler Works
1.13      pazsan   16231: 
                   16232: @node Bugs, Origin, Cross Compiler, Top
1.21      crook    16233: @appendix Bugs
1.1       anton    16234: @cindex bug reporting
                   16235: 
1.21      crook    16236: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1       anton    16237: 
1.103     anton    16238: If you find a bug, please submit a bug report through
                   16239: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21      crook    16240: 
                   16241: @itemize @bullet
                   16242: @item
1.81      anton    16243: A program (or a sequence of keyboard commands) that reproduces the bug.
                   16244: @item
                   16245: A description of what you think constitutes the buggy behaviour.
                   16246: @item
1.21      crook    16247: The Gforth version used (it is announced at the start of an
                   16248: interactive Gforth session).
                   16249: @item
                   16250: The machine and operating system (on Unix
                   16251: systems @code{uname -a} will report this information).
                   16252: @item
1.81      anton    16253: The installation options (you can find the configure options at the
                   16254: start of @file{config.status}) and configuration (@code{configure}
                   16255: output or @file{config.cache}).
1.21      crook    16256: @item
                   16257: A complete list of changes (if any) you (or your installer) have made to the
                   16258: Gforth sources.
                   16259: @end itemize
1.1       anton    16260: 
                   16261: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   16262: to Report Bugs, gcc.info, GNU C Manual}.
                   16263: 
                   16264: 
1.21      crook    16265: @node Origin, Forth-related information, Bugs, Top
                   16266: @appendix Authors and Ancestors of Gforth
1.1       anton    16267: 
                   16268: @section Authors and Contributors
                   16269: @cindex authors of Gforth
                   16270: @cindex contributors to Gforth
                   16271: 
                   16272: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81      anton    16273: Ertl. The third major author was Jens Wilke.  Neal Crook contributed a
                   16274: lot to the manual.  Assemblers and disassemblers were contributed by
1.161     anton    16275: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
                   16276: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
                   16277: and Stuart Ramsden inspired us with their continuous feedback. Lennart
                   16278: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
                   16279: working on automatic support for calling C libraries. Helpful comments
                   16280: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
                   16281: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
                   16282: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
                   16283: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
                   16284: comments from many others; thank you all, sorry for not listing you
                   16285: here (but digging through my mailbox to extract your names is on my
                   16286: to-do list).
1.1       anton    16287: 
                   16288: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   16289: and autoconf, among others), and to the creators of the Internet: Gforth
1.21      crook    16290: was developed across the Internet, and its authors did not meet
1.20      pazsan   16291: physically for the first 4 years of development.
1.1       anton    16292: 
                   16293: @section Pedigree
1.26      crook    16294: @cindex pedigree of Gforth
1.1       anton    16295: 
1.81      anton    16296: Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
                   16297: significant part of the design of Gforth was prescribed by ANS Forth.
1.1       anton    16298: 
1.20      pazsan   16299: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1       anton    16300: 32 bit native code version of VolksForth for the Atari ST, written
                   16301: mostly by Dietrich Weineck.
                   16302: 
1.81      anton    16303: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
                   16304: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147     anton    16305: the mid-80s and ported to the Atari ST in 1986.  It descends from fig-Forth.
1.1       anton    16306: 
1.147     anton    16307: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   16308: @c Forth-83 standard. !! Pedigree? When?
1.1       anton    16309: 
                   16310: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   16311: 1979. Robert Selzer and Bill Ragsdale developed the original
                   16312: implementation of fig-Forth for the 6502 based on microForth.
                   16313: 
                   16314: The principal architect of microForth was Dean Sanderson. microForth was
                   16315: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   16316: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   16317: Z80.
                   16318: 
                   16319: All earlier Forth systems were custom-made, usually by Charles Moore,
                   16320: who discovered (as he puts it) Forth during the late 60s. The first full
                   16321: Forth existed in 1971.
                   16322: 
1.81      anton    16323: A part of the information in this section comes from
                   16324: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
                   16325: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147     anton    16326: Charles H. Moore, presented at the HOPL-II conference and preprinted
                   16327: in SIGPLAN Notices 28(3), 1993.  You can find more historical and
                   16328: genealogical information about Forth there.  For a more general (and
                   16329: graphical) Forth family tree look see
                   16330: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
                   16331: Forth Family Tree and Timeline}.
1.1       anton    16332: 
1.81      anton    16333: @c ------------------------------------------------------------------
1.113     anton    16334: @node Forth-related information, Licenses, Origin, Top
1.21      crook    16335: @appendix Other Forth-related information
                   16336: @cindex Forth-related information
                   16337: 
1.81      anton    16338: @c anton: I threw most of this stuff out, because it can be found through
                   16339: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21      crook    16340: 
                   16341: @cindex comp.lang.forth
                   16342: @cindex frequently asked questions
1.81      anton    16343: There is an active news group (comp.lang.forth) discussing Forth
                   16344: (including Gforth) and Forth-related issues. Its
                   16345: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
                   16346: (frequently asked questions and their answers) contains a lot of
                   16347: information on Forth.  You should read it before posting to
                   16348: comp.lang.forth.
1.21      crook    16349: 
1.81      anton    16350: The ANS Forth standard is most usable in its
                   16351: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21      crook    16352: 
1.113     anton    16353: @c ---------------------------------------------------
                   16354: @node  Licenses, Word Index, Forth-related information, Top
                   16355: @appendix Licenses
                   16356: 
                   16357: @menu
                   16358: * GNU Free Documentation License::  License for copying this manual.
1.192     anton    16359: * Copying::                     GPL (for copying this software).
1.113     anton    16360: @end menu
                   16361: 
1.192     anton    16362: @node GNU Free Documentation License, Copying, Licenses, Licenses
                   16363: @appendixsec GNU Free Documentation License
1.113     anton    16364: @include fdl.texi
                   16365: 
1.192     anton    16366: @node Copying,  , GNU Free Documentation License, Licenses
                   16367: @appendixsec GNU GENERAL PUBLIC LICENSE
1.113     anton    16368: @include gpl.texi
                   16369: 
                   16370: 
                   16371: 
1.81      anton    16372: @c ------------------------------------------------------------------
1.113     anton    16373: @node Word Index, Concept Index, Licenses, Top
1.1       anton    16374: @unnumbered Word Index
                   16375: 
1.26      crook    16376: This index is a list of Forth words that have ``glossary'' entries
                   16377: within this manual. Each word is listed with its stack effect and
                   16378: wordset.
1.1       anton    16379: 
                   16380: @printindex fn
                   16381: 
1.81      anton    16382: @c anton: the name index seems superfluous given the word and concept indices.
                   16383: 
                   16384: @c @node Name Index, Concept Index, Word Index, Top
                   16385: @c @unnumbered Name Index
1.41      anton    16386: 
1.81      anton    16387: @c This index is a list of Forth words that have ``glossary'' entries
                   16388: @c within this manual.
1.41      anton    16389: 
1.81      anton    16390: @c @printindex ky
1.41      anton    16391: 
1.113     anton    16392: @c -------------------------------------------------------
1.81      anton    16393: @node Concept Index,  , Word Index, Top
1.1       anton    16394: @unnumbered Concept and Word Index
                   16395: 
1.26      crook    16396: Not all entries listed in this index are present verbatim in the
                   16397: text. This index also duplicates, in abbreviated form, all of the words
                   16398: listed in the Word Index (only the names are listed for the words here).
1.1       anton    16399: 
                   16400: @printindex cp
                   16401: 
                   16402: @bye
1.81      anton    16403: 
                   16404: 
1.1       anton    16405: 

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