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

1.1       anton       1: \input texinfo   @c -*-texinfo-*-
                      2: @comment The source is gforth.ds, from which gforth.texi is generated
1.28      crook       3: 
1.21      crook       4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
1.28      crook       5: @comment 1. x-ref all ambiguous or implementation-defined features?
                      6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
                      7: @comment 3. words in miscellaneous section need a home.
                      8: @comment 4. search for TODO for other minor and major works required.
                      9: @comment 5. [rats] change all @var to @i in Forth source so that info
                     10: @comment    file looks decent.
1.36      anton      11: @c          Not an improvement IMO - anton
                     12: @c          and anyway, this should be taken up
                     13: @c          with Karl Berry (the texinfo guy) - anton
1.113     anton      14: @c
                     15: @c Karl Berry writes:
                     16: @c  If they don't like the all-caps for @var Info output, all I can say is
                     17: @c  that it's always been that way, and the usage of all-caps for
                     18: @c  metavariables has a long tradition.  I think it's best to just let it be
                     19: @c  what it is, for the sake of consistency among manuals.
                     20: @c
1.29      crook      21: @comment .. would be useful to have a word that identified all deferred words
                     22: @comment should semantics stuff in intro be moved to another section
                     23: 
1.66      anton      24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
1.28      crook      25: 
1.1       anton      26: @comment %**start of header (This is for running Texinfo on a region.)
                     27: @setfilename gforth.info
1.113     anton      28: @include version.texi
1.1       anton      29: @settitle Gforth Manual
1.113     anton      30: @c @syncodeindex pg cp
1.49      anton      31: 
1.12      anton      32: @macro progstyle {}
                     33: Programming style note:
1.3       anton      34: @end macro
1.48      anton      35: 
                     36: @macro assignment {}
                     37: @table @i
                     38: @item Assignment:
                     39: @end macro
                     40: @macro endassignment {}
                     41: @end table
                     42: @end macro
                     43: 
1.29      crook      44: @comment macros for beautifying glossary entries
                     45: @macro GLOSS-START {}
                     46: @iftex
                     47: @ninerm
                     48: @end iftex
                     49: @end macro
                     50: 
                     51: @macro GLOSS-END {}
                     52: @iftex
                     53: @rm
                     54: @end iftex
                     55: @end macro
                     56: 
1.113     anton      57: @comment %**end of header (This is for running Texinfo on a region.)
                     58: @copying
1.125     anton      59: This manual is for Gforth (version @value{VERSION}, @value{UPDATED}),
                     60: a fast and portable implementation of the ANS Forth language.  It
                     61: serves as reference manual, but it also contains an introduction to
                     62: Forth and a Forth tutorial.
1.29      crook      63: 
1.197     anton      64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007,2008 Free Software Foundation, Inc.
1.29      crook      65: 
1.113     anton      66: @quotation
                     67: Permission is granted to copy, distribute and/or modify this document
                     68: under the terms of the GNU Free Documentation License, Version 1.1 or
                     69: any later version published by the Free Software Foundation; with no
                     70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
                     71: and with the Back-Cover Texts as in (a) below.  A copy of the
                     72: license is included in the section entitled ``GNU Free Documentation
                     73: License.''
                     74: 
                     75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
                     76: this GNU Manual, like GNU software.  Copies published by the Free
                     77: Software Foundation raise funds for GNU development.''
                     78: @end quotation
                     79: @end copying
1.10      anton      80: 
1.113     anton      81: @dircategory Software development
                     82: @direntry
                     83: * Gforth: (gforth).             A fast interpreter for the Forth language.
                     84: @end direntry
                     85: @c The Texinfo manual also recommends doing this, but for Gforth it may
                     86: @c  not make much sense
                     87: @c @dircategory Individual utilities
                     88: @c @direntry
                     89: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
                     90: @c @end direntry
1.1       anton      91: 
                     92: @titlepage
1.113     anton      93: @title Gforth
                     94: @subtitle for version @value{VERSION}, @value{UPDATED}
                     95: @author Neal Crook
                     96: @author Anton Ertl
1.114     anton      97: @author David Kuehling
1.113     anton      98: @author Bernd Paysan
                     99: @author Jens Wilke
1.1       anton     100: @page
                    101: @vskip 0pt plus 1filll
1.113     anton     102: @insertcopying
                    103: @end titlepage
1.1       anton     104: 
1.113     anton     105: @contents
1.1       anton     106: 
1.113     anton     107: @ifnottex
                    108: @node Top, Goals, (dir), (dir)
                    109: @top Gforth
1.1       anton     110: 
1.113     anton     111: @insertcopying
1.49      anton     112: @end ifnottex
1.1       anton     113: 
                    114: @menu
1.26      crook     115: * Goals::                       About the Gforth Project
1.29      crook     116: * Gforth Environment::          Starting (and exiting) Gforth
1.48      anton     117: * Tutorial::                    Hands-on Forth Tutorial
1.21      crook     118: * Introduction::                An introduction to ANS Forth
1.1       anton     119: * Words::                       Forth words available in Gforth
1.24      anton     120: * Error messages::              How to interpret them
1.1       anton     121: * Tools::                       Programming tools
                    122: * ANS conformance::             Implementation-defined options etc.
1.65      anton     123: * Standard vs Extensions::      Should I use extensions?
1.1       anton     124: * Model::                       The abstract machine of Gforth
                    125: * Integrating Gforth::          Forth as scripting language for applications
                    126: * Emacs and Gforth::            The Gforth Mode
                    127: * Image Files::                 @code{.fi} files contain compiled code
                    128: * Engine::                      The inner interpreter and the primitives
1.13      pazsan    129: * Cross Compiler::              The Cross Compiler
1.1       anton     130: * Bugs::                        How to report them
                    131: * Origin::                      Authors and ancestors of Gforth
1.21      crook     132: * Forth-related information::   Books and places to look on the WWW
1.113     anton     133: * Licenses::                    
1.1       anton     134: * Word Index::                  An item for each Forth word
                    135: * Concept Index::               A menu covering many topics
1.12      anton     136: 
1.91      anton     137: @detailmenu
                    138:  --- The Detailed Node Listing ---
1.12      anton     139: 
1.29      crook     140: Gforth Environment
                    141: 
1.32      anton     142: * Invoking Gforth::             Getting in
                    143: * Leaving Gforth::              Getting out
                    144: * Command-line editing::        
1.48      anton     145: * Environment variables::       that affect how Gforth starts up
1.32      anton     146: * Gforth Files::                What gets installed and where
1.112     anton     147: * Gforth in pipes::             
1.204     anton     148: * Startup speed::               When 14ms is not fast enough ...
1.48      anton     149: 
                    150: Forth Tutorial
                    151: 
                    152: * Starting Gforth Tutorial::    
                    153: * Syntax Tutorial::             
                    154: * Crash Course Tutorial::       
                    155: * Stack Tutorial::              
                    156: * Arithmetics Tutorial::        
                    157: * Stack Manipulation Tutorial::  
                    158: * Using files for Forth code Tutorial::  
                    159: * Comments Tutorial::           
                    160: * Colon Definitions Tutorial::  
                    161: * Decompilation Tutorial::      
                    162: * Stack-Effect Comments Tutorial::  
                    163: * Types Tutorial::              
                    164: * Factoring Tutorial::          
                    165: * Designing the stack effect Tutorial::  
                    166: * Local Variables Tutorial::    
                    167: * Conditional execution Tutorial::  
                    168: * Flags and Comparisons Tutorial::  
                    169: * General Loops Tutorial::      
                    170: * Counted loops Tutorial::      
                    171: * Recursion Tutorial::          
                    172: * Leaving definitions or loops Tutorial::  
                    173: * Return Stack Tutorial::       
                    174: * Memory Tutorial::             
                    175: * Characters and Strings Tutorial::  
                    176: * Alignment Tutorial::          
1.190     anton     177: * Floating Point Tutorial::     
1.87      anton     178: * Files Tutorial::              
1.48      anton     179: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                    180: * Execution Tokens Tutorial::   
                    181: * Exceptions Tutorial::         
                    182: * Defining Words Tutorial::     
                    183: * Arrays and Records Tutorial::  
                    184: * POSTPONE Tutorial::           
                    185: * Literal Tutorial::            
                    186: * Advanced macros Tutorial::    
                    187: * Compilation Tokens Tutorial::  
                    188: * Wordlists and Search Order Tutorial::  
1.29      crook     189: 
1.24      anton     190: An Introduction to ANS Forth
                    191: 
1.67      anton     192: * Introducing the Text Interpreter::  
                    193: * Stacks and Postfix notation::  
                    194: * Your first definition::       
                    195: * How does that work?::         
                    196: * Forth is written in Forth::   
                    197: * Review - elements of a Forth system::  
                    198: * Where to go next::            
                    199: * Exercises::                   
1.24      anton     200: 
1.12      anton     201: Forth Words
                    202: 
                    203: * Notation::                    
1.65      anton     204: * Case insensitivity::          
                    205: * Comments::                    
                    206: * Boolean Flags::               
1.12      anton     207: * Arithmetic::                  
                    208: * Stack Manipulation::          
                    209: * Memory::                      
                    210: * Control Structures::          
                    211: * Defining Words::              
1.65      anton     212: * Interpretation and Compilation Semantics::  
1.47      crook     213: * Tokens for Words::            
1.81      anton     214: * Compiling words::             
1.65      anton     215: * The Text Interpreter::        
1.111     anton     216: * The Input Stream::            
1.65      anton     217: * Word Lists::                  
                    218: * Environmental Queries::       
1.12      anton     219: * Files::                       
                    220: * Blocks::                      
                    221: * Other I/O::                   
1.121     anton     222: * OS command line arguments::   
1.78      anton     223: * Locals::                      
                    224: * Structures::                  
                    225: * Object-oriented Forth::       
1.12      anton     226: * Programming Tools::           
1.150     anton     227: * C Interface::                 
1.12      anton     228: * Assembler and Code Words::    
                    229: * Threading Words::             
1.65      anton     230: * Passing Commands to the OS::  
                    231: * Keeping track of Time::       
                    232: * Miscellaneous Words::         
1.12      anton     233: 
                    234: Arithmetic
                    235: 
                    236: * Single precision::            
1.67      anton     237: * Double precision::            Double-cell integer arithmetic
1.12      anton     238: * Bitwise operations::          
1.67      anton     239: * Numeric comparison::          
1.32      anton     240: * Mixed precision::             Operations with single and double-cell integers
1.12      anton     241: * Floating Point::              
                    242: 
                    243: Stack Manipulation
                    244: 
                    245: * Data stack::                  
                    246: * Floating point stack::        
                    247: * Return stack::                
                    248: * Locals stack::                
                    249: * Stack pointer manipulation::  
                    250: 
                    251: Memory
                    252: 
1.32      anton     253: * Memory model::                
                    254: * Dictionary allocation::       
                    255: * Heap Allocation::             
                    256: * Memory Access::               
                    257: * Address arithmetic::          
                    258: * Memory Blocks::               
1.12      anton     259: 
                    260: Control Structures
                    261: 
1.41      anton     262: * Selection::                   IF ... ELSE ... ENDIF
                    263: * Simple Loops::                BEGIN ...
1.32      anton     264: * Counted Loops::               DO
1.67      anton     265: * Arbitrary control structures::  
                    266: * Calls and returns::           
1.12      anton     267: * Exception Handling::          
                    268: 
                    269: Defining Words
                    270: 
1.67      anton     271: * CREATE::                      
1.44      crook     272: * Variables::                   Variables and user variables
1.67      anton     273: * Constants::                   
1.44      crook     274: * Values::                      Initialised variables
1.67      anton     275: * Colon Definitions::           
1.44      crook     276: * Anonymous Definitions::       Definitions without names
1.71      anton     277: * Supplying names::             Passing definition names as strings
1.67      anton     278: * User-defined Defining Words::  
1.170     pazsan    279: * Deferred Words::              Allow forward references
1.67      anton     280: * Aliases::                     
1.47      crook     281: 
1.63      anton     282: User-defined Defining Words
                    283: 
                    284: * CREATE..DOES> applications::  
                    285: * CREATE..DOES> details::       
                    286: * Advanced does> usage example::  
1.155     anton     287: * Const-does>::                 
1.63      anton     288: 
1.47      crook     289: Interpretation and Compilation Semantics
                    290: 
1.67      anton     291: * Combined words::              
1.12      anton     292: 
1.71      anton     293: Tokens for Words
                    294: 
                    295: * Execution token::             represents execution/interpretation semantics
                    296: * Compilation token::           represents compilation semantics
                    297: * Name token::                  represents named words
                    298: 
1.82      anton     299: Compiling words
                    300: 
                    301: * Literals::                    Compiling data values
                    302: * Macros::                      Compiling words
                    303: 
1.21      crook     304: The Text Interpreter
                    305: 
1.67      anton     306: * Input Sources::               
                    307: * Number Conversion::           
                    308: * Interpret/Compile states::    
                    309: * Interpreter Directives::      
1.21      crook     310: 
1.26      crook     311: Word Lists
                    312: 
1.75      anton     313: * Vocabularies::                
1.67      anton     314: * Why use word lists?::         
1.75      anton     315: * Word list example::           
1.26      crook     316: 
                    317: Files
                    318: 
1.48      anton     319: * Forth source files::          
                    320: * General files::               
1.167     anton     321: * Redirection::                 
1.48      anton     322: * Search Paths::                
                    323: 
                    324: Search Paths
                    325: 
1.75      anton     326: * Source Search Paths::         
1.26      crook     327: * General Search Paths::        
                    328: 
                    329: Other I/O
                    330: 
1.32      anton     331: * Simple numeric output::       Predefined formats
                    332: * Formatted numeric output::    Formatted (pictured) output
                    333: * String Formats::              How Forth stores strings in memory
1.67      anton     334: * Displaying characters and strings::  Other stuff
1.178     anton     335: * Terminal output::             Cursor positioning etc.
1.181     anton     336: * Single-key input::            
                    337: * Line input and conversion::   
1.112     anton     338: * Pipes::                       How to create your own pipes
1.149     pazsan    339: * Xchars and Unicode::          Non-ASCII characters
1.26      crook     340: 
                    341: Locals
                    342: 
                    343: * Gforth locals::               
                    344: * ANS Forth locals::            
                    345: 
                    346: Gforth locals
                    347: 
                    348: * Where are locals visible by name?::  
                    349: * How long do locals live?::    
1.78      anton     350: * Locals programming style::    
                    351: * Locals implementation::       
1.26      crook     352: 
1.12      anton     353: Structures
                    354: 
                    355: * Why explicit structure support?::  
                    356: * Structure Usage::             
                    357: * Structure Naming Convention::  
                    358: * Structure Implementation::    
                    359: * Structure Glossary::          
1.183     anton     360: * Forth200x Structures::        
1.12      anton     361: 
                    362: Object-oriented Forth
                    363: 
1.48      anton     364: * Why object-oriented programming?::  
                    365: * Object-Oriented Terminology::  
                    366: * Objects::                     
                    367: * OOF::                         
                    368: * Mini-OOF::                    
1.23      crook     369: * Comparison with other object models::  
1.12      anton     370: 
1.24      anton     371: The @file{objects.fs} model
1.12      anton     372: 
                    373: * Properties of the Objects model::  
                    374: * Basic Objects Usage::         
1.41      anton     375: * The Objects base class::      
1.12      anton     376: * Creating objects::            
                    377: * Object-Oriented Programming Style::  
                    378: * Class Binding::               
                    379: * Method conveniences::         
                    380: * Classes and Scoping::         
1.41      anton     381: * Dividing classes::            
1.12      anton     382: * Object Interfaces::           
                    383: * Objects Implementation::      
                    384: * Objects Glossary::            
                    385: 
1.24      anton     386: The @file{oof.fs} model
1.12      anton     387: 
1.67      anton     388: * Properties of the OOF model::  
                    389: * Basic OOF Usage::             
                    390: * The OOF base class::          
                    391: * Class Declaration::           
                    392: * Class Implementation::        
1.12      anton     393: 
1.24      anton     394: The @file{mini-oof.fs} model
1.23      crook     395: 
1.48      anton     396: * Basic Mini-OOF Usage::        
                    397: * Mini-OOF Example::            
                    398: * Mini-OOF Implementation::     
1.23      crook     399: 
1.78      anton     400: Programming Tools
                    401: 
1.150     anton     402: * Examining::                   Data and Code.
                    403: * Forgetting words::            Usually before reloading.
1.78      anton     404: * Debugging::                   Simple and quick.
                    405: * Assertions::                  Making your programs self-checking.
                    406: * Singlestep Debugger::         Executing your program word by word.
                    407: 
1.155     anton     408: C Interface
                    409: 
                    410: * Calling C Functions::         
                    411: * Declaring C Functions::       
1.180     anton     412: * Calling C function pointers::  
1.196     anton     413: * Defining library interfaces::  
                    414: * Declaring OS-level libraries::  
1.155     anton     415: * Callbacks::                   
1.178     anton     416: * C interface internals::       
1.155     anton     417: * Low-Level C Interface Words::  
                    418: 
1.78      anton     419: Assembler and Code Words
                    420: 
                    421: * Code and ;code::              
                    422: * Common Assembler::            Assembler Syntax
                    423: * Common Disassembler::         
                    424: * 386 Assembler::               Deviations and special cases
                    425: * Alpha Assembler::             Deviations and special cases
                    426: * MIPS assembler::              Deviations and special cases
1.167     anton     427: * PowerPC assembler::           Deviations and special cases
1.193     dvdkhlng  428: * ARM Assembler::               Deviations and special cases
1.78      anton     429: * Other assemblers::            How to write them
                    430: 
1.12      anton     431: Tools
                    432: 
                    433: * ANS Report::                  Report the words used, sorted by wordset.
1.127     anton     434: * Stack depth changes::         Where does this stack item come from?
1.12      anton     435: 
                    436: ANS conformance
                    437: 
                    438: * The Core Words::              
                    439: * The optional Block word set::  
                    440: * The optional Double Number word set::  
                    441: * The optional Exception word set::  
                    442: * The optional Facility word set::  
                    443: * The optional File-Access word set::  
                    444: * The optional Floating-Point word set::  
                    445: * The optional Locals word set::  
                    446: * The optional Memory-Allocation word set::  
                    447: * The optional Programming-Tools word set::  
                    448: * The optional Search-Order word set::  
                    449: 
                    450: The Core Words
                    451: 
                    452: * core-idef::                   Implementation Defined Options                   
                    453: * core-ambcond::                Ambiguous Conditions                
                    454: * core-other::                  Other System Documentation                  
                    455: 
                    456: The optional Block word set
                    457: 
                    458: * block-idef::                  Implementation Defined Options
                    459: * block-ambcond::               Ambiguous Conditions               
                    460: * block-other::                 Other System Documentation                 
                    461: 
                    462: The optional Double Number word set
                    463: 
                    464: * double-ambcond::              Ambiguous Conditions              
                    465: 
                    466: The optional Exception word set
                    467: 
                    468: * exception-idef::              Implementation Defined Options              
                    469: 
                    470: The optional Facility word set
                    471: 
                    472: * facility-idef::               Implementation Defined Options               
                    473: * facility-ambcond::            Ambiguous Conditions            
                    474: 
                    475: The optional File-Access word set
                    476: 
                    477: * file-idef::                   Implementation Defined Options
                    478: * file-ambcond::                Ambiguous Conditions                
                    479: 
                    480: The optional Floating-Point word set
                    481: 
                    482: * floating-idef::               Implementation Defined Options
                    483: * floating-ambcond::            Ambiguous Conditions            
                    484: 
                    485: The optional Locals word set
                    486: 
                    487: * locals-idef::                 Implementation Defined Options                 
                    488: * locals-ambcond::              Ambiguous Conditions              
                    489: 
                    490: The optional Memory-Allocation word set
                    491: 
                    492: * memory-idef::                 Implementation Defined Options                 
                    493: 
                    494: The optional Programming-Tools word set
                    495: 
                    496: * programming-idef::            Implementation Defined Options            
                    497: * programming-ambcond::         Ambiguous Conditions         
                    498: 
                    499: The optional Search-Order word set
                    500: 
                    501: * search-idef::                 Implementation Defined Options                 
                    502: * search-ambcond::              Ambiguous Conditions              
                    503: 
1.109     anton     504: Emacs and Gforth
                    505: 
                    506: * Installing gforth.el::        Making Emacs aware of Forth.
                    507: * Emacs Tags::                  Viewing the source of a word in Emacs.
                    508: * Hilighting::                  Making Forth code look prettier.
                    509: * Auto-Indentation::            Customizing auto-indentation.
                    510: * Blocks Files::                Reading and writing blocks files.
                    511: 
1.12      anton     512: Image Files
                    513: 
1.24      anton     514: * Image Licensing Issues::      Distribution terms for images.
                    515: * Image File Background::       Why have image files?
1.67      anton     516: * Non-Relocatable Image Files::  don't always work.
1.24      anton     517: * Data-Relocatable Image Files::  are better.
1.67      anton     518: * Fully Relocatable Image Files::  better yet.
1.24      anton     519: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.32      anton     520: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.24      anton     521: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     522: 
                    523: Fully Relocatable Image Files
                    524: 
1.27      crook     525: * gforthmi::                    The normal way
1.12      anton     526: * cross.fs::                    The hard way
                    527: 
                    528: Engine
                    529: 
                    530: * Portability::                 
                    531: * Threading::                   
                    532: * Primitives::                  
                    533: * Performance::                 
                    534: 
                    535: Threading
                    536: 
                    537: * Scheduling::                  
                    538: * Direct or Indirect Threaded?::  
1.109     anton     539: * Dynamic Superinstructions::   
1.12      anton     540: * DOES>::                       
                    541: 
                    542: Primitives
                    543: 
                    544: * Automatic Generation::        
                    545: * TOS Optimization::            
                    546: * Produced code::               
1.13      pazsan    547: 
                    548: Cross Compiler
                    549: 
1.67      anton     550: * Using the Cross Compiler::    
                    551: * How the Cross Compiler Works::  
1.13      pazsan    552: 
1.113     anton     553: Licenses
                    554: 
                    555: * GNU Free Documentation License::  License for copying this manual.
1.192     anton     556: * Copying::                     GPL (for copying this software).
1.113     anton     557: 
1.24      anton     558: @end detailmenu
1.1       anton     559: @end menu
                    560: 
1.113     anton     561: @c ----------------------------------------------------------
1.1       anton     562: @iftex
                    563: @unnumbered Preface
                    564: @cindex Preface
1.21      crook     565: This manual documents Gforth. Some introductory material is provided for
                    566: readers who are unfamiliar with Forth or who are migrating to Gforth
                    567: from other Forth compilers. However, this manual is primarily a
                    568: reference manual.
1.1       anton     569: @end iftex
                    570: 
1.28      crook     571: @comment TODO much more blurb here.
1.26      crook     572: 
                    573: @c ******************************************************************
1.113     anton     574: @node Goals, Gforth Environment, Top, Top
1.26      crook     575: @comment node-name,     next,           previous, up
                    576: @chapter Goals of Gforth
                    577: @cindex goals of the Gforth project
                    578: The goal of the Gforth Project is to develop a standard model for
                    579: ANS Forth. This can be split into several subgoals:
                    580: 
                    581: @itemize @bullet
                    582: @item
                    583: Gforth should conform to the ANS Forth Standard.
                    584: @item
                    585: It should be a model, i.e. it should define all the
                    586: implementation-dependent things.
                    587: @item
                    588: It should become standard, i.e. widely accepted and used. This goal
                    589: is the most difficult one.
                    590: @end itemize
                    591: 
                    592: To achieve these goals Gforth should be
                    593: @itemize @bullet
                    594: @item
                    595: Similar to previous models (fig-Forth, F83)
                    596: @item
                    597: Powerful. It should provide for all the things that are considered
                    598: necessary today and even some that are not yet considered necessary.
                    599: @item
                    600: Efficient. It should not get the reputation of being exceptionally
                    601: slow.
                    602: @item
                    603: Free.
                    604: @item
                    605: Available on many machines/easy to port.
                    606: @end itemize
                    607: 
                    608: Have we achieved these goals? Gforth conforms to the ANS Forth
                    609: standard. It may be considered a model, but we have not yet documented
                    610: which parts of the model are stable and which parts we are likely to
                    611: change. It certainly has not yet become a de facto standard, but it
                    612: appears to be quite popular. It has some similarities to and some
                    613: differences from previous models. It has some powerful features, but not
                    614: yet everything that we envisioned. We certainly have achieved our
1.65      anton     615: execution speed goals (@pxref{Performance})@footnote{However, in 1998
                    616: the bar was raised when the major commercial Forth vendors switched to
                    617: native code compilers.}.  It is free and available on many machines.
1.29      crook     618: 
1.26      crook     619: @c ******************************************************************
1.48      anton     620: @node Gforth Environment, Tutorial, Goals, Top
1.29      crook     621: @chapter Gforth Environment
                    622: @cindex Gforth environment
1.21      crook     623: 
1.45      crook     624: Note: ultimately, the Gforth man page will be auto-generated from the
1.29      crook     625: material in this chapter.
1.21      crook     626: 
                    627: @menu
1.29      crook     628: * Invoking Gforth::             Getting in
                    629: * Leaving Gforth::              Getting out
                    630: * Command-line editing::        
1.48      anton     631: * Environment variables::       that affect how Gforth starts up
1.29      crook     632: * Gforth Files::                What gets installed and where
1.112     anton     633: * Gforth in pipes::             
1.204     anton     634: * Startup speed::               When 14ms is not fast enough ...
1.21      crook     635: @end menu
                    636: 
1.49      anton     637: For related information about the creation of images see @ref{Image Files}.
1.29      crook     638: 
1.21      crook     639: @comment ----------------------------------------------
1.48      anton     640: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29      crook     641: @section Invoking Gforth
                    642: @cindex invoking Gforth
                    643: @cindex running Gforth
                    644: @cindex command-line options
                    645: @cindex options on the command line
                    646: @cindex flags on the command line
1.21      crook     647: 
1.30      anton     648: Gforth is made up of two parts; an executable ``engine'' (named
1.109     anton     649: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30      anton     650: will usually just say @code{gforth} -- this automatically loads the
                    651: default image file @file{gforth.fi}. In many other cases the default
                    652: Gforth image will be invoked like this:
1.21      crook     653: @example
1.30      anton     654: gforth [file | -e forth-code] ...
1.21      crook     655: @end example
1.29      crook     656: @noindent
                    657: This interprets the contents of the files and the Forth code in the order they
                    658: are given.
1.21      crook     659: 
1.109     anton     660: In addition to the @command{gforth} engine, there is also an engine
                    661: called @command{gforth-fast}, which is faster, but gives less
                    662: informative error messages (@pxref{Error messages}) and may catch some
1.166     anton     663: errors (in particular, stack underflows and integer division errors)
                    664: later or not at all.  You should use it for debugged,
1.109     anton     665: performance-critical programs.
                    666: 
                    667: Moreover, there is an engine called @command{gforth-itc}, which is
                    668: useful in some backwards-compatibility situations (@pxref{Direct or
                    669: Indirect Threaded?}).
1.30      anton     670: 
1.29      crook     671: In general, the command line looks like this:
1.21      crook     672: 
                    673: @example
1.30      anton     674: gforth[-fast] [engine options] [image options]
1.21      crook     675: @end example
                    676: 
1.30      anton     677: The engine options must come before the rest of the command
1.29      crook     678: line. They are:
1.26      crook     679: 
1.29      crook     680: @table @code
                    681: @cindex -i, command-line option
                    682: @cindex --image-file, command-line option
                    683: @item --image-file @i{file}
                    684: @itemx -i @i{file}
                    685: Loads the Forth image @i{file} instead of the default
                    686: @file{gforth.fi} (@pxref{Image Files}).
1.21      crook     687: 
1.39      anton     688: @cindex --appl-image, command-line option
                    689: @item --appl-image @i{file}
                    690: Loads the image @i{file} and leaves all further command-line arguments
1.65      anton     691: to the image (instead of processing them as engine options).  This is
                    692: useful for building executable application images on Unix, built with
1.39      anton     693: @code{gforthmi --application ...}.
                    694: 
1.29      crook     695: @cindex --path, command-line option
                    696: @cindex -p, command-line option
                    697: @item --path @i{path}
                    698: @itemx -p @i{path}
                    699: Uses @i{path} for searching the image file and Forth source code files
                    700: instead of the default in the environment variable @code{GFORTHPATH} or
                    701: the path specified at installation time (e.g.,
                    702: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                    703: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook     704: 
1.29      crook     705: @cindex --dictionary-size, command-line option
                    706: @cindex -m, command-line option
                    707: @cindex @i{size} parameters for command-line options
                    708: @cindex size of the dictionary and the stacks
                    709: @item --dictionary-size @i{size}
                    710: @itemx -m @i{size}
                    711: Allocate @i{size} space for the Forth dictionary space instead of
                    712: using the default specified in the image (typically 256K). The
                    713: @i{size} specification for this and subsequent options consists of
                    714: an integer and a unit (e.g.,
                    715: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
                    716: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                    717: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                    718: @code{e} is used.
1.21      crook     719: 
1.29      crook     720: @cindex --data-stack-size, command-line option
                    721: @cindex -d, command-line option
                    722: @item --data-stack-size @i{size}
                    723: @itemx -d @i{size}
                    724: Allocate @i{size} space for the data stack instead of using the
                    725: default specified in the image (typically 16K).
1.21      crook     726: 
1.29      crook     727: @cindex --return-stack-size, command-line option
                    728: @cindex -r, command-line option
                    729: @item --return-stack-size @i{size}
                    730: @itemx -r @i{size}
                    731: Allocate @i{size} space for the return stack instead of using the
                    732: default specified in the image (typically 15K).
1.21      crook     733: 
1.29      crook     734: @cindex --fp-stack-size, command-line option
                    735: @cindex -f, command-line option
                    736: @item --fp-stack-size @i{size}
                    737: @itemx -f @i{size}
                    738: Allocate @i{size} space for the floating point stack instead of
                    739: using the default specified in the image (typically 15.5K). In this case
                    740: the unit specifier @code{e} refers to floating point numbers.
1.21      crook     741: 
1.48      anton     742: @cindex --locals-stack-size, command-line option
                    743: @cindex -l, command-line option
                    744: @item --locals-stack-size @i{size}
                    745: @itemx -l @i{size}
                    746: Allocate @i{size} space for the locals stack instead of using the
                    747: default specified in the image (typically 14.5K).
                    748: 
1.176     anton     749: @cindex --vm-commit, command-line option
                    750: @cindex overcommit memory for dictionary and stacks
                    751: @cindex memory overcommit for dictionary and stacks
                    752: @item --vm-commit
                    753: Normally, Gforth tries to start up even if there is not enough virtual
                    754: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
                    755: on OSs that support it); so you can ask for a really big dictionary
                    756: and/or stacks, and as long as you don't use more virtual memory than
                    757: is available, everything will be fine (but if you use more, processes
                    758: get killed).  With this option you just use the default allocation
                    759: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
                    760: means that you cannot and should not ask for as big dictionary and
                    761: stacks, but once Gforth successfully starts up, out-of-memory won't
                    762: kill it.
                    763: 
1.48      anton     764: @cindex -h, command-line option
                    765: @cindex --help, command-line option
                    766: @item --help
                    767: @itemx -h
                    768: Print a message about the command-line options
                    769: 
                    770: @cindex -v, command-line option
                    771: @cindex --version, command-line option
                    772: @item --version
                    773: @itemx -v
                    774: Print version and exit
                    775: 
                    776: @cindex --debug, command-line option
                    777: @item --debug
                    778: Print some information useful for debugging on startup.
                    779: 
                    780: @cindex --offset-image, command-line option
                    781: @item --offset-image
                    782: Start the dictionary at a slightly different position than would be used
                    783: otherwise (useful for creating data-relocatable images,
                    784: @pxref{Data-Relocatable Image Files}).
                    785: 
                    786: @cindex --no-offset-im, command-line option
                    787: @item --no-offset-im
                    788: Start the dictionary at the normal position.
                    789: 
                    790: @cindex --clear-dictionary, command-line option
                    791: @item --clear-dictionary
                    792: Initialize all bytes in the dictionary to 0 before loading the image
                    793: (@pxref{Data-Relocatable Image Files}).
                    794: 
                    795: @cindex --die-on-signal, command-line-option
                    796: @item --die-on-signal
                    797: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                    798: or the segmentation violation SIGSEGV) by translating it into a Forth
                    799: @code{THROW}. With this option, Gforth exits if it receives such a
                    800: signal. This option is useful when the engine and/or the image might be
                    801: severely broken (such that it causes another signal before recovering
                    802: from the first); this option avoids endless loops in such cases.
1.109     anton     803: 
1.119     anton     804: @cindex --no-dynamic, command-line option
                    805: @cindex --dynamic, command-line option
1.109     anton     806: @item --no-dynamic
                    807: @item --dynamic
                    808: Disable or enable dynamic superinstructions with replication
                    809: (@pxref{Dynamic Superinstructions}).
                    810: 
1.119     anton     811: @cindex --no-super, command-line option
1.109     anton     812: @item --no-super
1.110     anton     813: Disable dynamic superinstructions, use just dynamic replication; this is
                    814: useful if you want to patch threaded code (@pxref{Dynamic
                    815: Superinstructions}).
1.119     anton     816: 
                    817: @cindex --ss-number, command-line option
                    818: @item --ss-number=@var{N}
                    819: Use only the first @var{N} static superinstructions compiled into the
                    820: engine (default: use them all; note that only @code{gforth-fast} has
                    821: any).  This option is useful for measuring the performance impact of
                    822: static superinstructions.
                    823: 
                    824: @cindex --ss-min-..., command-line options
                    825: @item --ss-min-codesize
                    826: @item --ss-min-ls
                    827: @item --ss-min-lsu
                    828: @item --ss-min-nexts
                    829: Use specified metric for determining the cost of a primitive or static
                    830: superinstruction for static superinstruction selection.  @code{Codesize}
                    831: is the native code size of the primive or static superinstruction,
                    832: @code{ls} is the number of loads and stores, @code{lsu} is the number of
                    833: loads, stores, and updates, and @code{nexts} is the number of dispatches
                    834: (not taking dynamic superinstructions into account), i.e. every
                    835: primitive or static superinstruction has cost 1. Default:
                    836: @code{codesize} if you use dynamic code generation, otherwise
                    837: @code{nexts}.
                    838: 
                    839: @cindex --ss-greedy, command-line option
                    840: @item --ss-greedy
                    841: This option is useful for measuring the performance impact of static
                    842: superinstructions.  By default, an optimal shortest-path algorithm is
                    843: used for selecting static superinstructions.  With @option{--ss-greedy}
                    844: this algorithm is modified to assume that anything after the static
                    845: superinstruction currently under consideration is not combined into
                    846: static superinstructions.  With @option{--ss-min-nexts} this produces
                    847: the same result as a greedy algorithm that always selects the longest
                    848: superinstruction available at the moment.  E.g., if there are
                    849: superinstructions AB and BCD, then for the sequence A B C D the optimal
                    850: algorithm will select A BCD and the greedy algorithm will select AB C D.
                    851: 
                    852: @cindex --print-metrics, command-line option
                    853: @item --print-metrics
                    854: Prints some metrics used during static superinstruction selection:
                    855: @code{code size} is the actual size of the dynamically generated code.
                    856: @code{Metric codesize} is the sum of the codesize metrics as seen by
                    857: static superinstruction selection; there is a difference from @code{code
                    858: size}, because not all primitives and static superinstructions are
                    859: compiled into dynamically generated code, and because of markers.  The
                    860: other metrics correspond to the @option{ss-min-...} options.  This
                    861: option is useful for evaluating the effects of the @option{--ss-...}
                    862: options.
1.109     anton     863: 
1.48      anton     864: @end table
                    865: 
                    866: @cindex loading files at startup
                    867: @cindex executing code on startup
                    868: @cindex batch processing with Gforth
                    869: As explained above, the image-specific command-line arguments for the
                    870: default image @file{gforth.fi} consist of a sequence of filenames and
                    871: @code{-e @var{forth-code}} options that are interpreted in the sequence
                    872: in which they are given. The @code{-e @var{forth-code}} or
1.121     anton     873: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
                    874: option takes only one argument; if you want to evaluate more Forth
                    875: words, you have to quote them or use @code{-e} several times. To exit
1.48      anton     876: after processing the command line (instead of entering interactive mode)
1.121     anton     877: append @code{-e bye} to the command line.  You can also process the
                    878: command-line arguments with a Forth program (@pxref{OS command line
                    879: arguments}).
1.48      anton     880: 
                    881: @cindex versions, invoking other versions of Gforth
                    882: If you have several versions of Gforth installed, @code{gforth} will
                    883: invoke the version that was installed last. @code{gforth-@i{version}}
                    884: invokes a specific version. If your environment contains the variable
                    885: @code{GFORTHPATH}, you may want to override it by using the
                    886: @code{--path} option.
                    887: 
                    888: Not yet implemented:
                    889: On startup the system first executes the system initialization file
                    890: (unless the option @code{--no-init-file} is given; note that the system
                    891: resulting from using this option may not be ANS Forth conformant). Then
                    892: the user initialization file @file{.gforth.fs} is executed, unless the
1.62      crook     893: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48      anton     894: then in @file{~}, then in the normal path (see above).
                    895: 
                    896: 
                    897: 
                    898: @comment ----------------------------------------------
                    899: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
                    900: @section Leaving Gforth
                    901: @cindex Gforth - leaving
                    902: @cindex leaving Gforth
                    903: 
                    904: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
                    905: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
                    906: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49      anton     907: data are discarded.  For ways of saving the state of the system before
                    908: leaving Gforth see @ref{Image Files}.
1.48      anton     909: 
                    910: doc-bye
                    911: 
                    912: 
                    913: @comment ----------------------------------------------
1.65      anton     914: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48      anton     915: @section Command-line editing
                    916: @cindex command-line editing
                    917: 
                    918: Gforth maintains a history file that records every line that you type to
                    919: the text interpreter. This file is preserved between sessions, and is
                    920: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
                    921: repeatedly you can recall successively older commands from this (or
                    922: previous) session(s). The full list of command-line editing facilities is:
                    923: 
                    924: @itemize @bullet
                    925: @item
                    926: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
                    927: commands from the history buffer.
                    928: @item
                    929: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
                    930: from the history buffer.
                    931: @item
                    932: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
                    933: @item
                    934: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
                    935: @item
                    936: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
                    937: closing up the line.
                    938: @item
                    939: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
                    940: @item
                    941: @kbd{Ctrl-a} to move the cursor to the start of the line.
                    942: @item
                    943: @kbd{Ctrl-e} to move the cursor to the end of the line.
                    944: @item
                    945: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
                    946: line.
                    947: @item
                    948: @key{TAB} to step through all possible full-word completions of the word
                    949: currently being typed.
                    950: @item
1.65      anton     951: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
                    952: using @code{bye}). 
                    953: @item
                    954: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
                    955: character under the cursor.
1.48      anton     956: @end itemize
                    957: 
                    958: When editing, displayable characters are inserted to the left of the
                    959: cursor position; the line is always in ``insert'' (as opposed to
                    960: ``overstrike'') mode.
                    961: 
                    962: @cindex history file
                    963: @cindex @file{.gforth-history}
                    964: On Unix systems, the history file is @file{~/.gforth-history} by
                    965: default@footnote{i.e. it is stored in the user's home directory.}. You
                    966: can find out the name and location of your history file using:
                    967: 
                    968: @example 
                    969: history-file type \ Unix-class systems
                    970: 
                    971: history-file type \ Other systems
                    972: history-dir  type
                    973: @end example
                    974: 
                    975: If you enter long definitions by hand, you can use a text editor to
                    976: paste them out of the history file into a Forth source file for reuse at
                    977: a later time.
                    978: 
                    979: Gforth never trims the size of the history file, so you should do this
                    980: periodically, if necessary.
                    981: 
                    982: @comment this is all defined in history.fs
                    983: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
                    984: @comment chosen?
                    985: 
                    986: 
                    987: @comment ----------------------------------------------
1.65      anton     988: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48      anton     989: @section Environment variables
                    990: @cindex environment variables
                    991: 
                    992: Gforth uses these environment variables:
                    993: 
                    994: @itemize @bullet
                    995: @item
                    996: @cindex @code{GFORTHHIST} -- environment variable
                    997: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
                    998: open/create the history file, @file{.gforth-history}. Default:
                    999: @code{$HOME}.
                   1000: 
                   1001: @item
                   1002: @cindex @code{GFORTHPATH} -- environment variable
                   1003: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
                   1004: for Forth source-code files.
                   1005: 
                   1006: @item
1.147     anton    1007: @cindex @code{LANG} -- environment variable
                   1008: @code{LANG} -- see @code{LC_CTYPE}
                   1009: 
                   1010: @item
                   1011: @cindex @code{LC_ALL} -- environment variable
                   1012: @code{LC_ALL} -- see @code{LC_CTYPE}
                   1013: 
                   1014: @item
                   1015: @cindex @code{LC_CTYPE} -- environment variable
                   1016: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
                   1017: startup, Gforth uses the UTF-8 encoding for strings internally and
                   1018: expects its input and produces its output in UTF-8 encoding, otherwise
                   1019: the encoding is 8bit (see @pxref{Xchars and Unicode}).  If this
                   1020: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
                   1021: that is unset, in @code{LANG}.
                   1022: 
                   1023: @item
1.129     anton    1024: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
                   1025: 
                   1026: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
                   1027: of @code{system} before passing it to C's @code{system()}.  Default:
1.130     anton    1028: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs.  The prefix
1.129     anton    1029: and the command are directly concatenated, so if a space between them is
                   1030: necessary, append it to the prefix.
                   1031: 
                   1032: @item
1.48      anton    1033: @cindex @code{GFORTH} -- environment variable
1.49      anton    1034: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1035: 
                   1036: @item
                   1037: @cindex @code{GFORTHD} -- environment variable
1.62      crook    1038: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1039: 
                   1040: @item
                   1041: @cindex @code{TMP}, @code{TEMP} - environment variable
                   1042: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
                   1043: location for the history file.
                   1044: @end itemize
                   1045: 
                   1046: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
                   1047: @comment mentioning these.
                   1048: 
                   1049: All the Gforth environment variables default to sensible values if they
                   1050: are not set.
                   1051: 
                   1052: 
                   1053: @comment ----------------------------------------------
1.112     anton    1054: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48      anton    1055: @section Gforth files
                   1056: @cindex Gforth files
                   1057: 
                   1058: When you install Gforth on a Unix system, it installs files in these
                   1059: locations by default:
                   1060: 
                   1061: @itemize @bullet
                   1062: @item
                   1063: @file{/usr/local/bin/gforth}
                   1064: @item
                   1065: @file{/usr/local/bin/gforthmi}
                   1066: @item
                   1067: @file{/usr/local/man/man1/gforth.1} - man page.
                   1068: @item
                   1069: @file{/usr/local/info} - the Info version of this manual.
                   1070: @item
                   1071: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
                   1072: @item
                   1073: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
                   1074: @item
                   1075: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
                   1076: @item
                   1077: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
                   1078: @end itemize
                   1079: 
                   1080: You can select different places for installation by using
                   1081: @code{configure} options (listed with @code{configure --help}).
                   1082: 
                   1083: @comment ----------------------------------------------
1.112     anton    1084: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
                   1085: @section Gforth in pipes
                   1086: @cindex pipes, Gforth as part of
                   1087: 
                   1088: Gforth can be used in pipes created elsewhere (described here).  It can
                   1089: also create pipes on its own (@pxref{Pipes}).
                   1090: 
                   1091: @cindex input from pipes
                   1092: If you pipe into Gforth, your program should read with @code{read-file}
                   1093: or @code{read-line} from @code{stdin} (@pxref{General files}).
                   1094: @code{Key} does not recognize the end of input.  Words like
                   1095: @code{accept} echo the input and are therefore usually not useful for
                   1096: reading from a pipe.  You have to invoke the Forth program with an OS
                   1097: command-line option, as you have no chance to use the Forth command line
                   1098: (the text interpreter would try to interpret the pipe input).
                   1099: 
                   1100: @cindex output in pipes
                   1101: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
                   1102: 
                   1103: @cindex silent exiting from Gforth
                   1104: When you write to a pipe that has been closed at the other end, Gforth
                   1105: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
                   1106: into the exception @code{broken-pipe-error}.  If your application does
                   1107: not catch that exception, the system catches it and exits, usually
                   1108: silently (unless you were working on the Forth command line; then it
                   1109: prints an error message and exits).  This is usually the desired
                   1110: behaviour.
                   1111: 
                   1112: If you do not like this behaviour, you have to catch the exception
                   1113: yourself, and react to it.
                   1114: 
                   1115: Here's an example of an invocation of Gforth that is usable in a pipe:
                   1116: 
                   1117: @example
                   1118: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
                   1119:  type repeat ; foo bye"
                   1120: @end example
                   1121: 
                   1122: This example just copies the input verbatim to the output.  A very
                   1123: simple pipe containing this example looks like this:
                   1124: 
                   1125: @example
                   1126: cat startup.fs |
                   1127: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
                   1128:  type repeat ; foo bye"|
                   1129: head
                   1130: @end example
                   1131: 
                   1132: @cindex stderr and pipes
                   1133: Pipes involving Gforth's @code{stderr} output do not work.
                   1134: 
                   1135: @comment ----------------------------------------------
                   1136: @node Startup speed,  , Gforth in pipes, Gforth Environment
1.48      anton    1137: @section Startup speed
                   1138: @cindex Startup speed
                   1139: @cindex speed, startup
                   1140: 
                   1141: If Gforth is used for CGI scripts or in shell scripts, its startup
1.204     anton    1142: speed may become a problem.  On a 3GHz Core 2 Duo E8400 under 64-bit
                   1143: Linux 2.6.27.8 with libc-2.7, @code{gforth-fast -e bye} takes 13.1ms
                   1144: user and 1.2ms system time (@code{gforth -e bye} is faster on startup
                   1145: with about 3.4ms user time and 1.2ms system time, because it subsumes
                   1146: some of the options discussed below).
1.48      anton    1147: 
                   1148: If startup speed is a problem, you may consider the following ways to
                   1149: improve it; or you may consider ways to reduce the number of startups
1.204     anton    1150: (for example, by using Fast-CGI).  Note that the first steps below
                   1151: improve the startup time at the cost of run-time (including
                   1152: compile-time), so whether they are profitable depends on the balance
                   1153: of these times in your application.
                   1154: 
                   1155: An easy step that influences Gforth startup speed is the use of a
                   1156: number of options that increase run-time, but decrease image-loading
                   1157: time.
                   1158: 
                   1159: The first of these that you should try is @code{--ss-number=0
                   1160: --ss-states=1} because this option buys relatively little run-time
                   1161: speedup and costs quite a bit of time at startup.  @code{gforth-fast
                   1162: --ss-number=0 --ss-states=1 -e bye} takes about 2.8ms user and 1.5ms
                   1163: system time.
1.48      anton    1164: 
1.204     anton    1165: The next option is @code{--no-dynamic} which has a substantial impact
                   1166: on run-time (about a factor of 2 on several platforms), but still
                   1167: makes startup speed a little faster: @code{gforth-fast --ss-number=0
                   1168: --ss-states=1 --no-dynamic -e bye} consumes about 2.6ms user and 1.2ms
                   1169: system time.
                   1170: 
                   1171: The next step to improve startup speed is to use a data-relocatable
                   1172: image (@pxref{Data-Relocatable Image Files}).  This avoids the
                   1173: relocation cost for the code in the image (but not for the data).
                   1174: Note that the image is then specific to the particular binary you are
                   1175: using (i.e., whether it is @code{gforth}, @code{gforth-fast}, and even
                   1176: the particular build).  You create the data-relocatable image that
                   1177: works with @code{./gforth-fast} with @code{GFORTHD="./gforth-fast
                   1178: --no-dynamic" gforthmi gforthdr.fi} (the @code{--no-dynamic} is
                   1179: required here or the image will not work).  And you run it with
                   1180: @code{gforth-fast -i gforthdr.fi ... -e bye} (the flags discussed
                   1181: above don't matter here, because they only come into play on
                   1182: relocatable code).  @code{gforth-fast -i gforthdr.fi -e bye} takes
                   1183: about 1.1ms user and 1.2ms system time.
                   1184: 
                   1185: One step further is to avoid all relocation cost and part of the
                   1186: copy-on-write cost through using a non-relocatable image
                   1187: (@pxref{Non-Relocatable Image Files}).  However, this has the
                   1188: disadvantage that it does not work on operating systems with address
                   1189: space randomization (the default in, e.g., Linux nowadays), or if the
                   1190: dictionary moves for any other reason (e.g., because of a change of
                   1191: the OS kernel or an updated library), so we cannot really recommend
                   1192: it.  You create a non-relocatable image with @code{gforth-fast
                   1193: --no-dynamic -e "savesystem gforthnr.fi bye"} (the @code{--no-dynamic}
                   1194: is required here, too).  And you run it with @code{gforth-fast -i
                   1195: gforthnr.fi ... -e bye} (again the flags discussed above don't
                   1196: matter).  @code{gforth-fast -i gforthdr.fi -e bye} takes
                   1197: about 0.9ms user and 0.9ms system time.
                   1198: 
                   1199: If the script you want to execute contains a significant amount of
                   1200: code, it may be profitable to compile it into the image to avoid the
                   1201: cost of compiling it at startup time.
1.48      anton    1202: 
                   1203: @c ******************************************************************
                   1204: @node Tutorial, Introduction, Gforth Environment, Top
                   1205: @chapter Forth Tutorial
                   1206: @cindex Tutorial
                   1207: @cindex Forth Tutorial
                   1208: 
1.67      anton    1209: @c Topics from nac's Introduction that could be mentioned:
                   1210: @c press <ret> after each line
                   1211: @c Prompt
                   1212: @c numbers vs. words in dictionary on text interpretation
                   1213: @c what happens on redefinition
                   1214: @c parsing words (in particular, defining words)
                   1215: 
1.83      anton    1216: The difference of this chapter from the Introduction
                   1217: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
                   1218: be used while sitting in front of a computer, and covers much more
                   1219: material, but does not explain how the Forth system works.
                   1220: 
1.62      crook    1221: This tutorial can be used with any ANS-compliant Forth; any
1.206     anton    1222: Gforth-specific features are marked as such and you can skip them if
                   1223: you work with another Forth.  This tutorial does not explain all
                   1224: features of Forth, just enough to get you started and give you some
                   1225: ideas about the facilities available in Forth.  Read the rest of the
                   1226: manual when you are through this.
1.48      anton    1227: 
                   1228: The intended way to use this tutorial is that you work through it while
                   1229: sitting in front of the console, take a look at the examples and predict
                   1230: what they will do, then try them out; if the outcome is not as expected,
                   1231: find out why (e.g., by trying out variations of the example), so you
                   1232: understand what's going on.  There are also some assignments that you
                   1233: should solve.
                   1234: 
                   1235: This tutorial assumes that you have programmed before and know what,
                   1236: e.g., a loop is.
                   1237: 
                   1238: @c !! explain compat library
                   1239: 
                   1240: @menu
                   1241: * Starting Gforth Tutorial::    
                   1242: * Syntax Tutorial::             
                   1243: * Crash Course Tutorial::       
                   1244: * Stack Tutorial::              
                   1245: * Arithmetics Tutorial::        
                   1246: * Stack Manipulation Tutorial::  
                   1247: * Using files for Forth code Tutorial::  
                   1248: * Comments Tutorial::           
                   1249: * Colon Definitions Tutorial::  
                   1250: * Decompilation Tutorial::      
                   1251: * Stack-Effect Comments Tutorial::  
                   1252: * Types Tutorial::              
                   1253: * Factoring Tutorial::          
                   1254: * Designing the stack effect Tutorial::  
                   1255: * Local Variables Tutorial::    
                   1256: * Conditional execution Tutorial::  
                   1257: * Flags and Comparisons Tutorial::  
                   1258: * General Loops Tutorial::      
                   1259: * Counted loops Tutorial::      
                   1260: * Recursion Tutorial::          
                   1261: * Leaving definitions or loops Tutorial::  
                   1262: * Return Stack Tutorial::       
                   1263: * Memory Tutorial::             
                   1264: * Characters and Strings Tutorial::  
                   1265: * Alignment Tutorial::          
1.190     anton    1266: * Floating Point Tutorial::     
1.87      anton    1267: * Files Tutorial::              
1.48      anton    1268: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                   1269: * Execution Tokens Tutorial::   
                   1270: * Exceptions Tutorial::         
                   1271: * Defining Words Tutorial::     
                   1272: * Arrays and Records Tutorial::  
                   1273: * POSTPONE Tutorial::           
                   1274: * Literal Tutorial::            
                   1275: * Advanced macros Tutorial::    
                   1276: * Compilation Tokens Tutorial::  
                   1277: * Wordlists and Search Order Tutorial::  
                   1278: @end menu
                   1279: 
                   1280: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
                   1281: @section Starting Gforth
1.66      anton    1282: @cindex starting Gforth tutorial
1.48      anton    1283: You can start Gforth by typing its name:
                   1284: 
                   1285: @example
                   1286: gforth
                   1287: @end example
                   1288: 
                   1289: That puts you into interactive mode; you can leave Gforth by typing
                   1290: @code{bye}.  While in Gforth, you can edit the command line and access
                   1291: the command line history with cursor keys, similar to bash.
                   1292: 
                   1293: 
                   1294: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
                   1295: @section Syntax
1.66      anton    1296: @cindex syntax tutorial
1.48      anton    1297: 
1.171     anton    1298: A @dfn{word} is a sequence of arbitrary characters (except white
1.48      anton    1299: space).  Words are separated by white space.  E.g., each of the
                   1300: following lines contains exactly one word:
                   1301: 
                   1302: @example
                   1303: word
                   1304: !@@#$%^&*()
                   1305: 1234567890
                   1306: 5!a
                   1307: @end example
                   1308: 
1.205     anton    1309: A frequent beginner's error is to leave out necessary white space,
1.48      anton    1310: resulting in an error like @samp{Undefined word}; so if you see such an
                   1311: error, check if you have put spaces wherever necessary.
                   1312: 
                   1313: @example
                   1314: ." hello, world" \ correct
                   1315: ."hello, world"  \ gives an "Undefined word" error
                   1316: @end example
                   1317: 
1.65      anton    1318: Gforth and most other Forth systems ignore differences in case (they are
1.48      anton    1319: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
                   1320: your system is case-sensitive, you may have to type all the examples
                   1321: given here in upper case.
                   1322: 
                   1323: 
                   1324: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
                   1325: @section Crash Course
                   1326: 
                   1327: Type
                   1328: 
                   1329: @example
                   1330: 0 0 !
                   1331: here execute
                   1332: ' catch >body 20 erase abort
                   1333: ' (quit) >body 20 erase
                   1334: @end example
                   1335: 
                   1336: The last two examples are guaranteed to destroy parts of Gforth (and
                   1337: most other systems), so you better leave Gforth afterwards (if it has
                   1338: not finished by itself).  On some systems you may have to kill gforth
                   1339: from outside (e.g., in Unix with @code{kill}).
                   1340: 
                   1341: Now that you know how to produce crashes (and that there's not much to
                   1342: them), let's learn how to produce meaningful programs.
                   1343: 
                   1344: 
                   1345: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
                   1346: @section Stack
1.66      anton    1347: @cindex stack tutorial
1.48      anton    1348: 
                   1349: The most obvious feature of Forth is the stack.  When you type in a
1.205     anton    1350: number, it is pushed on the stack.  You can display the contents of the
1.48      anton    1351: stack with @code{.s}.
                   1352: 
                   1353: @example
                   1354: 1 2 .s
                   1355: 3 .s
                   1356: @end example
                   1357: 
                   1358: @code{.s} displays the top-of-stack to the right, i.e., the numbers
                   1359: appear in @code{.s} output as they appeared in the input.
                   1360: 
1.205     anton    1361: You can print the top element of the stack with @code{.}.
1.48      anton    1362: 
                   1363: @example
                   1364: 1 2 3 . . .
                   1365: @end example
                   1366: 
                   1367: In general, words consume their stack arguments (@code{.s} is an
                   1368: exception).
                   1369: 
1.141     anton    1370: @quotation Assignment
1.48      anton    1371: What does the stack contain after @code{5 6 7 .}?
1.141     anton    1372: @end quotation
1.48      anton    1373: 
                   1374: 
                   1375: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
                   1376: @section Arithmetics
1.66      anton    1377: @cindex arithmetics tutorial
1.48      anton    1378: 
                   1379: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
                   1380: operate on the top two stack items:
                   1381: 
                   1382: @example
1.67      anton    1383: 2 2 .s
                   1384: + .s
                   1385: .
1.48      anton    1386: 2 1 - .
                   1387: 7 3 mod .
                   1388: @end example
                   1389: 
                   1390: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
                   1391: as in the corresponding infix expression (this is generally the case in
                   1392: Forth).
                   1393: 
                   1394: Parentheses are superfluous (and not available), because the order of
                   1395: the words unambiguously determines the order of evaluation and the
                   1396: operands:
                   1397: 
                   1398: @example
                   1399: 3 4 + 5 * .
                   1400: 3 4 5 * + .
                   1401: @end example
                   1402: 
1.141     anton    1403: @quotation Assignment
1.48      anton    1404: What are the infix expressions corresponding to the Forth code above?
                   1405: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
                   1406: known as Postfix or RPN (Reverse Polish Notation).}.
1.141     anton    1407: @end quotation
1.48      anton    1408: 
                   1409: To change the sign, use @code{negate}:
                   1410: 
                   1411: @example
                   1412: 2 negate .
                   1413: @end example
                   1414: 
1.141     anton    1415: @quotation Assignment
1.48      anton    1416: Convert -(-3)*4-5 to Forth.
1.141     anton    1417: @end quotation
1.48      anton    1418: 
                   1419: @code{/mod} performs both @code{/} and @code{mod}.
                   1420: 
                   1421: @example
                   1422: 7 3 /mod . .
                   1423: @end example
                   1424: 
1.66      anton    1425: Reference: @ref{Arithmetic}.
                   1426: 
                   1427: 
1.48      anton    1428: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
                   1429: @section Stack Manipulation
1.66      anton    1430: @cindex stack manipulation tutorial
1.48      anton    1431: 
                   1432: Stack manipulation words rearrange the data on the stack.
                   1433: 
                   1434: @example
                   1435: 1 .s drop .s
                   1436: 1 .s dup .s drop drop .s
                   1437: 1 2 .s over .s drop drop drop
                   1438: 1 2 .s swap .s drop drop
                   1439: 1 2 3 .s rot .s drop drop drop
                   1440: @end example
                   1441: 
                   1442: These are the most important stack manipulation words.  There are also
                   1443: variants that manipulate twice as many stack items:
                   1444: 
                   1445: @example
                   1446: 1 2 3 4 .s 2swap .s 2drop 2drop
                   1447: @end example
                   1448: 
                   1449: Two more stack manipulation words are:
                   1450: 
                   1451: @example
                   1452: 1 2 .s nip .s drop
                   1453: 1 2 .s tuck .s 2drop drop
                   1454: @end example
                   1455: 
1.141     anton    1456: @quotation Assignment
1.48      anton    1457: Replace @code{nip} and @code{tuck} with combinations of other stack
                   1458: manipulation words.
                   1459: 
                   1460: @example
                   1461: Given:          How do you get:
                   1462: 1 2 3           3 2 1           
                   1463: 1 2 3           1 2 3 2                 
                   1464: 1 2 3           1 2 3 3                 
                   1465: 1 2 3           1 3 3           
                   1466: 1 2 3           2 1 3           
                   1467: 1 2 3 4         4 3 2 1         
                   1468: 1 2 3           1 2 3 1 2 3             
                   1469: 1 2 3 4         1 2 3 4 1 2             
                   1470: 1 2 3
                   1471: 1 2 3           1 2 3 4                 
                   1472: 1 2 3           1 3             
                   1473: @end example
1.141     anton    1474: @end quotation
1.48      anton    1475: 
                   1476: @example
                   1477: 5 dup * .
                   1478: @end example
                   1479: 
1.141     anton    1480: @quotation Assignment
1.48      anton    1481: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
                   1482: Write a piece of Forth code that expects two numbers on the stack
                   1483: (@var{a} and @var{b}, with @var{b} on top) and computes
                   1484: @code{(a-b)(a+1)}.
1.141     anton    1485: @end quotation
1.48      anton    1486: 
1.66      anton    1487: Reference: @ref{Stack Manipulation}.
                   1488: 
                   1489: 
1.48      anton    1490: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
                   1491: @section Using files for Forth code
1.66      anton    1492: @cindex loading Forth code, tutorial
                   1493: @cindex files containing Forth code, tutorial
1.48      anton    1494: 
                   1495: While working at the Forth command line is convenient for one-line
                   1496: examples and short one-off code, you probably want to store your source
                   1497: code in files for convenient editing and persistence.  You can use your
                   1498: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102     anton    1499: Gforth}) to create @var{file.fs} and use
1.48      anton    1500: 
                   1501: @example
1.102     anton    1502: s" @var{file.fs}" included
1.48      anton    1503: @end example
                   1504: 
                   1505: to load it into your Forth system.  The file name extension I use for
                   1506: Forth files is @samp{.fs}.
                   1507: 
                   1508: You can easily start Gforth with some files loaded like this:
                   1509: 
                   1510: @example
1.102     anton    1511: gforth @var{file1.fs} @var{file2.fs}
1.48      anton    1512: @end example
                   1513: 
                   1514: If an error occurs during loading these files, Gforth terminates,
                   1515: whereas an error during @code{INCLUDED} within Gforth usually gives you
                   1516: a Gforth command line.  Starting the Forth system every time gives you a
                   1517: clean start every time, without interference from the results of earlier
                   1518: tries.
                   1519: 
                   1520: I often put all the tests in a file, then load the code and run the
                   1521: tests with
                   1522: 
                   1523: @example
1.102     anton    1524: gforth @var{code.fs} @var{tests.fs} -e bye
1.48      anton    1525: @end example
                   1526: 
                   1527: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
                   1528: @code{-e bye} ensures that Gforth terminates afterwards so that I can
                   1529: restart this command without ado.
                   1530: 
                   1531: The advantage of this approach is that the tests can be repeated easily
                   1532: every time the program ist changed, making it easy to catch bugs
                   1533: introduced by the change.
                   1534: 
1.66      anton    1535: Reference: @ref{Forth source files}.
                   1536: 
1.48      anton    1537: 
                   1538: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
                   1539: @section Comments
1.66      anton    1540: @cindex comments tutorial
1.48      anton    1541: 
                   1542: @example
                   1543: \ That's a comment; it ends at the end of the line
                   1544: ( Another comment; it ends here: )  .s
                   1545: @end example
                   1546: 
                   1547: @code{\} and @code{(} are ordinary Forth words and therefore have to be
                   1548: separated with white space from the following text.
                   1549: 
                   1550: @example
                   1551: \This gives an "Undefined word" error
                   1552: @end example
                   1553: 
                   1554: The first @code{)} ends a comment started with @code{(}, so you cannot
                   1555: nest @code{(}-comments; and you cannot comment out text containing a
                   1556: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
                   1557: avoid @code{)} in word names.}.
                   1558: 
                   1559: I use @code{\}-comments for descriptive text and for commenting out code
                   1560: of one or more line; I use @code{(}-comments for describing the stack
                   1561: effect, the stack contents, or for commenting out sub-line pieces of
                   1562: code.
                   1563: 
                   1564: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
                   1565: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
                   1566: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
                   1567: with @kbd{M-q}.
                   1568: 
1.66      anton    1569: Reference: @ref{Comments}.
                   1570: 
1.48      anton    1571: 
                   1572: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
                   1573: @section Colon Definitions
1.66      anton    1574: @cindex colon definitions, tutorial
                   1575: @cindex definitions, tutorial
                   1576: @cindex procedures, tutorial
                   1577: @cindex functions, tutorial
1.48      anton    1578: 
                   1579: are similar to procedures and functions in other programming languages.
                   1580: 
                   1581: @example
                   1582: : squared ( n -- n^2 )
                   1583:    dup * ;
                   1584: 5 squared .
                   1585: 7 squared .
                   1586: @end example
                   1587: 
                   1588: @code{:} starts the colon definition; its name is @code{squared}.  The
                   1589: following comment describes its stack effect.  The words @code{dup *}
                   1590: are not executed, but compiled into the definition.  @code{;} ends the
                   1591: colon definition.
                   1592: 
                   1593: The newly-defined word can be used like any other word, including using
                   1594: it in other definitions:
                   1595: 
                   1596: @example
                   1597: : cubed ( n -- n^3 )
                   1598:    dup squared * ;
                   1599: -5 cubed .
                   1600: : fourth-power ( n -- n^4 )
                   1601:    squared squared ;
                   1602: 3 fourth-power .
                   1603: @end example
                   1604: 
1.141     anton    1605: @quotation Assignment
1.48      anton    1606: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
                   1607: @code{/mod} in terms of other Forth words, and check if they work (hint:
                   1608: test your tests on the originals first).  Don't let the
                   1609: @samp{redefined}-Messages spook you, they are just warnings.
1.141     anton    1610: @end quotation
1.48      anton    1611: 
1.66      anton    1612: Reference: @ref{Colon Definitions}.
                   1613: 
1.48      anton    1614: 
                   1615: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
                   1616: @section Decompilation
1.66      anton    1617: @cindex decompilation tutorial
                   1618: @cindex see tutorial
1.48      anton    1619: 
                   1620: You can decompile colon definitions with @code{see}:
                   1621: 
                   1622: @example
                   1623: see squared
                   1624: see cubed
                   1625: @end example
                   1626: 
                   1627: In Gforth @code{see} shows you a reconstruction of the source code from
                   1628: the executable code.  Informations that were present in the source, but
                   1629: not in the executable code, are lost (e.g., comments).
                   1630: 
1.65      anton    1631: You can also decompile the predefined words:
                   1632: 
                   1633: @example
                   1634: see .
                   1635: see +
                   1636: @end example
                   1637: 
                   1638: 
1.48      anton    1639: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
                   1640: @section Stack-Effect Comments
1.66      anton    1641: @cindex stack-effect comments, tutorial
                   1642: @cindex --, tutorial
1.48      anton    1643: By convention the comment after the name of a definition describes the
1.171     anton    1644: stack effect: The part in front of the @samp{--} describes the state of
1.48      anton    1645: the stack before the execution of the definition, i.e., the parameters
                   1646: that are passed into the colon definition; the part behind the @samp{--}
                   1647: is the state of the stack after the execution of the definition, i.e.,
                   1648: the results of the definition.  The stack comment only shows the top
                   1649: stack items that the definition accesses and/or changes.
                   1650: 
                   1651: You should put a correct stack effect on every definition, even if it is
                   1652: just @code{( -- )}.  You should also add some descriptive comment to
                   1653: more complicated words (I usually do this in the lines following
                   1654: @code{:}).  If you don't do this, your code becomes unreadable (because
1.117     anton    1655: you have to work through every definition before you can understand
1.48      anton    1656: any).
                   1657: 
1.141     anton    1658: @quotation Assignment
1.48      anton    1659: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
                   1660: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
                   1661: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
1.65      anton    1662: are done, you can compare your stack effects to those in this manual
1.48      anton    1663: (@pxref{Word Index}).
1.141     anton    1664: @end quotation
1.48      anton    1665: 
                   1666: Sometimes programmers put comments at various places in colon
                   1667: definitions that describe the contents of the stack at that place (stack
                   1668: comments); i.e., they are like the first part of a stack-effect
                   1669: comment. E.g.,
                   1670: 
                   1671: @example
                   1672: : cubed ( n -- n^3 )
                   1673:    dup squared  ( n n^2 ) * ;
                   1674: @end example
                   1675: 
                   1676: In this case the stack comment is pretty superfluous, because the word
                   1677: is simple enough.  If you think it would be a good idea to add such a
                   1678: comment to increase readability, you should also consider factoring the
                   1679: word into several simpler words (@pxref{Factoring Tutorial,,
1.60      anton    1680: Factoring}), which typically eliminates the need for the stack comment;
1.48      anton    1681: however, if you decide not to refactor it, then having such a comment is
                   1682: better than not having it.
                   1683: 
                   1684: The names of the stack items in stack-effect and stack comments in the
                   1685: standard, in this manual, and in many programs specify the type through
                   1686: a type prefix, similar to Fortran and Hungarian notation.  The most
                   1687: frequent prefixes are:
                   1688: 
                   1689: @table @code
                   1690: @item n
                   1691: signed integer
                   1692: @item u
                   1693: unsigned integer
                   1694: @item c
                   1695: character
                   1696: @item f
                   1697: Boolean flags, i.e. @code{false} or @code{true}.
                   1698: @item a-addr,a-
                   1699: Cell-aligned address
                   1700: @item c-addr,c-
                   1701: Char-aligned address (note that a Char may have two bytes in Windows NT)
                   1702: @item xt
                   1703: Execution token, same size as Cell
                   1704: @item w,x
                   1705: Cell, can contain an integer or an address.  It usually takes 32, 64 or
                   1706: 16 bits (depending on your platform and Forth system). A cell is more
                   1707: commonly known as machine word, but the term @emph{word} already means
                   1708: something different in Forth.
                   1709: @item d
                   1710: signed double-cell integer
                   1711: @item ud
                   1712: unsigned double-cell integer
                   1713: @item r
                   1714: Float (on the FP stack)
                   1715: @end table
                   1716: 
                   1717: You can find a more complete list in @ref{Notation}.
                   1718: 
1.141     anton    1719: @quotation Assignment
1.48      anton    1720: Write stack-effect comments for all definitions you have written up to
                   1721: now.
1.141     anton    1722: @end quotation
1.48      anton    1723: 
                   1724: 
                   1725: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
                   1726: @section Types
1.66      anton    1727: @cindex types tutorial
1.48      anton    1728: 
                   1729: In Forth the names of the operations are not overloaded; so similar
                   1730: operations on different types need different names; e.g., @code{+} adds
                   1731: integers, and you have to use @code{f+} to add floating-point numbers.
                   1732: The following prefixes are often used for related operations on
                   1733: different types:
                   1734: 
                   1735: @table @code
                   1736: @item (none)
                   1737: signed integer
                   1738: @item u
                   1739: unsigned integer
                   1740: @item c
                   1741: character
                   1742: @item d
                   1743: signed double-cell integer
                   1744: @item ud, du
                   1745: unsigned double-cell integer
                   1746: @item 2
                   1747: two cells (not-necessarily double-cell numbers)
                   1748: @item m, um
                   1749: mixed single-cell and double-cell operations
                   1750: @item f
                   1751: floating-point (note that in stack comments @samp{f} represents flags,
1.66      anton    1752: and @samp{r} represents FP numbers).
1.48      anton    1753: @end table
                   1754: 
                   1755: If there are no differences between the signed and the unsigned variant
                   1756: (e.g., for @code{+}), there is only the prefix-less variant.
                   1757: 
                   1758: Forth does not perform type checking, neither at compile time, nor at
                   1759: run time.  If you use the wrong oeration, the data are interpreted
                   1760: incorrectly:
                   1761: 
                   1762: @example
                   1763: -1 u.
                   1764: @end example
                   1765: 
                   1766: If you have only experience with type-checked languages until now, and
                   1767: have heard how important type-checking is, don't panic!  In my
                   1768: experience (and that of other Forthers), type errors in Forth code are
                   1769: usually easy to find (once you get used to it), the increased vigilance
                   1770: of the programmer tends to catch some harder errors in addition to most
                   1771: type errors, and you never have to work around the type system, so in
                   1772: most situations the lack of type-checking seems to be a win (projects to
                   1773: add type checking to Forth have not caught on).
                   1774: 
                   1775: 
                   1776: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
                   1777: @section Factoring
1.66      anton    1778: @cindex factoring tutorial
1.48      anton    1779: 
                   1780: If you try to write longer definitions, you will soon find it hard to
                   1781: keep track of the stack contents.  Therefore, good Forth programmers
                   1782: tend to write only short definitions (e.g., three lines).  The art of
                   1783: finding meaningful short definitions is known as factoring (as in
                   1784: factoring polynomials).
                   1785: 
                   1786: Well-factored programs offer additional advantages: smaller, more
                   1787: general words, are easier to test and debug and can be reused more and
                   1788: better than larger, specialized words.
                   1789: 
                   1790: So, if you run into difficulties with stack management, when writing
                   1791: code, try to define meaningful factors for the word, and define the word
                   1792: in terms of those.  Even if a factor contains only two words, it is
                   1793: often helpful.
                   1794: 
1.65      anton    1795: Good factoring is not easy, and it takes some practice to get the knack
                   1796: for it; but even experienced Forth programmers often don't find the
                   1797: right solution right away, but only when rewriting the program.  So, if
                   1798: you don't come up with a good solution immediately, keep trying, don't
                   1799: despair.
1.48      anton    1800: 
                   1801: @c example !!
                   1802: 
                   1803: 
                   1804: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
                   1805: @section Designing the stack effect
1.66      anton    1806: @cindex Stack effect design, tutorial
                   1807: @cindex design of stack effects, tutorial
1.48      anton    1808: 
                   1809: In other languages you can use an arbitrary order of parameters for a
1.65      anton    1810: function; and since there is only one result, you don't have to deal with
1.48      anton    1811: the order of results, either.
                   1812: 
1.117     anton    1813: In Forth (and other stack-based languages, e.g., PostScript) the
1.48      anton    1814: parameter and result order of a definition is important and should be
                   1815: designed well.  The general guideline is to design the stack effect such
                   1816: that the word is simple to use in most cases, even if that complicates
                   1817: the implementation of the word.  Some concrete rules are:
                   1818: 
                   1819: @itemize @bullet
                   1820: 
                   1821: @item
                   1822: Words consume all of their parameters (e.g., @code{.}).
                   1823: 
                   1824: @item
                   1825: If there is a convention on the order of parameters (e.g., from
                   1826: mathematics or another programming language), stick with it (e.g.,
                   1827: @code{-}).
                   1828: 
                   1829: @item
                   1830: If one parameter usually requires only a short computation (e.g., it is
                   1831: a constant), pass it on the top of the stack.  Conversely, parameters
                   1832: that usually require a long sequence of code to compute should be passed
                   1833: as the bottom (i.e., first) parameter.  This makes the code easier to
1.171     anton    1834: read, because the reader does not need to keep track of the bottom item
1.48      anton    1835: through a long sequence of code (or, alternatively, through stack
1.49      anton    1836: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48      anton    1837: address on top of the stack because it is usually simpler to compute
                   1838: than the stored value (often the address is just a variable).
                   1839: 
                   1840: @item
                   1841: Similarly, results that are usually consumed quickly should be returned
                   1842: on the top of stack, whereas a result that is often used in long
                   1843: computations should be passed as bottom result.  E.g., the file words
                   1844: like @code{open-file} return the error code on the top of stack, because
                   1845: it is usually consumed quickly by @code{throw}; moreover, the error code
                   1846: has to be checked before doing anything with the other results.
                   1847: 
                   1848: @end itemize
                   1849: 
                   1850: These rules are just general guidelines, don't lose sight of the overall
                   1851: goal to make the words easy to use.  E.g., if the convention rule
                   1852: conflicts with the computation-length rule, you might decide in favour
                   1853: of the convention if the word will be used rarely, and in favour of the
                   1854: computation-length rule if the word will be used frequently (because
                   1855: with frequent use the cost of breaking the computation-length rule would
                   1856: be quite high, and frequent use makes it easier to remember an
                   1857: unconventional order).
                   1858: 
                   1859: @c example !! structure package
                   1860: 
1.65      anton    1861: 
1.48      anton    1862: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
                   1863: @section Local Variables
1.66      anton    1864: @cindex local variables, tutorial
1.48      anton    1865: 
                   1866: You can define local variables (@emph{locals}) in a colon definition:
                   1867: 
                   1868: @example
                   1869: : swap @{ a b -- b a @}
                   1870:   b a ;
                   1871: 1 2 swap .s 2drop
                   1872: @end example
                   1873: 
                   1874: (If your Forth system does not support this syntax, include
1.187     anton    1875: @file{compat/anslocal.fs} first).
1.48      anton    1876: 
                   1877: In this example @code{@{ a b -- b a @}} is the locals definition; it
                   1878: takes two cells from the stack, puts the top of stack in @code{b} and
                   1879: the next stack element in @code{a}.  @code{--} starts a comment ending
                   1880: with @code{@}}.  After the locals definition, using the name of the
                   1881: local will push its value on the stack.  You can leave the comment
                   1882: part (@code{-- b a}) away:
                   1883: 
                   1884: @example
                   1885: : swap ( x1 x2 -- x2 x1 )
                   1886:   @{ a b @} b a ;
                   1887: @end example
                   1888: 
                   1889: In Gforth you can have several locals definitions, anywhere in a colon
                   1890: definition; in contrast, in a standard program you can have only one
                   1891: locals definition per colon definition, and that locals definition must
1.163     anton    1892: be outside any control structure.
1.48      anton    1893: 
                   1894: With locals you can write slightly longer definitions without running
                   1895: into stack trouble.  However, I recommend trying to write colon
                   1896: definitions without locals for exercise purposes to help you gain the
                   1897: essential factoring skills.
                   1898: 
1.141     anton    1899: @quotation Assignment
1.48      anton    1900: Rewrite your definitions until now with locals
1.141     anton    1901: @end quotation
1.48      anton    1902: 
1.66      anton    1903: Reference: @ref{Locals}.
                   1904: 
1.48      anton    1905: 
                   1906: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
                   1907: @section Conditional execution
1.66      anton    1908: @cindex conditionals, tutorial
                   1909: @cindex if, tutorial
1.48      anton    1910: 
                   1911: In Forth you can use control structures only inside colon definitions.
                   1912: An @code{if}-structure looks like this:
                   1913: 
                   1914: @example
                   1915: : abs ( n1 -- +n2 )
                   1916:     dup 0 < if
                   1917:         negate
                   1918:     endif ;
                   1919: 5 abs .
                   1920: -5 abs .
                   1921: @end example
                   1922: 
                   1923: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
                   1924: the following code is performed, otherwise execution continues after the
1.51      pazsan   1925: @code{endif} (or @code{else}).  @code{<} compares the top two stack
1.171     anton    1926: elements and produces a flag:
1.48      anton    1927: 
                   1928: @example
                   1929: 1 2 < .
                   1930: 2 1 < .
                   1931: 1 1 < .
                   1932: @end example
                   1933: 
                   1934: Actually the standard name for @code{endif} is @code{then}.  This
                   1935: tutorial presents the examples using @code{endif}, because this is often
                   1936: less confusing for people familiar with other programming languages
                   1937: where @code{then} has a different meaning.  If your system does not have
                   1938: @code{endif}, define it with
                   1939: 
                   1940: @example
                   1941: : endif postpone then ; immediate
                   1942: @end example
                   1943: 
                   1944: You can optionally use an @code{else}-part:
                   1945: 
                   1946: @example
                   1947: : min ( n1 n2 -- n )
                   1948:   2dup < if
                   1949:     drop
                   1950:   else
                   1951:     nip
                   1952:   endif ;
                   1953: 2 3 min .
                   1954: 3 2 min .
                   1955: @end example
                   1956: 
1.141     anton    1957: @quotation Assignment
1.48      anton    1958: Write @code{min} without @code{else}-part (hint: what's the definition
                   1959: of @code{nip}?).
1.141     anton    1960: @end quotation
1.48      anton    1961: 
1.66      anton    1962: Reference: @ref{Selection}.
                   1963: 
1.48      anton    1964: 
                   1965: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
                   1966: @section Flags and Comparisons
1.66      anton    1967: @cindex flags tutorial
                   1968: @cindex comparison tutorial
1.48      anton    1969: 
                   1970: In a false-flag all bits are clear (0 when interpreted as integer).  In
                   1971: a canonical true-flag all bits are set (-1 as a twos-complement signed
                   1972: integer); in many contexts (e.g., @code{if}) any non-zero value is
                   1973: treated as true flag.
                   1974: 
                   1975: @example
                   1976: false .
                   1977: true .
                   1978: true hex u. decimal
                   1979: @end example
                   1980: 
                   1981: Comparison words produce canonical flags:
                   1982: 
                   1983: @example
                   1984: 1 1 = .
                   1985: 1 0= .
                   1986: 0 1 < .
                   1987: 0 0 < .
                   1988: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
                   1989: -1 1 < .
                   1990: @end example
                   1991: 
1.66      anton    1992: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
                   1993: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
                   1994: these combinations are standard (for details see the standard,
                   1995: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48      anton    1996: 
1.171     anton    1997: You can use @code{and or xor invert} as operations on canonical flags.
                   1998: Actually they are bitwise operations:
1.48      anton    1999: 
                   2000: @example
                   2001: 1 2 and .
                   2002: 1 2 or .
                   2003: 1 3 xor .
                   2004: 1 invert .
                   2005: @end example
                   2006: 
                   2007: You can convert a zero/non-zero flag into a canonical flag with
                   2008: @code{0<>} (and complement it on the way with @code{0=}).
                   2009: 
                   2010: @example
                   2011: 1 0= .
                   2012: 1 0<> .
                   2013: @end example
                   2014: 
1.65      anton    2015: You can use the all-bits-set feature of canonical flags and the bitwise
1.48      anton    2016: operation of the Boolean operations to avoid @code{if}s:
                   2017: 
                   2018: @example
                   2019: : foo ( n1 -- n2 )
                   2020:   0= if
                   2021:     14
                   2022:   else
                   2023:     0
                   2024:   endif ;
                   2025: 0 foo .
                   2026: 1 foo .
                   2027: 
                   2028: : foo ( n1 -- n2 )
                   2029:   0= 14 and ;
                   2030: 0 foo .
                   2031: 1 foo .
                   2032: @end example
                   2033: 
1.141     anton    2034: @quotation Assignment
1.48      anton    2035: Write @code{min} without @code{if}.
1.141     anton    2036: @end quotation
1.48      anton    2037: 
1.66      anton    2038: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
                   2039: @ref{Bitwise operations}.
                   2040: 
1.48      anton    2041: 
                   2042: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
                   2043: @section General Loops
1.66      anton    2044: @cindex loops, indefinite, tutorial
1.48      anton    2045: 
                   2046: The endless loop is the most simple one:
                   2047: 
                   2048: @example
                   2049: : endless ( -- )
                   2050:   0 begin
                   2051:     dup . 1+
                   2052:   again ;
                   2053: endless
                   2054: @end example
                   2055: 
                   2056: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
                   2057: does nothing at run-time, @code{again} jumps back to @code{begin}.
                   2058: 
                   2059: A loop with one exit at any place looks like this:
                   2060: 
                   2061: @example
                   2062: : log2 ( +n1 -- n2 )
                   2063: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2064:   assert( dup 0> )
                   2065:   2/ 0 begin
                   2066:     over 0> while
                   2067:       1+ swap 2/ swap
                   2068:   repeat
                   2069:   nip ;
                   2070: 7 log2 .
                   2071: 8 log2 .
                   2072: @end example
                   2073: 
                   2074: At run-time @code{while} consumes a flag; if it is 0, execution
1.51      pazsan   2075: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48      anton    2076: continues behind the @code{while}.  @code{Repeat} jumps back to
                   2077: @code{begin}, just like @code{again}.
                   2078: 
                   2079: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90      anton    2080: However, @code{2/} is not one of them; it shifts its argument right by
1.48      anton    2081: one bit (arithmetic shift right):
                   2082: 
                   2083: @example
                   2084: -5 2 / .
                   2085: -5 2/ .
                   2086: @end example
                   2087: 
                   2088: @code{assert(} is no standard word, but you can get it on systems other
1.198     anton    2089: than Gforth by including @file{compat/assert.fs}.  You can see what it
1.48      anton    2090: does by trying
                   2091: 
                   2092: @example
                   2093: 0 log2 .
                   2094: @end example
                   2095: 
                   2096: Here's a loop with an exit at the end:
                   2097: 
                   2098: @example
                   2099: : log2 ( +n1 -- n2 )
                   2100: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2101:   assert( dup 0 > )
                   2102:   -1 begin
                   2103:     1+ swap 2/ swap
                   2104:     over 0 <=
                   2105:   until
                   2106:   nip ;
                   2107: @end example
                   2108: 
                   2109: @code{Until} consumes a flag; if it is non-zero, execution continues at
                   2110: the @code{begin}, otherwise after the @code{until}.
                   2111: 
1.141     anton    2112: @quotation Assignment
1.48      anton    2113: Write a definition for computing the greatest common divisor.
1.141     anton    2114: @end quotation
1.48      anton    2115: 
1.66      anton    2116: Reference: @ref{Simple Loops}.
                   2117: 
1.48      anton    2118: 
                   2119: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
                   2120: @section Counted loops
1.66      anton    2121: @cindex loops, counted, tutorial
1.48      anton    2122: 
                   2123: @example
                   2124: : ^ ( n1 u -- n )
1.171     anton    2125: \ n = the uth power of n1
1.48      anton    2126:   1 swap 0 u+do
                   2127:     over *
                   2128:   loop
                   2129:   nip ;
                   2130: 3 2 ^ .
                   2131: 4 3 ^ .
                   2132: @end example
                   2133: 
                   2134: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
                   2135: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
                   2136: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
                   2137: times (or not at all, if @code{u3-u4<0}).
                   2138: 
                   2139: You can see the stack effect design rules at work in the stack effect of
                   2140: the loop start words: Since the start value of the loop is more
                   2141: frequently constant than the end value, the start value is passed on
                   2142: the top-of-stack.
                   2143: 
                   2144: You can access the counter of a counted loop with @code{i}:
                   2145: 
                   2146: @example
                   2147: : fac ( u -- u! )
                   2148:   1 swap 1+ 1 u+do
                   2149:     i *
                   2150:   loop ;
                   2151: 5 fac .
                   2152: 7 fac .
                   2153: @end example
                   2154: 
                   2155: There is also @code{+do}, which expects signed numbers (important for
                   2156: deciding whether to enter the loop).
                   2157: 
1.141     anton    2158: @quotation Assignment
1.48      anton    2159: Write a definition for computing the nth Fibonacci number.
1.141     anton    2160: @end quotation
1.48      anton    2161: 
1.65      anton    2162: You can also use increments other than 1:
                   2163: 
                   2164: @example
                   2165: : up2 ( n1 n2 -- )
                   2166:   +do
                   2167:     i .
                   2168:   2 +loop ;
                   2169: 10 0 up2
                   2170: 
                   2171: : down2 ( n1 n2 -- )
                   2172:   -do
                   2173:     i .
                   2174:   2 -loop ;
                   2175: 0 10 down2
                   2176: @end example
1.48      anton    2177: 
1.66      anton    2178: Reference: @ref{Counted Loops}.
                   2179: 
1.48      anton    2180: 
                   2181: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
                   2182: @section Recursion
1.66      anton    2183: @cindex recursion tutorial
1.48      anton    2184: 
                   2185: Usually the name of a definition is not visible in the definition; but
                   2186: earlier definitions are usually visible:
                   2187: 
                   2188: @example
1.166     anton    2189: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
1.48      anton    2190: : / ( n1 n2 -- n )
                   2191:   dup 0= if
                   2192:     -10 throw \ report division by zero
                   2193:   endif
                   2194:   /           \ old version
                   2195: ;
                   2196: 1 0 /
                   2197: @end example
                   2198: 
                   2199: For recursive definitions you can use @code{recursive} (non-standard) or
                   2200: @code{recurse}:
                   2201: 
                   2202: @example
                   2203: : fac1 ( n -- n! ) recursive
                   2204:  dup 0> if
                   2205:    dup 1- fac1 *
                   2206:  else
                   2207:    drop 1
                   2208:  endif ;
                   2209: 7 fac1 .
                   2210: 
                   2211: : fac2 ( n -- n! )
                   2212:  dup 0> if
                   2213:    dup 1- recurse *
                   2214:  else
                   2215:    drop 1
                   2216:  endif ;
                   2217: 8 fac2 .
                   2218: @end example
                   2219: 
1.141     anton    2220: @quotation Assignment
1.48      anton    2221: Write a recursive definition for computing the nth Fibonacci number.
1.141     anton    2222: @end quotation
1.48      anton    2223: 
1.66      anton    2224: Reference (including indirect recursion): @xref{Calls and returns}.
                   2225: 
1.48      anton    2226: 
                   2227: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
                   2228: @section Leaving definitions or loops
1.66      anton    2229: @cindex leaving definitions, tutorial
                   2230: @cindex leaving loops, tutorial
1.48      anton    2231: 
                   2232: @code{EXIT} exits the current definition right away.  For every counted
                   2233: loop that is left in this way, an @code{UNLOOP} has to be performed
                   2234: before the @code{EXIT}:
                   2235: 
                   2236: @c !! real examples
                   2237: @example
                   2238: : ...
                   2239:  ... u+do
                   2240:    ... if
                   2241:      ... unloop exit
                   2242:    endif
                   2243:    ...
                   2244:  loop
                   2245:  ... ;
                   2246: @end example
                   2247: 
                   2248: @code{LEAVE} leaves the innermost counted loop right away:
                   2249: 
                   2250: @example
                   2251: : ...
                   2252:  ... u+do
                   2253:    ... if
                   2254:      ... leave
                   2255:    endif
                   2256:    ...
                   2257:  loop
                   2258:  ... ;
                   2259: @end example
                   2260: 
1.65      anton    2261: @c !! example
1.48      anton    2262: 
1.66      anton    2263: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
                   2264: 
                   2265: 
1.48      anton    2266: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
                   2267: @section Return Stack
1.66      anton    2268: @cindex return stack tutorial
1.48      anton    2269: 
                   2270: In addition to the data stack Forth also has a second stack, the return
                   2271: stack; most Forth systems store the return addresses of procedure calls
                   2272: there (thus its name).  Programmers can also use this stack:
                   2273: 
                   2274: @example
                   2275: : foo ( n1 n2 -- )
                   2276:  .s
                   2277:  >r .s
1.50      anton    2278:  r@@ .
1.48      anton    2279:  >r .s
1.50      anton    2280:  r@@ .
1.48      anton    2281:  r> .
1.50      anton    2282:  r@@ .
1.48      anton    2283:  r> . ;
                   2284: 1 2 foo
                   2285: @end example
                   2286: 
                   2287: @code{>r} takes an element from the data stack and pushes it onto the
                   2288: return stack; conversely, @code{r>} moves an elementm from the return to
                   2289: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148     anton    2290: on the data stack.
1.48      anton    2291: 
                   2292: Forth programmers usually use the return stack for storing data
                   2293: temporarily, if using the data stack alone would be too complex, and
                   2294: factoring and locals are not an option:
                   2295: 
                   2296: @example
                   2297: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
                   2298:  rot >r rot r> ;
                   2299: @end example
                   2300: 
                   2301: The return address of the definition and the loop control parameters of
                   2302: counted loops usually reside on the return stack, so you have to take
                   2303: all items, that you have pushed on the return stack in a colon
                   2304: definition or counted loop, from the return stack before the definition
                   2305: or loop ends.  You cannot access items that you pushed on the return
                   2306: stack outside some definition or loop within the definition of loop.
                   2307: 
                   2308: If you miscount the return stack items, this usually ends in a crash:
                   2309: 
                   2310: @example
                   2311: : crash ( n -- )
                   2312:   >r ;
                   2313: 5 crash
                   2314: @end example
                   2315: 
                   2316: You cannot mix using locals and using the return stack (according to the
                   2317: standard; Gforth has no problem).  However, they solve the same
                   2318: problems, so this shouldn't be an issue.
                   2319: 
1.141     anton    2320: @quotation Assignment
1.48      anton    2321: Can you rewrite any of the definitions you wrote until now in a better
                   2322: way using the return stack?
1.141     anton    2323: @end quotation
1.48      anton    2324: 
1.66      anton    2325: Reference: @ref{Return stack}.
                   2326: 
1.48      anton    2327: 
                   2328: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
                   2329: @section Memory
1.66      anton    2330: @cindex memory access/allocation tutorial
1.48      anton    2331: 
                   2332: You can create a global variable @code{v} with
                   2333: 
                   2334: @example
                   2335: variable v ( -- addr )
                   2336: @end example
                   2337: 
                   2338: @code{v} pushes the address of a cell in memory on the stack.  This cell
                   2339: was reserved by @code{variable}.  You can use @code{!} (store) to store
                   2340: values into this cell and @code{@@} (fetch) to load the value from the
                   2341: stack into memory:
                   2342: 
                   2343: @example
                   2344: v .
                   2345: 5 v ! .s
1.50      anton    2346: v @@ .
1.48      anton    2347: @end example
                   2348: 
1.65      anton    2349: You can see a raw dump of memory with @code{dump}:
                   2350: 
                   2351: @example
                   2352: v 1 cells .s dump
                   2353: @end example
                   2354: 
                   2355: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
                   2356: generally, address units (aus)) that @code{n1 cells} occupy.  You can
                   2357: also reserve more memory:
1.48      anton    2358: 
                   2359: @example
                   2360: create v2 20 cells allot
1.65      anton    2361: v2 20 cells dump
1.48      anton    2362: @end example
                   2363: 
1.65      anton    2364: creates a word @code{v2} and reserves 20 uninitialized cells; the
                   2365: address pushed by @code{v2} points to the start of these 20 cells.  You
                   2366: can use address arithmetic to access these cells:
1.48      anton    2367: 
                   2368: @example
                   2369: 3 v2 5 cells + !
1.65      anton    2370: v2 20 cells dump
1.48      anton    2371: @end example
                   2372: 
                   2373: You can reserve and initialize memory with @code{,}:
                   2374: 
                   2375: @example
                   2376: create v3
                   2377:   5 , 4 , 3 , 2 , 1 ,
1.50      anton    2378: v3 @@ .
                   2379: v3 cell+ @@ .
                   2380: v3 2 cells + @@ .
1.65      anton    2381: v3 5 cells dump
1.48      anton    2382: @end example
                   2383: 
1.141     anton    2384: @quotation Assignment
1.48      anton    2385: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
                   2386: @code{u} cells, with the first of these cells at @code{addr}, the next
                   2387: one at @code{addr cell+} etc.
1.141     anton    2388: @end quotation
1.48      anton    2389: 
                   2390: You can also reserve memory without creating a new word:
                   2391: 
                   2392: @example
1.60      anton    2393: here 10 cells allot .
                   2394: here .
1.48      anton    2395: @end example
                   2396: 
                   2397: @code{Here} pushes the start address of the memory area.  You should
                   2398: store it somewhere, or you will have a hard time finding the memory area
                   2399: again.
                   2400: 
                   2401: @code{Allot} manages dictionary memory.  The dictionary memory contains
                   2402: the system's data structures for words etc. on Gforth and most other
                   2403: Forth systems.  It is managed like a stack: You can free the memory that
                   2404: you have just @code{allot}ed with
                   2405: 
                   2406: @example
                   2407: -10 cells allot
1.60      anton    2408: here .
1.48      anton    2409: @end example
                   2410: 
                   2411: Note that you cannot do this if you have created a new word in the
                   2412: meantime (because then your @code{allot}ed memory is no longer on the
                   2413: top of the dictionary ``stack'').
                   2414: 
                   2415: Alternatively, you can use @code{allocate} and @code{free} which allow
                   2416: freeing memory in any order:
                   2417: 
                   2418: @example
                   2419: 10 cells allocate throw .s
                   2420: 20 cells allocate throw .s
                   2421: swap
                   2422: free throw
                   2423: free throw
                   2424: @end example
                   2425: 
                   2426: The @code{throw}s deal with errors (e.g., out of memory).
                   2427: 
1.65      anton    2428: And there is also a
                   2429: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   2430: garbage collector}, which eliminates the need to @code{free} memory
                   2431: explicitly.
1.48      anton    2432: 
1.66      anton    2433: Reference: @ref{Memory}.
                   2434: 
1.48      anton    2435: 
                   2436: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
                   2437: @section Characters and Strings
1.66      anton    2438: @cindex strings tutorial
                   2439: @cindex characters tutorial
1.48      anton    2440: 
                   2441: On the stack characters take up a cell, like numbers.  In memory they
                   2442: have their own size (one 8-bit byte on most systems), and therefore
                   2443: require their own words for memory access:
                   2444: 
                   2445: @example
                   2446: create v4 
                   2447:   104 c, 97 c, 108 c, 108 c, 111 c,
1.50      anton    2448: v4 4 chars + c@@ .
1.65      anton    2449: v4 5 chars dump
1.48      anton    2450: @end example
                   2451: 
                   2452: The preferred representation of strings on the stack is @code{addr
                   2453: u-count}, where @code{addr} is the address of the first character and
                   2454: @code{u-count} is the number of characters in the string.
                   2455: 
                   2456: @example
                   2457: v4 5 type
                   2458: @end example
                   2459: 
                   2460: You get a string constant with
                   2461: 
                   2462: @example
                   2463: s" hello, world" .s
                   2464: type
                   2465: @end example
                   2466: 
                   2467: Make sure you have a space between @code{s"} and the string; @code{s"}
                   2468: is a normal Forth word and must be delimited with white space (try what
                   2469: happens when you remove the space).
                   2470: 
                   2471: However, this interpretive use of @code{s"} is quite restricted: the
                   2472: string exists only until the next call of @code{s"} (some Forth systems
                   2473: keep more than one of these strings, but usually they still have a
1.62      crook    2474: limited lifetime).
1.48      anton    2475: 
                   2476: @example
                   2477: s" hello," s" world" .s
                   2478: type
                   2479: type
                   2480: @end example
                   2481: 
1.62      crook    2482: You can also use @code{s"} in a definition, and the resulting
                   2483: strings then live forever (well, for as long as the definition):
1.48      anton    2484: 
                   2485: @example
                   2486: : foo s" hello," s" world" ;
                   2487: foo .s
                   2488: type
                   2489: type
                   2490: @end example
                   2491: 
1.141     anton    2492: @quotation Assignment
1.48      anton    2493: @code{Emit ( c -- )} types @code{c} as character (not a number).
                   2494: Implement @code{type ( addr u -- )}.
1.141     anton    2495: @end quotation
1.48      anton    2496: 
1.66      anton    2497: Reference: @ref{Memory Blocks}.
                   2498: 
                   2499: 
1.190     anton    2500: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
1.48      anton    2501: @section Alignment
1.66      anton    2502: @cindex alignment tutorial
                   2503: @cindex memory alignment tutorial
1.48      anton    2504: 
                   2505: On many processors cells have to be aligned in memory, if you want to
                   2506: access them with @code{@@} and @code{!} (and even if the processor does
1.62      crook    2507: not require alignment, access to aligned cells is faster).
1.48      anton    2508: 
                   2509: @code{Create} aligns @code{here} (i.e., the place where the next
                   2510: allocation will occur, and that the @code{create}d word points to).
                   2511: Likewise, the memory produced by @code{allocate} starts at an aligned
                   2512: address.  Adding a number of @code{cells} to an aligned address produces
                   2513: another aligned address.
                   2514: 
                   2515: However, address arithmetic involving @code{char+} and @code{chars} can
                   2516: create an address that is not cell-aligned.  @code{Aligned ( addr --
                   2517: a-addr )} produces the next aligned address:
                   2518: 
                   2519: @example
1.50      anton    2520: v3 char+ aligned .s @@ .
                   2521: v3 char+ .s @@ .
1.48      anton    2522: @end example
                   2523: 
                   2524: Similarly, @code{align} advances @code{here} to the next aligned
                   2525: address:
                   2526: 
                   2527: @example
                   2528: create v5 97 c,
                   2529: here .
                   2530: align here .
                   2531: 1000 ,
                   2532: @end example
                   2533: 
                   2534: Note that you should use aligned addresses even if your processor does
                   2535: not require them, if you want your program to be portable.
                   2536: 
1.66      anton    2537: Reference: @ref{Address arithmetic}.
                   2538: 
1.190     anton    2539: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
                   2540: @section Floating Point
                   2541: @cindex floating point tutorial
                   2542: @cindex FP tutorial
                   2543: 
                   2544: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
                   2545: might expect, but there are a few things worth noting:
                   2546: 
                   2547: The first point is not specific to Forth, but so important and yet not
                   2548: universally known that I mention it here: FP numbers are not reals.
                   2549: Many properties (e.g., arithmetic laws) that reals have and that one
                   2550: expects of all kinds of numbers do not hold for FP numbers.  If you
                   2551: want to use FP computations, you should learn about their problems and
                   2552: how to avoid them; a good starting point is @cite{David Goldberg,
                   2553: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
                   2554: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
                   2555: Computing Surveys 23(1):5@minus{}48, March 1991}.
                   2556: 
                   2557: In Forth source code literal FP numbers need an exponent, e.g.,
                   2558: @code{1e0}; this can also be written shorter as @code{1e},
                   2559: @code{+1.0e+0}, and many variations in between.  The reason for this
                   2560: is that, for historical reasons, Forth interprets a decimal point
                   2561: alone (e.g., @code{1.}) as indicating a double-cell integer.  Another
                   2562: requirement for literal FP numbers is that the current base is
                   2563: decimal; with a hex base @code{1e} is interpreted as an integer.
                   2564: 
                   2565: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
                   2566: ANS Forth system may implement the FP stack on the data stack, but
                   2567: virtually all systems implement a separate FP stack; and programming
                   2568: in a way that accommodates all models is so cumbersome that nobody
                   2569: does it.}  One advantage of this model is that cells are not in the
                   2570: way when accessing FP values, and vice versa.  Forth has a set of
                   2571: words for manipulating the FP stack: @code{fdup fswap fdrop fover
                   2572: frot} and (non-standard) @code{fnip ftuck fpick}.
                   2573: 
                   2574: FP arithmetic words are prefixed with @code{F}.  There is the usual
                   2575: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
                   2576: other functions, e.g., @code{fsqrt fsin fln fmin}.  One word that you
                   2577: might expect is @code{f=}; but @code{f=} is non-standard, because FP
                   2578: computation results are usually inaccurate, so exact comparison is
                   2579: usually a mistake, and one should use approximate comparison.
                   2580: Unfortunately, @code{f~}, the standard word for that purpose, is not
                   2581: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
                   2582: well.
                   2583: 
                   2584: And of course there are words for accessing FP numbers in memory
                   2585: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
                   2586: faligned}).  There are also variants of these words with an @code{sf}
                   2587: and @code{df} prefix for accessing IEEE format single-precision and
                   2588: double-precision numbers in memory; their main purpose is for
                   2589: accessing external FP data (e.g., that has been read from or will be
                   2590: written to a file).
                   2591: 
                   2592: Here is an example of a dot-product word and its use:
                   2593: 
                   2594: @example
                   2595: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   2596:   >r swap 2swap swap 0e r> 0 ?DO
                   2597:     dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
                   2598:   LOOP
                   2599:   2drop 2drop ;
1.48      anton    2600: 
1.190     anton    2601: create v 1.23e f, 4.56e f, 7.89e f,
                   2602: 
                   2603: v 1 floats  v 1 floats  3  v* f.
                   2604: @end example
                   2605: 
                   2606: @quotation Assignment
                   2607: Write a program to solve a quadratic equation.  Then read @cite{Henry
                   2608: G. Baker,
                   2609: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
                   2610: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
                   2611: 33(1):30@minus{}39, January 1998}, and see if you can improve your
                   2612: program.  Finally, find a test case where the original and the
                   2613: improved version produce different results.
                   2614: @end quotation
                   2615: 
                   2616: Reference: @ref{Floating Point}; @ref{Floating point stack};
                   2617: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
                   2618: arithmetic}.
                   2619: 
                   2620: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
1.84      pazsan   2621: @section Files
                   2622: @cindex files tutorial
                   2623: 
                   2624: This section gives a short introduction into how to use files inside
                   2625: Forth. It's broken up into five easy steps:
                   2626: 
                   2627: @enumerate 1
                   2628: @item Opened an ASCII text file for input
                   2629: @item Opened a file for output
                   2630: @item Read input file until string matched (or some other condition matched)
                   2631: @item Wrote some lines from input ( modified or not) to output
                   2632: @item Closed the files.
                   2633: @end enumerate
                   2634: 
1.153     anton    2635: Reference: @ref{General files}.
                   2636: 
1.84      pazsan   2637: @subsection Open file for input
                   2638: 
                   2639: @example
                   2640: s" foo.in"  r/o open-file throw Value fd-in
                   2641: @end example
                   2642: 
                   2643: @subsection Create file for output
                   2644: 
                   2645: @example
                   2646: s" foo.out" w/o create-file throw Value fd-out
                   2647: @end example
                   2648: 
                   2649: The available file modes are r/o for read-only access, r/w for
                   2650: read-write access, and w/o for write-only access. You could open both
                   2651: files with r/w, too, if you like. All file words return error codes; for
                   2652: most applications, it's best to pass there error codes with @code{throw}
                   2653: to the outer error handler.
                   2654: 
                   2655: If you want words for opening and assigning, define them as follows:
                   2656: 
                   2657: @example
                   2658: 0 Value fd-in
                   2659: 0 Value fd-out
                   2660: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
                   2661: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
                   2662: @end example
                   2663: 
                   2664: Usage example:
                   2665: 
                   2666: @example
                   2667: s" foo.in" open-input
                   2668: s" foo.out" open-output
                   2669: @end example
                   2670: 
                   2671: @subsection Scan file for a particular line
                   2672: 
                   2673: @example
                   2674: 256 Constant max-line
                   2675: Create line-buffer  max-line 2 + allot
                   2676: 
                   2677: : scan-file ( addr u -- )
                   2678:   begin
                   2679:       line-buffer max-line fd-in read-line throw
                   2680:   while
                   2681:          >r 2dup line-buffer r> compare 0=
                   2682:      until
                   2683:   else
                   2684:      drop
                   2685:   then
                   2686:   2drop ;
                   2687: @end example
                   2688: 
                   2689: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94      anton    2690: the buffer at addr, and returns the number of bytes read, a flag that is
                   2691: false when the end of file is reached, and an error code.
1.84      pazsan   2692: 
                   2693: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
                   2694: returns zero if both strings are equal. It returns a positive number if
                   2695: the first string is lexically greater, a negative if the second string
                   2696: is lexically greater.
                   2697: 
                   2698: We haven't seen this loop here; it has two exits. Since the @code{while}
                   2699: exits with the number of bytes read on the stack, we have to clean up
                   2700: that separately; that's after the @code{else}.
                   2701: 
                   2702: Usage example:
                   2703: 
                   2704: @example
                   2705: s" The text I search is here" scan-file
                   2706: @end example
                   2707: 
                   2708: @subsection Copy input to output
                   2709: 
                   2710: @example
                   2711: : copy-file ( -- )
                   2712:   begin
                   2713:       line-buffer max-line fd-in read-line throw
                   2714:   while
1.194     anton    2715:       line-buffer swap fd-out write-line throw
1.84      pazsan   2716:   repeat ;
                   2717: @end example
1.194     anton    2718: @c !! does not handle long lines, no newline at end of file
1.84      pazsan   2719: 
                   2720: @subsection Close files
                   2721: 
                   2722: @example
                   2723: fd-in close-file throw
                   2724: fd-out close-file throw
                   2725: @end example
                   2726: 
                   2727: Likewise, you can put that into definitions, too:
                   2728: 
                   2729: @example
                   2730: : close-input ( -- )  fd-in close-file throw ;
                   2731: : close-output ( -- )  fd-out close-file throw ;
                   2732: @end example
                   2733: 
1.141     anton    2734: @quotation Assignment
1.84      pazsan   2735: How could you modify @code{copy-file} so that it copies until a second line is
                   2736: matched? Can you write a program that extracts a section of a text file,
                   2737: given the line that starts and the line that terminates that section?
1.141     anton    2738: @end quotation
1.84      pazsan   2739: 
                   2740: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48      anton    2741: @section Interpretation and Compilation Semantics and Immediacy
1.66      anton    2742: @cindex semantics tutorial
                   2743: @cindex interpretation semantics tutorial
                   2744: @cindex compilation semantics tutorial
                   2745: @cindex immediate, tutorial
1.48      anton    2746: 
                   2747: When a word is compiled, it behaves differently from being interpreted.
                   2748: E.g., consider @code{+}:
                   2749: 
                   2750: @example
                   2751: 1 2 + .
                   2752: : foo + ;
                   2753: @end example
                   2754: 
                   2755: These two behaviours are known as compilation and interpretation
                   2756: semantics.  For normal words (e.g., @code{+}), the compilation semantics
                   2757: is to append the interpretation semantics to the currently defined word
                   2758: (@code{foo} in the example above).  I.e., when @code{foo} is executed
                   2759: later, the interpretation semantics of @code{+} (i.e., adding two
                   2760: numbers) will be performed.
                   2761: 
                   2762: However, there are words with non-default compilation semantics, e.g.,
                   2763: the control-flow words like @code{if}.  You can use @code{immediate} to
                   2764: change the compilation semantics of the last defined word to be equal to
                   2765: the interpretation semantics:
                   2766: 
                   2767: @example
                   2768: : [FOO] ( -- )
                   2769:  5 . ; immediate
                   2770: 
                   2771: [FOO]
                   2772: : bar ( -- )
                   2773:   [FOO] ;
                   2774: bar
                   2775: see bar
                   2776: @end example
                   2777: 
1.198     anton    2778: Two conventions to mark words with non-default compilation semantics are
1.48      anton    2779: names with brackets (more frequently used) and to write them all in
                   2780: upper case (less frequently used).
                   2781: 
                   2782: In Gforth (and many other systems) you can also remove the
                   2783: interpretation semantics with @code{compile-only} (the compilation
                   2784: semantics is derived from the original interpretation semantics):
                   2785: 
                   2786: @example
                   2787: : flip ( -- )
                   2788:  6 . ; compile-only \ but not immediate
                   2789: flip
                   2790: 
                   2791: : flop ( -- )
                   2792:  flip ;
                   2793: flop
                   2794: @end example
                   2795: 
                   2796: In this example the interpretation semantics of @code{flop} is equal to
                   2797: the original interpretation semantics of @code{flip}.
                   2798: 
                   2799: The text interpreter has two states: in interpret state, it performs the
                   2800: interpretation semantics of words it encounters; in compile state, it
                   2801: performs the compilation semantics of these words.
                   2802: 
                   2803: Among other things, @code{:} switches into compile state, and @code{;}
                   2804: switches back to interpret state.  They contain the factors @code{]}
                   2805: (switch to compile state) and @code{[} (switch to interpret state), that
                   2806: do nothing but switch the state.
                   2807: 
                   2808: @example
                   2809: : xxx ( -- )
                   2810:   [ 5 . ]
                   2811: ;
                   2812: 
                   2813: xxx
                   2814: see xxx
                   2815: @end example
                   2816: 
                   2817: These brackets are also the source of the naming convention mentioned
                   2818: above.
                   2819: 
1.66      anton    2820: Reference: @ref{Interpretation and Compilation Semantics}.
                   2821: 
1.48      anton    2822: 
                   2823: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
                   2824: @section Execution Tokens
1.66      anton    2825: @cindex execution tokens tutorial
                   2826: @cindex XT tutorial
1.48      anton    2827: 
                   2828: @code{' word} gives you the execution token (XT) of a word.  The XT is a
                   2829: cell representing the interpretation semantics of a word.  You can
                   2830: execute this semantics with @code{execute}:
                   2831: 
                   2832: @example
                   2833: ' + .s
                   2834: 1 2 rot execute .
                   2835: @end example
                   2836: 
                   2837: The XT is similar to a function pointer in C.  However, parameter
                   2838: passing through the stack makes it a little more flexible:
                   2839: 
                   2840: @example
                   2841: : map-array ( ... addr u xt -- ... )
1.50      anton    2842: \ executes xt ( ... x -- ... ) for every element of the array starting
                   2843: \ at addr and containing u elements
1.48      anton    2844:   @{ xt @}
                   2845:   cells over + swap ?do
1.50      anton    2846:     i @@ xt execute
1.48      anton    2847:   1 cells +loop ;
                   2848: 
                   2849: create a 3 , 4 , 2 , -1 , 4 ,
                   2850: a 5 ' . map-array .s
                   2851: 0 a 5 ' + map-array .
                   2852: s" max-n" environment? drop .s
                   2853: a 5 ' min map-array .
                   2854: @end example
                   2855: 
                   2856: You can use map-array with the XTs of words that consume one element
                   2857: more than they produce.  In theory you can also use it with other XTs,
                   2858: but the stack effect then depends on the size of the array, which is
                   2859: hard to understand.
                   2860: 
1.51      pazsan   2861: Since XTs are cell-sized, you can store them in memory and manipulate
                   2862: them on the stack like other cells.  You can also compile the XT into a
1.48      anton    2863: word with @code{compile,}:
                   2864: 
                   2865: @example
                   2866: : foo1 ( n1 n2 -- n )
                   2867:    [ ' + compile, ] ;
                   2868: see foo
                   2869: @end example
                   2870: 
                   2871: This is non-standard, because @code{compile,} has no compilation
                   2872: semantics in the standard, but it works in good Forth systems.  For the
                   2873: broken ones, use
                   2874: 
                   2875: @example
                   2876: : [compile,] compile, ; immediate
                   2877: 
                   2878: : foo1 ( n1 n2 -- n )
                   2879:    [ ' + ] [compile,] ;
                   2880: see foo
                   2881: @end example
                   2882: 
                   2883: @code{'} is a word with default compilation semantics; it parses the
                   2884: next word when its interpretation semantics are executed, not during
                   2885: compilation:
                   2886: 
                   2887: @example
                   2888: : foo ( -- xt )
                   2889:   ' ;
                   2890: see foo
                   2891: : bar ( ... "word" -- ... )
                   2892:   ' execute ;
                   2893: see bar
1.60      anton    2894: 1 2 bar + .
1.48      anton    2895: @end example
                   2896: 
                   2897: You often want to parse a word during compilation and compile its XT so
                   2898: it will be pushed on the stack at run-time.  @code{[']} does this:
                   2899: 
                   2900: @example
                   2901: : xt-+ ( -- xt )
                   2902:   ['] + ;
                   2903: see xt-+
                   2904: 1 2 xt-+ execute .
                   2905: @end example
                   2906: 
                   2907: Many programmers tend to see @code{'} and the word it parses as one
                   2908: unit, and expect it to behave like @code{[']} when compiled, and are
                   2909: confused by the actual behaviour.  If you are, just remember that the
                   2910: Forth system just takes @code{'} as one unit and has no idea that it is
                   2911: a parsing word (attempts to convenience programmers in this issue have
                   2912: usually resulted in even worse pitfalls, see
1.66      anton    2913: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
                   2914: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48      anton    2915: 
                   2916: Note that the state of the interpreter does not come into play when
1.51      pazsan   2917: creating and executing XTs.  I.e., even when you execute @code{'} in
1.48      anton    2918: compile state, it still gives you the interpretation semantics.  And
                   2919: whatever that state is, @code{execute} performs the semantics
1.66      anton    2920: represented by the XT (i.e., for XTs produced with @code{'} the
                   2921: interpretation semantics).
                   2922: 
                   2923: Reference: @ref{Tokens for Words}.
1.48      anton    2924: 
                   2925: 
                   2926: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
                   2927: @section Exceptions
1.66      anton    2928: @cindex exceptions tutorial
1.48      anton    2929: 
                   2930: @code{throw ( n -- )} causes an exception unless n is zero.
                   2931: 
                   2932: @example
                   2933: 100 throw .s
                   2934: 0 throw .s
                   2935: @end example
                   2936: 
                   2937: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
                   2938: it catches exceptions and pushes the number of the exception on the
                   2939: stack (or 0, if the xt executed without exception).  If there was an
                   2940: exception, the stacks have the same depth as when entering @code{catch}:
                   2941: 
                   2942: @example
                   2943: .s
                   2944: 3 0 ' / catch .s
                   2945: 3 2 ' / catch .s
                   2946: @end example
                   2947: 
1.141     anton    2948: @quotation Assignment
1.48      anton    2949: Try the same with @code{execute} instead of @code{catch}.
1.141     anton    2950: @end quotation
1.48      anton    2951: 
                   2952: @code{Throw} always jumps to the dynamically next enclosing
                   2953: @code{catch}, even if it has to leave several call levels to achieve
                   2954: this:
                   2955: 
                   2956: @example
                   2957: : foo 100 throw ;
                   2958: : foo1 foo ." after foo" ;
1.51      pazsan   2959: : bar ['] foo1 catch ;
1.60      anton    2960: bar .
1.48      anton    2961: @end example
                   2962: 
                   2963: It is often important to restore a value upon leaving a definition, even
                   2964: if the definition is left through an exception.  You can ensure this
                   2965: like this:
                   2966: 
                   2967: @example
                   2968: : ...
                   2969:    save-x
1.51      pazsan   2970:    ['] word-changing-x catch ( ... n )
1.48      anton    2971:    restore-x
                   2972:    ( ... n ) throw ;
                   2973: @end example
                   2974: 
1.172     anton    2975: However, this is still not safe against, e.g., the user pressing
                   2976: @kbd{Ctrl-C} when execution is between the @code{catch} and
                   2977: @code{restore-x}.
                   2978: 
                   2979: Gforth provides an alternative exception handling syntax that is safe
                   2980: against such cases: @code{try ... restore ... endtry}.  If the code
                   2981: between @code{try} and @code{endtry} has an exception, the stack
                   2982: depths are restored, the exception number is pushed on the stack, and
                   2983: the execution continues right after @code{restore}.
1.48      anton    2984: 
1.172     anton    2985: The safer equivalent to the restoration code above is
1.48      anton    2986: 
                   2987: @example
                   2988: : ...
                   2989:   save-x
                   2990:   try
1.92      anton    2991:     word-changing-x 0
1.172     anton    2992:   restore
                   2993:     restore-x
                   2994:   endtry
1.48      anton    2995:   throw ;
                   2996: @end example
                   2997: 
1.66      anton    2998: Reference: @ref{Exception Handling}.
                   2999: 
1.48      anton    3000: 
                   3001: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
                   3002: @section Defining Words
1.66      anton    3003: @cindex defining words tutorial
                   3004: @cindex does> tutorial
                   3005: @cindex create...does> tutorial
                   3006: 
                   3007: @c before semantics?
1.48      anton    3008: 
                   3009: @code{:}, @code{create}, and @code{variable} are definition words: They
                   3010: define other words.  @code{Constant} is another definition word:
                   3011: 
                   3012: @example
                   3013: 5 constant foo
                   3014: foo .
                   3015: @end example
                   3016: 
                   3017: You can also use the prefixes @code{2} (double-cell) and @code{f}
                   3018: (floating point) with @code{variable} and @code{constant}.
                   3019: 
                   3020: You can also define your own defining words.  E.g.:
                   3021: 
                   3022: @example
                   3023: : variable ( "name" -- )
                   3024:   create 0 , ;
                   3025: @end example
                   3026: 
                   3027: You can also define defining words that create words that do something
                   3028: other than just producing their address:
                   3029: 
                   3030: @example
                   3031: : constant ( n "name" -- )
                   3032:   create ,
                   3033: does> ( -- n )
1.50      anton    3034:   ( addr ) @@ ;
1.48      anton    3035: 
                   3036: 5 constant foo
                   3037: foo .
                   3038: @end example
                   3039: 
                   3040: The definition of @code{constant} above ends at the @code{does>}; i.e.,
                   3041: @code{does>} replaces @code{;}, but it also does something else: It
                   3042: changes the last defined word such that it pushes the address of the
                   3043: body of the word and then performs the code after the @code{does>}
                   3044: whenever it is called.
                   3045: 
                   3046: In the example above, @code{constant} uses @code{,} to store 5 into the
                   3047: body of @code{foo}.  When @code{foo} executes, it pushes the address of
                   3048: the body onto the stack, then (in the code after the @code{does>})
                   3049: fetches the 5 from there.
                   3050: 
                   3051: The stack comment near the @code{does>} reflects the stack effect of the
                   3052: defined word, not the stack effect of the code after the @code{does>}
                   3053: (the difference is that the code expects the address of the body that
                   3054: the stack comment does not show).
                   3055: 
                   3056: You can use these definition words to do factoring in cases that involve
                   3057: (other) definition words.  E.g., a field offset is always added to an
                   3058: address.  Instead of defining
                   3059: 
                   3060: @example
                   3061: 2 cells constant offset-field1
                   3062: @end example
                   3063: 
                   3064: and using this like
                   3065: 
                   3066: @example
                   3067: ( addr ) offset-field1 +
                   3068: @end example
                   3069: 
                   3070: you can define a definition word
                   3071: 
                   3072: @example
                   3073: : simple-field ( n "name" -- )
                   3074:   create ,
                   3075: does> ( n1 -- n1+n )
1.50      anton    3076:   ( addr ) @@ + ;
1.48      anton    3077: @end example
1.21      crook    3078: 
1.48      anton    3079: Definition and use of field offsets now look like this:
1.21      crook    3080: 
1.48      anton    3081: @example
                   3082: 2 cells simple-field field1
1.60      anton    3083: create mystruct 4 cells allot
                   3084: mystruct .s field1 .s drop
1.48      anton    3085: @end example
1.21      crook    3086: 
1.48      anton    3087: If you want to do something with the word without performing the code
                   3088: after the @code{does>}, you can access the body of a @code{create}d word
                   3089: with @code{>body ( xt -- addr )}:
1.21      crook    3090: 
1.48      anton    3091: @example
                   3092: : value ( n "name" -- )
                   3093:   create ,
                   3094: does> ( -- n1 )
1.50      anton    3095:   @@ ;
1.48      anton    3096: : to ( n "name" -- )
                   3097:   ' >body ! ;
1.21      crook    3098: 
1.48      anton    3099: 5 value foo
                   3100: foo .
                   3101: 7 to foo
                   3102: foo .
                   3103: @end example
1.21      crook    3104: 
1.141     anton    3105: @quotation Assignment
1.48      anton    3106: Define @code{defer ( "name" -- )}, which creates a word that stores an
                   3107: XT (at the start the XT of @code{abort}), and upon execution
                   3108: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
                   3109: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
                   3110: recursion is one application of @code{defer}.
1.141     anton    3111: @end quotation
1.29      crook    3112: 
1.66      anton    3113: Reference: @ref{User-defined Defining Words}.
                   3114: 
                   3115: 
1.48      anton    3116: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
                   3117: @section Arrays and Records
1.66      anton    3118: @cindex arrays tutorial
                   3119: @cindex records tutorial
                   3120: @cindex structs tutorial
1.29      crook    3121: 
1.48      anton    3122: Forth has no standard words for defining data structures such as arrays
                   3123: and records (structs in C terminology), but you can build them yourself
                   3124: based on address arithmetic.  You can also define words for defining
                   3125: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29      crook    3126: 
1.48      anton    3127: One of the first projects a Forth newcomer sets out upon when learning
                   3128: about defining words is an array defining word (possibly for
                   3129: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
                   3130: learn something from it.  However, don't be disappointed when you later
                   3131: learn that you have little use for these words (inappropriate use would
1.198     anton    3132: be even worse).  I have not found a set of useful array words yet;
1.48      anton    3133: the needs are just too diverse, and named, global arrays (the result of
                   3134: naive use of defining words) are often not flexible enough (e.g.,
1.66      anton    3135: consider how to pass them as parameters).  Another such project is a set
                   3136: of words to help dealing with strings.
1.29      crook    3137: 
1.48      anton    3138: On the other hand, there is a useful set of record words, and it has
                   3139: been defined in @file{compat/struct.fs}; these words are predefined in
                   3140: Gforth.  They are explained in depth elsewhere in this manual (see
                   3141: @pxref{Structures}).  The @code{simple-field} example above is
                   3142: simplified variant of fields in this package.
1.21      crook    3143: 
                   3144: 
1.48      anton    3145: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
                   3146: @section @code{POSTPONE}
1.66      anton    3147: @cindex postpone tutorial
1.21      crook    3148: 
1.48      anton    3149: You can compile the compilation semantics (instead of compiling the
                   3150: interpretation semantics) of a word with @code{POSTPONE}:
1.21      crook    3151: 
1.48      anton    3152: @example
                   3153: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51      pazsan   3154:  POSTPONE + ; immediate
1.48      anton    3155: : foo ( n1 n2 -- n )
                   3156:  MY-+ ;
                   3157: 1 2 foo .
                   3158: see foo
                   3159: @end example
1.21      crook    3160: 
1.48      anton    3161: During the definition of @code{foo} the text interpreter performs the
                   3162: compilation semantics of @code{MY-+}, which performs the compilation
                   3163: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
                   3164: 
                   3165: This example also displays separate stack comments for the compilation
                   3166: semantics and for the stack effect of the compiled code.  For words with
                   3167: default compilation semantics these stack effects are usually not
                   3168: displayed; the stack effect of the compilation semantics is always
                   3169: @code{( -- )} for these words, the stack effect for the compiled code is
                   3170: the stack effect of the interpretation semantics.
                   3171: 
                   3172: Note that the state of the interpreter does not come into play when
                   3173: performing the compilation semantics in this way.  You can also perform
                   3174: it interpretively, e.g.:
                   3175: 
                   3176: @example
                   3177: : foo2 ( n1 n2 -- n )
                   3178:  [ MY-+ ] ;
                   3179: 1 2 foo .
                   3180: see foo
                   3181: @end example
1.21      crook    3182: 
1.48      anton    3183: However, there are some broken Forth systems where this does not always
1.62      crook    3184: work, and therefore this practice was been declared non-standard in
1.48      anton    3185: 1999.
                   3186: @c !! repair.fs
                   3187: 
                   3188: Here is another example for using @code{POSTPONE}:
1.44      crook    3189: 
1.48      anton    3190: @example
                   3191: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
                   3192:  POSTPONE negate POSTPONE + ; immediate compile-only
                   3193: : bar ( n1 n2 -- n )
                   3194:   MY-- ;
                   3195: 2 1 bar .
                   3196: see bar
                   3197: @end example
1.21      crook    3198: 
1.48      anton    3199: You can define @code{ENDIF} in this way:
1.21      crook    3200: 
1.48      anton    3201: @example
                   3202: : ENDIF ( Compilation: orig -- )
                   3203:   POSTPONE then ; immediate
                   3204: @end example
1.21      crook    3205: 
1.141     anton    3206: @quotation Assignment
1.48      anton    3207: Write @code{MY-2DUP} that has compilation semantics equivalent to
                   3208: @code{2dup}, but compiles @code{over over}.
1.141     anton    3209: @end quotation
1.29      crook    3210: 
1.66      anton    3211: @c !! @xref{Macros} for reference
                   3212: 
                   3213: 
1.48      anton    3214: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
                   3215: @section @code{Literal}
1.66      anton    3216: @cindex literal tutorial
1.29      crook    3217: 
1.48      anton    3218: You cannot @code{POSTPONE} numbers:
1.21      crook    3219: 
1.48      anton    3220: @example
                   3221: : [FOO] POSTPONE 500 ; immediate
1.21      crook    3222: @end example
                   3223: 
1.48      anton    3224: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29      crook    3225: 
1.48      anton    3226: @example
                   3227: : [FOO] ( compilation: --; run-time: -- n )
                   3228:   500 POSTPONE literal ; immediate
1.29      crook    3229: 
1.60      anton    3230: : flip [FOO] ;
1.48      anton    3231: flip .
                   3232: see flip
                   3233: @end example
1.29      crook    3234: 
1.48      anton    3235: @code{LITERAL} consumes a number at compile-time (when it's compilation
                   3236: semantics are executed) and pushes it at run-time (when the code it
                   3237: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
                   3238: number computed at compile time into the current word:
1.29      crook    3239: 
1.48      anton    3240: @example
                   3241: : bar ( -- n )
                   3242:   [ 2 2 + ] literal ;
                   3243: see bar
                   3244: @end example
1.29      crook    3245: 
1.141     anton    3246: @quotation Assignment
1.48      anton    3247: Write @code{]L} which allows writing the example above as @code{: bar (
                   3248: -- n ) [ 2 2 + ]L ;}
1.141     anton    3249: @end quotation
1.48      anton    3250: 
1.66      anton    3251: @c !! @xref{Macros} for reference
                   3252: 
1.48      anton    3253: 
                   3254: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
                   3255: @section Advanced macros
1.66      anton    3256: @cindex macros, advanced tutorial
                   3257: @cindex run-time code generation, tutorial
1.48      anton    3258: 
1.66      anton    3259: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
                   3260: Execution Tokens}.  It frequently performs @code{execute}, a relatively
                   3261: expensive operation in some Forth implementations.  You can use
1.48      anton    3262: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
                   3263: and produce a word that contains the word to be performed directly:
                   3264: 
                   3265: @c use ]] ... [[
                   3266: @example
                   3267: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
                   3268: \ at run-time, execute xt ( ... x -- ... ) for each element of the
                   3269: \ array beginning at addr and containing u elements
                   3270:   @{ xt @}
                   3271:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50      anton    3272:     POSTPONE i POSTPONE @@ xt compile,
1.48      anton    3273:   1 cells POSTPONE literal POSTPONE +loop ;
                   3274: 
                   3275: : sum-array ( addr u -- n )
                   3276:  0 rot rot [ ' + compile-map-array ] ;
                   3277: see sum-array
                   3278: a 5 sum-array .
                   3279: @end example
                   3280: 
                   3281: You can use the full power of Forth for generating the code; here's an
                   3282: example where the code is generated in a loop:
                   3283: 
                   3284: @example
                   3285: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
                   3286: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50      anton    3287:   POSTPONE tuck POSTPONE @@
1.48      anton    3288:   POSTPONE literal POSTPONE * POSTPONE +
                   3289:   POSTPONE swap POSTPONE cell+ ;
                   3290: 
                   3291: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51      pazsan   3292: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48      anton    3293:   0 postpone literal postpone swap
                   3294:   [ ' compile-vmul-step compile-map-array ]
                   3295:   postpone drop ;
                   3296: see compile-vmul
                   3297: 
                   3298: : a-vmul ( addr -- n )
1.51      pazsan   3299: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48      anton    3300:  [ a 5 compile-vmul ] ;
                   3301: see a-vmul
                   3302: a a-vmul .
                   3303: @end example
                   3304: 
                   3305: This example uses @code{compile-map-array} to show off, but you could
1.66      anton    3306: also use @code{map-array} instead (try it now!).
1.48      anton    3307: 
                   3308: You can use this technique for efficient multiplication of large
                   3309: matrices.  In matrix multiplication, you multiply every line of one
                   3310: matrix with every column of the other matrix.  You can generate the code
                   3311: for one line once, and use it for every column.  The only downside of
                   3312: this technique is that it is cumbersome to recover the memory consumed
                   3313: by the generated code when you are done (and in more complicated cases
                   3314: it is not possible portably).
                   3315: 
1.66      anton    3316: @c !! @xref{Macros} for reference
                   3317: 
                   3318: 
1.48      anton    3319: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
                   3320: @section Compilation Tokens
1.66      anton    3321: @cindex compilation tokens, tutorial
                   3322: @cindex CT, tutorial
1.48      anton    3323: 
                   3324: This section is Gforth-specific.  You can skip it.
                   3325: 
                   3326: @code{' word compile,} compiles the interpretation semantics.  For words
                   3327: with default compilation semantics this is the same as performing the
                   3328: compilation semantics.  To represent the compilation semantics of other
                   3329: words (e.g., words like @code{if} that have no interpretation
                   3330: semantics), Gforth has the concept of a compilation token (CT,
                   3331: consisting of two cells), and words @code{comp'} and @code{[comp']}.
                   3332: You can perform the compilation semantics represented by a CT with
                   3333: @code{execute}:
1.29      crook    3334: 
1.48      anton    3335: @example
                   3336: : foo2 ( n1 n2 -- n )
                   3337:    [ comp' + execute ] ;
                   3338: see foo
                   3339: @end example
1.29      crook    3340: 
1.48      anton    3341: You can compile the compilation semantics represented by a CT with
                   3342: @code{postpone,}:
1.30      anton    3343: 
1.48      anton    3344: @example
                   3345: : foo3 ( -- )
                   3346:   [ comp' + postpone, ] ;
                   3347: see foo3
                   3348: @end example
1.30      anton    3349: 
1.51      pazsan   3350: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48      anton    3351: @code{comp'} is particularly useful for words that have no
                   3352: interpretation semantics:
1.29      crook    3353: 
1.30      anton    3354: @example
1.48      anton    3355: ' if
1.60      anton    3356: comp' if .s 2drop
1.30      anton    3357: @end example
                   3358: 
1.66      anton    3359: Reference: @ref{Tokens for Words}.
                   3360: 
1.29      crook    3361: 
1.48      anton    3362: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
                   3363: @section Wordlists and Search Order
1.66      anton    3364: @cindex wordlists tutorial
                   3365: @cindex search order, tutorial
1.48      anton    3366: 
                   3367: The dictionary is not just a memory area that allows you to allocate
                   3368: memory with @code{allot}, it also contains the Forth words, arranged in
                   3369: several wordlists.  When searching for a word in a wordlist,
                   3370: conceptually you start searching at the youngest and proceed towards
                   3371: older words (in reality most systems nowadays use hash-tables); i.e., if
                   3372: you define a word with the same name as an older word, the new word
                   3373: shadows the older word.
                   3374: 
                   3375: Which wordlists are searched in which order is determined by the search
                   3376: order.  You can display the search order with @code{order}.  It displays
                   3377: first the search order, starting with the wordlist searched first, then
                   3378: it displays the wordlist that will contain newly defined words.
1.21      crook    3379: 
1.48      anton    3380: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21      crook    3381: 
1.48      anton    3382: @example
                   3383: wordlist constant mywords
                   3384: @end example
1.21      crook    3385: 
1.48      anton    3386: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
                   3387: defined words (the @emph{current} wordlist):
1.21      crook    3388: 
1.48      anton    3389: @example
                   3390: mywords set-current
                   3391: order
                   3392: @end example
1.26      crook    3393: 
1.48      anton    3394: Gforth does not display a name for the wordlist in @code{mywords}
                   3395: because this wordlist was created anonymously with @code{wordlist}.
1.21      crook    3396: 
1.48      anton    3397: You can get the current wordlist with @code{get-current ( -- wid)}.  If
                   3398: you want to put something into a specific wordlist without overall
                   3399: effect on the current wordlist, this typically looks like this:
1.21      crook    3400: 
1.48      anton    3401: @example
                   3402: get-current mywords set-current ( wid )
                   3403: create someword
                   3404: ( wid ) set-current
                   3405: @end example
1.21      crook    3406: 
1.48      anton    3407: You can write the search order with @code{set-order ( wid1 .. widn n --
                   3408: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
                   3409: searched wordlist is topmost.
1.21      crook    3410: 
1.48      anton    3411: @example
                   3412: get-order mywords swap 1+ set-order
                   3413: order
                   3414: @end example
1.21      crook    3415: 
1.48      anton    3416: Yes, the order of wordlists in the output of @code{order} is reversed
                   3417: from stack comments and the output of @code{.s} and thus unintuitive.
1.21      crook    3418: 
1.141     anton    3419: @quotation Assignment
1.48      anton    3420: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
                   3421: wordlist to the search order.  Define @code{previous ( -- )}, which
                   3422: removes the first searched wordlist from the search order.  Experiment
                   3423: with boundary conditions (you will see some crashes or situations that
                   3424: are hard or impossible to leave).
1.141     anton    3425: @end quotation
1.21      crook    3426: 
1.48      anton    3427: The search order is a powerful foundation for providing features similar
                   3428: to Modula-2 modules and C++ namespaces.  However, trying to modularize
                   3429: programs in this way has disadvantages for debugging and reuse/factoring
                   3430: that overcome the advantages in my experience (I don't do huge projects,
1.55      anton    3431: though).  These disadvantages are not so clear in other
1.82      anton    3432: languages/programming environments, because these languages are not so
1.48      anton    3433: strong in debugging and reuse.
1.21      crook    3434: 
1.66      anton    3435: @c !! example
                   3436: 
                   3437: Reference: @ref{Word Lists}.
1.21      crook    3438: 
1.29      crook    3439: @c ******************************************************************
1.48      anton    3440: @node Introduction, Words, Tutorial, Top
1.29      crook    3441: @comment node-name,     next,           previous, up
                   3442: @chapter An Introduction to ANS Forth
                   3443: @cindex Forth - an introduction
1.21      crook    3444: 
1.83      anton    3445: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
                   3446: that it is slower-paced in its examples, but uses them to dive deep into
                   3447: explaining Forth internals (not covered by the Tutorial).  Apart from
                   3448: that, this chapter covers far less material.  It is suitable for reading
                   3449: without using a computer.
                   3450: 
1.29      crook    3451: The primary purpose of this manual is to document Gforth. However, since
                   3452: Forth is not a widely-known language and there is a lack of up-to-date
                   3453: teaching material, it seems worthwhile to provide some introductory
1.49      anton    3454: material.  For other sources of Forth-related
                   3455: information, see @ref{Forth-related information}.
1.21      crook    3456: 
1.29      crook    3457: The examples in this section should work on any ANS Forth; the
                   3458: output shown was produced using Gforth. Each example attempts to
                   3459: reproduce the exact output that Gforth produces. If you try out the
                   3460: examples (and you should), what you should type is shown @kbd{like this}
                   3461: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    3462: that, where the example shows @key{RET} it means that you should
1.29      crook    3463: press the ``carriage return'' key. Unfortunately, some output formats for
                   3464: this manual cannot show the difference between @kbd{this} and
                   3465: @code{this} which will make trying out the examples harder (but not
                   3466: impossible).
1.21      crook    3467: 
1.29      crook    3468: Forth is an unusual language. It provides an interactive development
                   3469: environment which includes both an interpreter and compiler. Forth
                   3470: programming style encourages you to break a problem down into many
                   3471: @cindex factoring
                   3472: small fragments (@dfn{factoring}), and then to develop and test each
                   3473: fragment interactively. Forth advocates assert that breaking the
                   3474: edit-compile-test cycle used by conventional programming languages can
                   3475: lead to great productivity improvements.
1.21      crook    3476: 
1.29      crook    3477: @menu
1.67      anton    3478: * Introducing the Text Interpreter::  
                   3479: * Stacks and Postfix notation::  
                   3480: * Your first definition::       
                   3481: * How does that work?::         
                   3482: * Forth is written in Forth::   
                   3483: * Review - elements of a Forth system::  
                   3484: * Where to go next::            
                   3485: * Exercises::                   
1.29      crook    3486: @end menu
1.21      crook    3487: 
1.29      crook    3488: @comment ----------------------------------------------
                   3489: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   3490: @section Introducing the Text Interpreter
                   3491: @cindex text interpreter
                   3492: @cindex outer interpreter
1.21      crook    3493: 
1.30      anton    3494: @c IMO this is too detailed and the pace is too slow for
                   3495: @c an introduction.  If you know German, take a look at
                   3496: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   3497: @c to see how I do it - anton 
                   3498: 
1.44      crook    3499: @c nac-> Where I have accepted your comments 100% and modified the text
                   3500: @c accordingly, I have deleted your comments. Elsewhere I have added a
                   3501: @c response like this to attempt to rationalise what I have done. Of
                   3502: @c course, this is a very clumsy mechanism for something that would be
                   3503: @c done far more efficiently over a beer. Please delete any dialogue
                   3504: @c you consider closed.
                   3505: 
1.29      crook    3506: When you invoke the Forth image, you will see a startup banner printed
                   3507: and nothing else (if you have Gforth installed on your system, try
1.30      anton    3508: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    3509: its command line interpreter, which is called the @dfn{Text Interpreter}
                   3510: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.49      anton    3511: about the text interpreter as you read through this chapter, for more
                   3512: detail @pxref{The Text Interpreter}).
1.21      crook    3513: 
1.29      crook    3514: Although it's not obvious, Forth is actually waiting for your
1.30      anton    3515: input. Type a number and press the @key{RET} key:
1.21      crook    3516: 
1.26      crook    3517: @example
1.30      anton    3518: @kbd{45@key{RET}}  ok
1.26      crook    3519: @end example
1.21      crook    3520: 
1.29      crook    3521: Rather than give you a prompt to invite you to input something, the text
                   3522: interpreter prints a status message @i{after} it has processed a line
                   3523: of input. The status message in this case (``@code{ ok}'' followed by
                   3524: carriage-return) indicates that the text interpreter was able to process
                   3525: all of your input successfully. Now type something illegal:
                   3526: 
                   3527: @example
1.30      anton    3528: @kbd{qwer341@key{RET}}
1.134     anton    3529: *the terminal*:2: Undefined word
                   3530: >>>qwer341<<<
                   3531: Backtrace:
                   3532: $2A95B42A20 throw 
                   3533: $2A95B57FB8 no.extensions 
1.29      crook    3534: @end example
1.23      crook    3535: 
1.134     anton    3536: The exact text, other than the ``Undefined word'' may differ slightly
                   3537: on your system, but the effect is the same; when the text interpreter
1.29      crook    3538: detects an error, it discards any remaining text on a line, resets
1.134     anton    3539: certain internal state and prints an error message. For a detailed
                   3540: description of error messages see @ref{Error messages}.
1.23      crook    3541: 
1.29      crook    3542: The text interpreter waits for you to press carriage-return, and then
                   3543: processes your input line. Starting at the beginning of the line, it
                   3544: breaks the line into groups of characters separated by spaces. For each
                   3545: group of characters in turn, it makes two attempts to do something:
1.23      crook    3546: 
1.29      crook    3547: @itemize @bullet
                   3548: @item
1.44      crook    3549: @cindex name dictionary
1.29      crook    3550: It tries to treat it as a command. It does this by searching a @dfn{name
                   3551: dictionary}. If the group of characters matches an entry in the name
                   3552: dictionary, the name dictionary provides the text interpreter with
                   3553: information that allows the text interpreter perform some actions. In
                   3554: Forth jargon, we say that the group
                   3555: @cindex word
                   3556: @cindex definition
                   3557: @cindex execution token
                   3558: @cindex xt
                   3559: of characters names a @dfn{word}, that the dictionary search returns an
                   3560: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   3561: word, and that the text interpreter executes the xt. Often, the terms
                   3562: @dfn{word} and @dfn{definition} are used interchangeably.
                   3563: @item
                   3564: If the text interpreter fails to find a match in the name dictionary, it
                   3565: tries to treat the group of characters as a number in the current number
                   3566: base (when you start up Forth, the current number base is base 10). If
                   3567: the group of characters legitimately represents a number, the text
                   3568: interpreter pushes the number onto a stack (we'll learn more about that
                   3569: in the next section).
                   3570: @end itemize
1.23      crook    3571: 
1.29      crook    3572: If the text interpreter is unable to do either of these things with any
                   3573: group of characters, it discards the group of characters and the rest of
                   3574: the line, then prints an error message. If the text interpreter reaches
                   3575: the end of the line without error, it prints the status message ``@code{ ok}''
                   3576: followed by carriage-return.
1.21      crook    3577: 
1.29      crook    3578: This is the simplest command we can give to the text interpreter:
1.23      crook    3579: 
                   3580: @example
1.30      anton    3581: @key{RET}  ok
1.23      crook    3582: @end example
1.21      crook    3583: 
1.29      crook    3584: The text interpreter did everything we asked it to do (nothing) without
                   3585: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   3586: command:
1.21      crook    3587: 
1.23      crook    3588: @example
1.30      anton    3589: @kbd{12 dup fred dup@key{RET}}
1.134     anton    3590: *the terminal*:3: Undefined word
                   3591: 12 dup >>>fred<<< dup
                   3592: Backtrace:
                   3593: $2A95B42A20 throw 
                   3594: $2A95B57FB8 no.extensions 
1.23      crook    3595: @end example
1.21      crook    3596: 
1.29      crook    3597: When you press the carriage-return key, the text interpreter starts to
                   3598: work its way along the line:
1.21      crook    3599: 
1.29      crook    3600: @itemize @bullet
                   3601: @item
                   3602: When it gets to the space after the @code{2}, it takes the group of
                   3603: characters @code{12} and looks them up in the name
                   3604: dictionary@footnote{We can't tell if it found them or not, but assume
                   3605: for now that it did not}. There is no match for this group of characters
                   3606: in the name dictionary, so it tries to treat them as a number. It is
                   3607: able to do this successfully, so it puts the number, 12, ``on the stack''
                   3608: (whatever that means).
                   3609: @item
                   3610: The text interpreter resumes scanning the line and gets the next group
                   3611: of characters, @code{dup}. It looks it up in the name dictionary and
                   3612: (you'll have to take my word for this) finds it, and executes the word
                   3613: @code{dup} (whatever that means).
                   3614: @item
                   3615: Once again, the text interpreter resumes scanning the line and gets the
                   3616: group of characters @code{fred}. It looks them up in the name
                   3617: dictionary, but can't find them. It tries to treat them as a number, but
                   3618: they don't represent any legal number.
                   3619: @end itemize
1.21      crook    3620: 
1.29      crook    3621: At this point, the text interpreter gives up and prints an error
                   3622: message. The error message shows exactly how far the text interpreter
                   3623: got in processing the line. In particular, it shows that the text
                   3624: interpreter made no attempt to do anything with the final character
                   3625: group, @code{dup}, even though we have good reason to believe that the
                   3626: text interpreter would have no problem looking that word up and
                   3627: executing it a second time.
1.21      crook    3628: 
                   3629: 
1.29      crook    3630: @comment ----------------------------------------------
                   3631: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   3632: @section Stacks, postfix notation and parameter passing
                   3633: @cindex text interpreter
                   3634: @cindex outer interpreter
1.21      crook    3635: 
1.29      crook    3636: In procedural programming languages (like C and Pascal), the
                   3637: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   3638: functions or procedures are called with @dfn{explicit parameters}. For
                   3639: example, in C we might write:
1.21      crook    3640: 
1.23      crook    3641: @example
1.29      crook    3642: total = total + new_volume(length,height,depth);
1.23      crook    3643: @end example
1.21      crook    3644: 
1.23      crook    3645: @noindent
1.29      crook    3646: where new_volume is a function-call to another piece of code, and total,
                   3647: length, height and depth are all variables. length, height and depth are
                   3648: parameters to the function-call.
1.21      crook    3649: 
1.29      crook    3650: In Forth, the equivalent of the function or procedure is the
                   3651: @dfn{definition} and parameters are implicitly passed between
                   3652: definitions using a shared stack that is visible to the
                   3653: programmer. Although Forth does support variables, the existence of the
                   3654: stack means that they are used far less often than in most other
                   3655: programming languages. When the text interpreter encounters a number, it
                   3656: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    3657: actual number is implementation-dependent ...) and the particular stack
1.29      crook    3658: used for any operation is implied unambiguously by the operation being
                   3659: performed. The stack used for all integer operations is called the @dfn{data
                   3660: stack} and, since this is the stack used most commonly, references to
                   3661: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    3662: 
1.29      crook    3663: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    3664: 
1.23      crook    3665: @example
1.30      anton    3666: @kbd{1 2 3@key{RET}}  ok
1.23      crook    3667: @end example
1.21      crook    3668: 
1.29      crook    3669: Then this instructs the text interpreter to placed three numbers on the
                   3670: (data) stack. An analogy for the behaviour of the stack is to take a
                   3671: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   3672: the table. The 3 was the last card onto the pile (``last-in'') and if
                   3673: you take a card off the pile then, unless you're prepared to fiddle a
                   3674: bit, the card that you take off will be the 3 (``first-out''). The
                   3675: number that will be first-out of the stack is called the @dfn{top of
                   3676: stack}, which
                   3677: @cindex TOS definition
                   3678: is often abbreviated to @dfn{TOS}.
1.21      crook    3679: 
1.29      crook    3680: To understand how parameters are passed in Forth, consider the
                   3681: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   3682: be surprised to learn that this definition performs addition. More
                   3683: precisely, it adds two number together and produces a result. Where does
                   3684: it get the two numbers from? It takes the top two numbers off the
                   3685: stack. Where does it place the result? On the stack. You can act-out the
                   3686: behaviour of @code{+} with your playing cards like this:
1.21      crook    3687: 
                   3688: @itemize @bullet
                   3689: @item
1.29      crook    3690: Pick up two cards from the stack on the table
1.21      crook    3691: @item
1.29      crook    3692: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   3693: numbers''
1.21      crook    3694: @item
1.29      crook    3695: Decide that the answer is 5
1.21      crook    3696: @item
1.29      crook    3697: Shuffle the two cards back into the pack and find a 5
1.21      crook    3698: @item
1.29      crook    3699: Put a 5 on the remaining ace that's on the table.
1.21      crook    3700: @end itemize
                   3701: 
1.29      crook    3702: If you don't have a pack of cards handy but you do have Forth running,
                   3703: you can use the definition @code{.s} to show the current state of the stack,
                   3704: without affecting the stack. Type:
1.21      crook    3705: 
                   3706: @example
1.124     anton    3707: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30      anton    3708: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    3709: @end example
                   3710: 
1.124     anton    3711: The text interpreter looks up the word @code{clearstacks} and executes
                   3712: it; it tidies up the stacks and removes any entries that may have been
1.29      crook    3713: left on it by earlier examples. The text interpreter pushes each of the
                   3714: three numbers in turn onto the stack. Finally, the text interpreter
                   3715: looks up the word @code{.s} and executes it. The effect of executing
                   3716: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   3717: followed by a list of all the items on the stack; the item on the far
                   3718: right-hand side is the TOS.
1.21      crook    3719: 
1.29      crook    3720: You can now type:
1.21      crook    3721: 
1.29      crook    3722: @example
1.30      anton    3723: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    3724: @end example
1.21      crook    3725: 
1.29      crook    3726: @noindent
                   3727: which is correct; there are now 2 items on the stack and the result of
                   3728: the addition is 5.
1.23      crook    3729: 
1.29      crook    3730: If you're playing with cards, try doing a second addition: pick up the
                   3731: two cards, work out that their sum is 6, shuffle them into the pack,
                   3732: look for a 6 and place that on the table. You now have just one item on
                   3733: the stack. What happens if you try to do a third addition? Pick up the
                   3734: first card, pick up the second card -- ah! There is no second card. This
                   3735: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95      anton    3736: do the same thing with Forth it often reports an error (probably a Stack
1.29      crook    3737: Underflow or an Invalid Memory Address error).
1.23      crook    3738: 
1.29      crook    3739: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   3740: which simply accepts that there is a finite amount of storage space
                   3741: reserved for the stack. To stretch the playing card analogy, if you had
                   3742: enough packs of cards and you piled the cards up on the table, you would
                   3743: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   3744: allows you to set the maximum size of the stacks. In general, the only
                   3745: time that you will get a stack overflow is because a definition has a
                   3746: bug in it and is generating data on the stack uncontrollably.
1.23      crook    3747: 
1.29      crook    3748: There's one final use for the playing card analogy. If you model your
                   3749: stack using a pack of playing cards, the maximum number of items on
                   3750: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   3751: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   3752: possible numbers are positive integer numbers 1 through 13; you can't
                   3753: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   3754: think about some of the cards, you can accommodate different
                   3755: numbers. For example, you could think of the Jack as representing 0,
                   3756: the Queen as representing -1 and the King as representing -2. Your
1.45      crook    3757: @i{range} remains unchanged (you can still only represent a total of 13
1.29      crook    3758: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    3759: 
1.29      crook    3760: In that analogy, the limit was the amount of information that a single
                   3761: stack entry could hold, and Forth has a similar limit. In Forth, the
                   3762: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   3763: implementation dependent and affects the maximum value that a stack
                   3764: entry can hold. A Standard Forth provides a cell size of at least
                   3765: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    3766: 
1.29      crook    3767: Forth does not do any type checking for you, so you are free to
                   3768: manipulate and combine stack items in any way you wish. A convenient way
                   3769: of treating stack items is as 2's complement signed integers, and that
                   3770: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    3771: 
1.29      crook    3772: @example
1.30      anton    3773: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    3774: @end example
1.21      crook    3775: 
1.29      crook    3776: If you use numbers and definitions like @code{+} in order to turn Forth
                   3777: into a great big pocket calculator, you will realise that it's rather
                   3778: different from a normal calculator. Rather than typing 2 + 3 = you had
                   3779: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   3780: result). The terminology used to describe this difference is to say that
                   3781: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   3782: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   3783: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    3784: 
1.29      crook    3785: Whilst postfix notation might look confusing to begin with, it has
                   3786: several important advantages:
1.21      crook    3787: 
1.23      crook    3788: @itemize @bullet
                   3789: @item
1.29      crook    3790: it is unambiguous
1.23      crook    3791: @item
1.29      crook    3792: it is more concise
1.23      crook    3793: @item
1.29      crook    3794: it fits naturally with a stack-based system
1.23      crook    3795: @end itemize
1.21      crook    3796: 
1.29      crook    3797: To examine these claims in more detail, consider these sums:
1.21      crook    3798: 
1.29      crook    3799: @example
                   3800: 6 + 5 * 4 =
                   3801: 4 * 5 + 6 =
                   3802: @end example
1.21      crook    3803: 
1.29      crook    3804: If you're just learning maths or your maths is very rusty, you will
                   3805: probably come up with the answer 44 for the first and 26 for the
                   3806: second. If you are a bit of a whizz at maths you will remember the
                   3807: @i{convention} that multiplication takes precendence over addition, and
                   3808: you'd come up with the answer 26 both times. To explain the answer 26
                   3809: to someone who got the answer 44, you'd probably rewrite the first sum
                   3810: like this:
1.21      crook    3811: 
1.29      crook    3812: @example
                   3813: 6 + (5 * 4) =
                   3814: @end example
1.21      crook    3815: 
1.29      crook    3816: If what you really wanted was to perform the addition before the
                   3817: multiplication, you would have to use parentheses to force it.
1.21      crook    3818: 
1.29      crook    3819: If you did the first two sums on a pocket calculator you would probably
                   3820: get the right answers, unless you were very cautious and entered them using
                   3821: these keystroke sequences:
1.21      crook    3822: 
1.29      crook    3823: 6 + 5 = * 4 =
                   3824: 4 * 5 = + 6 =
1.21      crook    3825: 
1.29      crook    3826: Postfix notation is unambiguous because the order that the operators
                   3827: are applied is always explicit; that also means that parentheses are
                   3828: never required. The operators are @i{active} (the act of quoting the
                   3829: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    3830: 
1.29      crook    3831: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   3832: equivalent ways:
1.26      crook    3833: 
                   3834: @example
1.29      crook    3835: 6 5 4 * +      or:
                   3836: 5 4 * 6 +
1.26      crook    3837: @end example
1.23      crook    3838: 
1.29      crook    3839: An important thing that you should notice about this notation is that
                   3840: the @i{order} of the numbers does not change; if you want to subtract
                   3841: 2 from 10 you type @code{10 2 -}.
1.1       anton    3842: 
1.29      crook    3843: The reason that Forth uses postfix notation is very simple to explain: it
                   3844: makes the implementation extremely simple, and it follows naturally from
                   3845: using the stack as a mechanism for passing parameters. Another way of
                   3846: thinking about this is to realise that all Forth definitions are
                   3847: @i{active}; they execute as they are encountered by the text
                   3848: interpreter. The result of this is that the syntax of Forth is trivially
                   3849: simple.
1.1       anton    3850: 
                   3851: 
                   3852: 
1.29      crook    3853: @comment ----------------------------------------------
                   3854: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   3855: @section Your first Forth definition
                   3856: @cindex first definition
1.1       anton    3857: 
1.29      crook    3858: Until now, the examples we've seen have been trivial; we've just been
                   3859: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   3860: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   3861: again@footnote{That's not quite true. If you press the up-arrow key on
                   3862: your keyboard you should be able to scroll back to any earlier command,
                   3863: edit it and re-enter it.} In this section we'll see how to add new
                   3864: words to Forth's vocabulary.
1.1       anton    3865: 
1.29      crook    3866: The easiest way to create a new word is to use a @dfn{colon
                   3867: definition}. We'll define a few and try them out before worrying too
                   3868: much about how they work. Try typing in these examples; be careful to
                   3869: copy the spaces accurately:
1.1       anton    3870: 
1.29      crook    3871: @example
                   3872: : add-two 2 + . ;
                   3873: : greet ." Hello and welcome" ;
                   3874: : demo 5 add-two ;
                   3875: @end example
1.1       anton    3876: 
1.29      crook    3877: @noindent
                   3878: Now try them out:
1.1       anton    3879: 
1.29      crook    3880: @example
1.30      anton    3881: @kbd{greet@key{RET}} Hello and welcome  ok
                   3882: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   3883: @kbd{4 add-two@key{RET}} 6  ok
                   3884: @kbd{demo@key{RET}} 7  ok
                   3885: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    3886: @end example
1.1       anton    3887: 
1.29      crook    3888: The first new thing that we've introduced here is the pair of words
                   3889: @code{:} and @code{;}. These are used to start and terminate a new
                   3890: definition, respectively. The first word after the @code{:} is the name
                   3891: for the new definition.
1.1       anton    3892: 
1.29      crook    3893: As you can see from the examples, a definition is built up of words that
                   3894: have already been defined; Forth makes no distinction between
                   3895: definitions that existed when you started the system up, and those that
                   3896: you define yourself.
1.1       anton    3897: 
1.29      crook    3898: The examples also introduce the words @code{.} (dot), @code{."}
                   3899: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   3900: the stack and displays it. It's like @code{.s} except that it only
                   3901: displays the top item of the stack and it is destructive; after it has
                   3902: executed, the number is no longer on the stack. There is always one
                   3903: space printed after the number, and no spaces before it. Dot-quote
                   3904: defines a string (a sequence of characters) that will be printed when
                   3905: the word is executed. The string can contain any printable characters
                   3906: except @code{"}. A @code{"} has a special function; it is not a Forth
                   3907: word but it acts as a delimiter (the way that delimiters work is
                   3908: described in the next section). Finally, @code{dup} duplicates the value
                   3909: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    3910: 
1.29      crook    3911: We already know that the text interpreter searches through the
                   3912: dictionary to locate names. If you've followed the examples earlier, you
                   3913: will already have a definition called @code{add-two}. Lets try modifying
                   3914: it by typing in a new definition:
1.1       anton    3915: 
1.29      crook    3916: @example
1.30      anton    3917: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    3918: @end example
1.5       anton    3919: 
1.29      crook    3920: Forth recognised that we were defining a word that already exists, and
                   3921: printed a message to warn us of that fact. Let's try out the new
                   3922: definition:
1.5       anton    3923: 
1.29      crook    3924: @example
1.30      anton    3925: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    3926: @end example
1.1       anton    3927: 
1.29      crook    3928: @noindent
                   3929: All that we've actually done here, though, is to create a new
                   3930: definition, with a particular name. The fact that there was already a
                   3931: definition with the same name did not make any difference to the way
                   3932: that the new definition was created (except that Forth printed a warning
                   3933: message). The old definition of add-two still exists (try @code{demo}
                   3934: again to see that this is true). Any new definition will use the new
                   3935: definition of @code{add-two}, but old definitions continue to use the
                   3936: version that already existed at the time that they were @code{compiled}.
1.1       anton    3937: 
1.29      crook    3938: Before you go on to the next section, try defining and redefining some
                   3939: words of your own.
1.1       anton    3940: 
1.29      crook    3941: @comment ----------------------------------------------
                   3942: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   3943: @section How does that work?
                   3944: @cindex parsing words
1.1       anton    3945: 
1.30      anton    3946: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   3947: 
                   3948: @c Is it a good idea to talk about the interpretation semantics of a
                   3949: @c number? We don't have an xt to go along with it. - anton
                   3950: 
                   3951: @c Now that I have eliminated execution semantics, I wonder if it would not
                   3952: @c be better to keep them (or add run-time semantics), to make it easier to
                   3953: @c explain what compilation semantics usually does. - anton
                   3954: 
1.44      crook    3955: @c nac-> I removed the term ``default compilation sematics'' from the
                   3956: @c introductory chapter. Removing ``execution semantics'' was making
                   3957: @c everything simpler to explain, then I think the use of this term made
                   3958: @c everything more complex again. I replaced it with ``default
                   3959: @c semantics'' (which is used elsewhere in the manual) by which I mean
                   3960: @c ``a definition that has neither the immediate nor the compile-only
1.83      anton    3961: @c flag set''.
                   3962: 
                   3963: @c anton: I have eliminated default semantics (except in one place where it
                   3964: @c means "default interpretation and compilation semantics"), because it
                   3965: @c makes no sense in the presence of combined words.  I reverted to
                   3966: @c "execution semantics" where necessary.
                   3967: 
                   3968: @c nac-> I reworded big chunks of the ``how does that work''
1.44      crook    3969: @c section (and, unusually for me, I think I even made it shorter!).  See
                   3970: @c what you think -- I know I have not addressed your primary concern
                   3971: @c that it is too heavy-going for an introduction. From what I understood
                   3972: @c of your course notes it looks as though they might be a good framework. 
                   3973: @c Things that I've tried to capture here are some things that came as a
                   3974: @c great revelation here when I first understood them. Also, I like the
                   3975: @c fact that a very simple code example shows up almost all of the issues
                   3976: @c that you need to understand to see how Forth works. That's unique and
                   3977: @c worthwhile to emphasise.
                   3978: 
1.83      anton    3979: @c anton: I think it's a good idea to present the details, especially those
                   3980: @c that you found to be a revelation, and probably the tutorial tries to be
                   3981: @c too superficial and does not get some of the things across that make
                   3982: @c Forth special.  I do believe that most of the time these things should
                   3983: @c be discussed at the end of a section or in separate sections instead of
                   3984: @c in the middle of a section (e.g., the stuff you added in "User-defined
                   3985: @c defining words" leads in a completely different direction from the rest
                   3986: @c of the section).
                   3987: 
1.29      crook    3988: Now we're going to take another look at the definition of @code{add-two}
                   3989: from the previous section. From our knowledge of the way that the text
                   3990: interpreter works, we would have expected this result when we tried to
                   3991: define @code{add-two}:
1.21      crook    3992: 
1.29      crook    3993: @example
1.44      crook    3994: @kbd{: add-two 2 + . ;@key{RET}}
1.134     anton    3995: *the terminal*:4: Undefined word
                   3996: : >>>add-two<<< 2 + . ;
1.29      crook    3997: @end example
1.28      crook    3998: 
1.29      crook    3999: The reason that this didn't happen is bound up in the way that @code{:}
                   4000: works. The word @code{:} does two special things. The first special
                   4001: thing that it does prevents the text interpreter from ever seeing the
                   4002: characters @code{add-two}. The text interpreter uses a variable called
                   4003: @cindex modifying >IN
1.44      crook    4004: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29      crook    4005: input line. When it encounters the word @code{:} it behaves in exactly
                   4006: the same way as it does for any other word; it looks it up in the name
                   4007: dictionary, finds its xt and executes it. When @code{:} executes, it
                   4008: looks at the input buffer, finds the word @code{add-two} and advances the
                   4009: value of @code{>IN} to point past it. It then does some other stuff
                   4010: associated with creating the new definition (including creating an entry
                   4011: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   4012: completes, control returns to the text interpreter, which is oblivious
                   4013: to the fact that it has been tricked into ignoring part of the input
                   4014: line.
1.21      crook    4015: 
1.29      crook    4016: @cindex parsing words
                   4017: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   4018: prevent the text interpreter from acting on the whole of the input line
                   4019: -- are called @dfn{parsing words}.
1.21      crook    4020: 
1.29      crook    4021: @cindex @code{state} - effect on the text interpreter
                   4022: @cindex text interpreter - effect of state
                   4023: The second special thing that @code{:} does is change the value of a
                   4024: variable called @code{state}, which affects the way that the text
                   4025: interpreter behaves. When Gforth starts up, @code{state} has the value
                   4026: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   4027: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44      crook    4028: the text interpreter is said to be @dfn{compiling}.
                   4029: 
                   4030: In this example, the text interpreter is compiling when it processes the
                   4031: string ``@code{2 + . ;}''. It still breaks the string down into
                   4032: character sequences in the same way. However, instead of pushing the
                   4033: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
                   4034: into the definition of @code{add-two} that will make the number @code{2} get
                   4035: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
                   4036: the behaviours of @code{+} and @code{.} are also compiled into the
                   4037: definition.
                   4038: 
                   4039: One category of words don't get compiled. These so-called @dfn{immediate
                   4040: words} get executed (performed @i{now}) regardless of whether the text
                   4041: interpreter is interpreting or compiling. The word @code{;} is an
                   4042: immediate word. Rather than being compiled into the definition, it
                   4043: executes. Its effect is to terminate the current definition, which
                   4044: includes changing the value of @code{state} back to 0.
                   4045: 
                   4046: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
                   4047: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
                   4048: definition.
1.28      crook    4049: 
1.30      anton    4050: In Forth, every word or number can be described in terms of two
1.29      crook    4051: properties:
1.28      crook    4052: 
                   4053: @itemize @bullet
                   4054: @item
1.29      crook    4055: @cindex interpretation semantics
1.44      crook    4056: Its @dfn{interpretation semantics} describe how it will behave when the
                   4057: text interpreter encounters it in @dfn{interpret} state. The
                   4058: interpretation semantics of a word are represented by an @dfn{execution
                   4059: token}.
1.28      crook    4060: @item
1.29      crook    4061: @cindex compilation semantics
1.44      crook    4062: Its @dfn{compilation semantics} describe how it will behave when the
                   4063: text interpreter encounters it in @dfn{compile} state. The compilation
                   4064: semantics of a word are represented in an implementation-dependent way;
                   4065: Gforth uses a @dfn{compilation token}.
1.29      crook    4066: @end itemize
                   4067: 
                   4068: @noindent
                   4069: Numbers are always treated in a fixed way:
                   4070: 
                   4071: @itemize @bullet
1.28      crook    4072: @item
1.44      crook    4073: When the number is @dfn{interpreted}, its behaviour is to push the
                   4074: number onto the stack.
1.28      crook    4075: @item
1.30      anton    4076: When the number is @dfn{compiled}, a piece of code is appended to the
                   4077: current definition that pushes the number when it runs. (In other words,
                   4078: the compilation semantics of a number are to postpone its interpretation
                   4079: semantics until the run-time of the definition that it is being compiled
                   4080: into.)
1.29      crook    4081: @end itemize
                   4082: 
1.44      crook    4083: Words don't behave in such a regular way, but most have @i{default
                   4084: semantics} which means that they behave like this:
1.29      crook    4085: 
                   4086: @itemize @bullet
1.28      crook    4087: @item
1.30      anton    4088: The @dfn{interpretation semantics} of the word are to do something useful.
                   4089: @item
1.29      crook    4090: The @dfn{compilation semantics} of the word are to append its
1.30      anton    4091: @dfn{interpretation semantics} to the current definition (so that its
                   4092: run-time behaviour is to do something useful).
1.28      crook    4093: @end itemize
                   4094: 
1.30      anton    4095: @cindex immediate words
1.44      crook    4096: The actual behaviour of any particular word can be controlled by using
                   4097: the words @code{immediate} and @code{compile-only} when the word is
                   4098: defined. These words set flags in the name dictionary entry of the most
                   4099: recently defined word, and these flags are retrieved by the text
                   4100: interpreter when it finds the word in the name dictionary.
                   4101: 
                   4102: A word that is marked as @dfn{immediate} has compilation semantics that
                   4103: are identical to its interpretation semantics. In other words, it
                   4104: behaves like this:
1.29      crook    4105: 
                   4106: @itemize @bullet
                   4107: @item
1.30      anton    4108: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    4109: @item
1.30      anton    4110: The @dfn{compilation semantics} of the word are to do something useful
                   4111: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    4112: @end itemize
1.28      crook    4113: 
1.44      crook    4114: Marking a word as @dfn{compile-only} prohibits the text interpreter from
                   4115: performing the interpretation semantics of the word directly; an attempt
                   4116: to do so will generate an error. It is never necessary to use
                   4117: @code{compile-only} (and it is not even part of ANS Forth, though it is
                   4118: provided by many implementations) but it is good etiquette to apply it
                   4119: to a word that will not behave correctly (and might have unexpected
                   4120: side-effects) in interpret state. For example, it is only legal to use
                   4121: the conditional word @code{IF} within a definition. If you forget this
                   4122: and try to use it elsewhere, the fact that (in Gforth) it is marked as
                   4123: @code{compile-only} allows the text interpreter to generate a helpful
                   4124: error message rather than subjecting you to the consequences of your
                   4125: folly.
                   4126: 
1.29      crook    4127: This example shows the difference between an immediate and a
                   4128: non-immediate word:
1.28      crook    4129: 
1.29      crook    4130: @example
                   4131: : show-state state @@ . ;
                   4132: : show-state-now show-state ; immediate
                   4133: : word1 show-state ;
                   4134: : word2 show-state-now ;
1.28      crook    4135: @end example
1.23      crook    4136: 
1.29      crook    4137: The word @code{immediate} after the definition of @code{show-state-now}
                   4138: makes that word an immediate word. These definitions introduce a new
                   4139: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   4140: variable, and leaves it on the stack. Therefore, the behaviour of
                   4141: @code{show-state} is to print a number that represents the current value
                   4142: of @code{state}.
1.28      crook    4143: 
1.29      crook    4144: When you execute @code{word1}, it prints the number 0, indicating that
                   4145: the system is interpreting. When the text interpreter compiled the
                   4146: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    4147: compilation semantics are to append its interpretation semantics to the
1.29      crook    4148: current definition. When you execute @code{word1}, it performs the
1.30      anton    4149: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    4150: (and therefore @code{show-state}) are executed, the system is
                   4151: interpreting.
1.28      crook    4152: 
1.30      anton    4153: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    4154: you should have seen the number -1 printed, followed by ``@code{
                   4155: ok}''. When the text interpreter compiled the definition of
                   4156: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    4157: whose compilation semantics are therefore to perform its interpretation
1.29      crook    4158: semantics. It is executed straight away (even before the text
                   4159: interpreter has moved on to process another group of characters; the
                   4160: @code{;} in this example). The effect of executing it are to display the
                   4161: value of @code{state} @i{at the time that the definition of}
                   4162: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   4163: system is compiling at this time. If you execute @code{word2} it does
                   4164: nothing at all.
1.28      crook    4165: 
1.29      crook    4166: @cindex @code{."}, how it works
                   4167: Before leaving the subject of immediate words, consider the behaviour of
                   4168: @code{."} in the definition of @code{greet}, in the previous
                   4169: section. This word is both a parsing word and an immediate word. Notice
                   4170: that there is a space between @code{."} and the start of the text
                   4171: @code{Hello and welcome}, but that there is no space between the last
                   4172: letter of @code{welcome} and the @code{"} character. The reason for this
                   4173: is that @code{."} is a Forth word; it must have a space after it so that
                   4174: the text interpreter can identify it. The @code{"} is not a Forth word;
                   4175: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   4176: is displayed, there is neither a space before the @code{H} nor after the
                   4177: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   4178: that @code{greet} is defined. When it executes, its behaviour is to
                   4179: search forward in the input line looking for the delimiter. When it
                   4180: finds the delimiter, it updates @code{>IN} to point past the
                   4181: delimiter. It also compiles some magic code into the definition of
                   4182: @code{greet}; the xt of a run-time routine that prints a text string. It
                   4183: compiles the string @code{Hello and welcome} into memory so that it is
                   4184: available to be printed later. When the text interpreter gains control,
                   4185: the next word it finds in the input stream is @code{;} and so it
                   4186: terminates the definition of @code{greet}.
1.28      crook    4187: 
                   4188: 
                   4189: @comment ----------------------------------------------
1.29      crook    4190: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   4191: @section Forth is written in Forth
                   4192: @cindex structure of Forth programs
                   4193: 
                   4194: When you start up a Forth compiler, a large number of definitions
                   4195: already exist. In Forth, you develop a new application using bottom-up
                   4196: programming techniques to create new definitions that are defined in
                   4197: terms of existing definitions. As you create each definition you can
                   4198: test and debug it interactively.
                   4199: 
                   4200: If you have tried out the examples in this section, you will probably
                   4201: have typed them in by hand; when you leave Gforth, your definitions will
                   4202: be lost. You can avoid this by using a text editor to enter Forth source
                   4203: code into a file, and then loading code from the file using
1.49      anton    4204: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29      crook    4205: processed by the text interpreter, just as though you had typed it in by
                   4206: hand@footnote{Actually, there are some subtle differences -- see
                   4207: @ref{The Text Interpreter}.}.
                   4208: 
                   4209: Gforth also supports the traditional Forth alternative to using text
1.49      anton    4210: files for program entry (@pxref{Blocks}).
1.28      crook    4211: 
1.29      crook    4212: In common with many, if not most, Forth compilers, most of Gforth is
                   4213: actually written in Forth. All of the @file{.fs} files in the
                   4214: installation directory@footnote{For example,
1.30      anton    4215: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    4216: study to see examples of Forth programming.
1.28      crook    4217: 
1.29      crook    4218: Gforth maintains a history file that records every line that you type to
                   4219: the text interpreter. This file is preserved between sessions, and is
                   4220: used to provide a command-line recall facility. If you enter long
                   4221: definitions by hand, you can use a text editor to paste them out of the
                   4222: history file into a Forth source file for reuse at a later time
1.49      anton    4223: (for more information @pxref{Command-line editing}).
1.28      crook    4224: 
                   4225: 
                   4226: @comment ----------------------------------------------
1.29      crook    4227: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   4228: @section Review - elements of a Forth system
                   4229: @cindex elements of a Forth system
1.28      crook    4230: 
1.29      crook    4231: To summarise this chapter:
1.28      crook    4232: 
                   4233: @itemize @bullet
                   4234: @item
1.29      crook    4235: Forth programs use @dfn{factoring} to break a problem down into small
                   4236: fragments called @dfn{words} or @dfn{definitions}.
                   4237: @item
                   4238: Forth program development is an interactive process.
                   4239: @item
                   4240: The main command loop that accepts input, and controls both
                   4241: interpretation and compilation, is called the @dfn{text interpreter}
                   4242: (also known as the @dfn{outer interpreter}).
                   4243: @item
                   4244: Forth has a very simple syntax, consisting of words and numbers
                   4245: separated by spaces or carriage-return characters. Any additional syntax
                   4246: is imposed by @dfn{parsing words}.
                   4247: @item
                   4248: Forth uses a stack to pass parameters between words. As a result, it
                   4249: uses postfix notation.
                   4250: @item
                   4251: To use a word that has previously been defined, the text interpreter
                   4252: searches for the word in the @dfn{name dictionary}.
                   4253: @item
1.30      anton    4254: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    4255: @item
1.29      crook    4256: The text interpreter uses the value of @code{state} to select between
                   4257: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   4258: semantics} of a word that it encounters.
1.28      crook    4259: @item
1.30      anton    4260: The relationship between the @dfn{interpretation semantics} and
                   4261: @dfn{compilation semantics} for a word
1.29      crook    4262: depend upon the way in which the word was defined (for example, whether
                   4263: it is an @dfn{immediate} word).
1.28      crook    4264: @item
1.29      crook    4265: Forth definitions can be implemented in Forth (called @dfn{high-level
                   4266: definitions}) or in some other way (usually a lower-level language and
                   4267: as a result often called @dfn{low-level definitions}, @dfn{code
                   4268: definitions} or @dfn{primitives}).
1.28      crook    4269: @item
1.29      crook    4270: Many Forth systems are implemented mainly in Forth.
1.28      crook    4271: @end itemize
                   4272: 
                   4273: 
1.29      crook    4274: @comment ----------------------------------------------
1.48      anton    4275: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29      crook    4276: @section Where To Go Next
                   4277: @cindex where to go next
1.28      crook    4278: 
1.29      crook    4279: Amazing as it may seem, if you have read (and understood) this far, you
                   4280: know almost all the fundamentals about the inner workings of a Forth
                   4281: system. You certainly know enough to be able to read and understand the
                   4282: rest of this manual and the ANS Forth document, to learn more about the
                   4283: facilities that Forth in general and Gforth in particular provide. Even
                   4284: scarier, you know almost enough to implement your own Forth system.
1.30      anton    4285: However, that's not a good idea just yet... better to try writing some
1.29      crook    4286: programs in Gforth.
1.28      crook    4287: 
1.29      crook    4288: Forth has such a rich vocabulary that it can be hard to know where to
                   4289: start in learning it. This section suggests a few sets of words that are
                   4290: enough to write small but useful programs. Use the word index in this
                   4291: document to learn more about each word, then try it out and try to write
                   4292: small definitions using it. Start by experimenting with these words:
1.28      crook    4293: 
                   4294: @itemize @bullet
                   4295: @item
1.29      crook    4296: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   4297: @item
                   4298: Comparison: @code{MIN MAX =}
                   4299: @item
                   4300: Logic: @code{AND OR XOR NOT}
                   4301: @item
                   4302: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    4303: @item
1.29      crook    4304: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    4305: @item
1.29      crook    4306: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    4307: @item
1.29      crook    4308: Defining words: @code{: ; CREATE}
1.28      crook    4309: @item
1.29      crook    4310: Memory allocation words: @code{ALLOT ,}
1.28      crook    4311: @item
1.29      crook    4312: Tools: @code{SEE WORDS .S MARKER}
                   4313: @end itemize
                   4314: 
                   4315: When you have mastered those, go on to:
                   4316: 
                   4317: @itemize @bullet
1.28      crook    4318: @item
1.29      crook    4319: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    4320: @item
1.29      crook    4321: Memory access: @code{@@ !}
1.28      crook    4322: @end itemize
1.23      crook    4323: 
1.29      crook    4324: When you have mastered these, there's nothing for it but to read through
                   4325: the whole of this manual and find out what you've missed.
                   4326: 
                   4327: @comment ----------------------------------------------
1.48      anton    4328: @node Exercises,  , Where to go next, Introduction
1.29      crook    4329: @section Exercises
                   4330: @cindex exercises
                   4331: 
                   4332: TODO: provide a set of programming excercises linked into the stuff done
                   4333: already and into other sections of the manual. Provide solutions to all
                   4334: the exercises in a .fs file in the distribution.
                   4335: 
                   4336: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   4337: 
                   4338: @c excercises:
                   4339: @c 1. take inches and convert to feet and inches.
                   4340: @c 2. take temperature and convert from fahrenheight to celcius;
                   4341: @c    may need to care about symmetric vs floored??
                   4342: @c 3. take input line and do character substitution
                   4343: @c    to encipher or decipher
                   4344: @c 4. as above but work on a file for in and out
                   4345: @c 5. take input line and convert to pig-latin 
                   4346: @c
                   4347: @c thing of sets of things to exercise then come up with
                   4348: @c problems that need those things.
                   4349: 
                   4350: 
1.26      crook    4351: @c ******************************************************************
1.29      crook    4352: @node Words, Error messages, Introduction, Top
1.1       anton    4353: @chapter Forth Words
1.26      crook    4354: @cindex words
1.1       anton    4355: 
                   4356: @menu
                   4357: * Notation::                    
1.65      anton    4358: * Case insensitivity::          
                   4359: * Comments::                    
                   4360: * Boolean Flags::               
1.1       anton    4361: * Arithmetic::                  
                   4362: * Stack Manipulation::          
1.5       anton    4363: * Memory::                      
1.1       anton    4364: * Control Structures::          
                   4365: * Defining Words::              
1.65      anton    4366: * Interpretation and Compilation Semantics::  
1.47      crook    4367: * Tokens for Words::            
1.81      anton    4368: * Compiling words::             
1.65      anton    4369: * The Text Interpreter::        
1.111     anton    4370: * The Input Stream::            
1.65      anton    4371: * Word Lists::                  
                   4372: * Environmental Queries::       
1.12      anton    4373: * Files::                       
                   4374: * Blocks::                      
                   4375: * Other I/O::                   
1.121     anton    4376: * OS command line arguments::   
1.78      anton    4377: * Locals::                      
                   4378: * Structures::                  
                   4379: * Object-oriented Forth::       
1.12      anton    4380: * Programming Tools::           
1.150     anton    4381: * C Interface::                 
1.12      anton    4382: * Assembler and Code Words::    
                   4383: * Threading Words::             
1.65      anton    4384: * Passing Commands to the OS::  
                   4385: * Keeping track of Time::       
                   4386: * Miscellaneous Words::         
1.1       anton    4387: @end menu
                   4388: 
1.65      anton    4389: @node Notation, Case insensitivity, Words, Words
1.1       anton    4390: @section Notation
                   4391: @cindex notation of glossary entries
                   4392: @cindex format of glossary entries
                   4393: @cindex glossary notation format
                   4394: @cindex word glossary entry format
                   4395: 
                   4396: The Forth words are described in this section in the glossary notation
1.67      anton    4397: that has become a de-facto standard for Forth texts:
1.1       anton    4398: 
                   4399: @format
1.29      crook    4400: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    4401: @end format
1.29      crook    4402: @i{Description}
1.1       anton    4403: 
                   4404: @table @var
                   4405: @item word
1.28      crook    4406: The name of the word.
1.1       anton    4407: 
                   4408: @item Stack effect
                   4409: @cindex stack effect
1.29      crook    4410: The stack effect is written in the notation @code{@i{before} --
                   4411: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    4412: stack entries before and after the execution of the word. The rest of
                   4413: the stack is not touched by the word. The top of stack is rightmost,
                   4414: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   4415: uses a separate floating point stack, but a unified stack
1.29      crook    4416: notation. Also, return stack effects are not shown in @i{stack
                   4417: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    4418: the type and/or the function of the item. See below for a discussion of
                   4419: the types.
                   4420: 
                   4421: All words have two stack effects: A compile-time stack effect and a
                   4422: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    4423: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    4424: this standard behaviour, or the word does other unusual things at
                   4425: compile time, both stack effects are shown; otherwise only the run-time
                   4426: stack effect is shown.
                   4427: 
                   4428: @cindex pronounciation of words
                   4429: @item pronunciation
                   4430: How the word is pronounced.
                   4431: 
                   4432: @cindex wordset
1.67      anton    4433: @cindex environment wordset
1.1       anton    4434: @item wordset
1.21      crook    4435: The ANS Forth standard is divided into several word sets. A standard
                   4436: system need not support all of them. Therefore, in theory, the fewer
                   4437: word sets your program uses the more portable it will be. However, we
                   4438: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    4439: all word sets. Words that are not defined in ANS Forth have
1.21      crook    4440: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    4441: describes words that will work in future releases of Gforth;
                   4442: @code{gforth-internal} words are more volatile. Environmental query
                   4443: strings are also displayed like words; you can recognize them by the
1.21      crook    4444: @code{environment} in the word set field.
1.1       anton    4445: 
                   4446: @item Description
                   4447: A description of the behaviour of the word.
                   4448: @end table
                   4449: 
                   4450: @cindex types of stack items
                   4451: @cindex stack item types
                   4452: The type of a stack item is specified by the character(s) the name
                   4453: starts with:
                   4454: 
                   4455: @table @code
                   4456: @item f
                   4457: @cindex @code{f}, stack item type
                   4458: Boolean flags, i.e. @code{false} or @code{true}.
                   4459: @item c
                   4460: @cindex @code{c}, stack item type
                   4461: Char
                   4462: @item w
                   4463: @cindex @code{w}, stack item type
                   4464: Cell, can contain an integer or an address
                   4465: @item n
                   4466: @cindex @code{n}, stack item type
                   4467: signed integer
                   4468: @item u
                   4469: @cindex @code{u}, stack item type
                   4470: unsigned integer
                   4471: @item d
                   4472: @cindex @code{d}, stack item type
                   4473: double sized signed integer
                   4474: @item ud
                   4475: @cindex @code{ud}, stack item type
                   4476: double sized unsigned integer
                   4477: @item r
                   4478: @cindex @code{r}, stack item type
                   4479: Float (on the FP stack)
1.21      crook    4480: @item a-
1.1       anton    4481: @cindex @code{a_}, stack item type
                   4482: Cell-aligned address
1.21      crook    4483: @item c-
1.1       anton    4484: @cindex @code{c_}, stack item type
                   4485: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    4486: @item f-
1.1       anton    4487: @cindex @code{f_}, stack item type
                   4488: Float-aligned address
1.21      crook    4489: @item df-
1.1       anton    4490: @cindex @code{df_}, stack item type
                   4491: Address aligned for IEEE double precision float
1.21      crook    4492: @item sf-
1.1       anton    4493: @cindex @code{sf_}, stack item type
                   4494: Address aligned for IEEE single precision float
                   4495: @item xt
                   4496: @cindex @code{xt}, stack item type
                   4497: Execution token, same size as Cell
                   4498: @item wid
                   4499: @cindex @code{wid}, stack item type
1.21      crook    4500: Word list ID, same size as Cell
1.68      anton    4501: @item ior, wior
                   4502: @cindex ior type description
                   4503: @cindex wior type description
                   4504: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
1.1       anton    4505: @item f83name
                   4506: @cindex @code{f83name}, stack item type
                   4507: Pointer to a name structure
                   4508: @item "
                   4509: @cindex @code{"}, stack item type
1.12      anton    4510: string in the input stream (not on the stack). The terminating character
                   4511: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    4512: quotes.
                   4513: @end table
                   4514: 
1.65      anton    4515: @comment ----------------------------------------------
                   4516: @node Case insensitivity, Comments, Notation, Words
                   4517: @section Case insensitivity
                   4518: @cindex case sensitivity
                   4519: @cindex upper and lower case
                   4520: 
                   4521: Gforth is case-insensitive; you can enter definitions and invoke
                   4522: Standard words using upper, lower or mixed case (however,
                   4523: @pxref{core-idef, Implementation-defined options, Implementation-defined
                   4524: options}).
                   4525: 
                   4526: ANS Forth only @i{requires} implementations to recognise Standard words
                   4527: when they are typed entirely in upper case. Therefore, a Standard
                   4528: program must use upper case for all Standard words. You can use whatever
                   4529: case you like for words that you define, but in a Standard program you
                   4530: have to use the words in the same case that you defined them.
                   4531: 
                   4532: Gforth supports case sensitivity through @code{table}s (case-sensitive
                   4533: wordlists, @pxref{Word Lists}).
                   4534: 
                   4535: Two people have asked how to convert Gforth to be case-sensitive; while
                   4536: we think this is a bad idea, you can change all wordlists into tables
                   4537: like this:
                   4538: 
                   4539: @example
                   4540: ' table-find forth-wordlist wordlist-map @ !
                   4541: @end example
                   4542: 
                   4543: Note that you now have to type the predefined words in the same case
                   4544: that we defined them, which are varying.  You may want to convert them
                   4545: to your favourite case before doing this operation (I won't explain how,
                   4546: because if you are even contemplating doing this, you'd better have
                   4547: enough knowledge of Forth systems to know this already).
                   4548: 
                   4549: @node Comments, Boolean Flags, Case insensitivity, Words
1.21      crook    4550: @section Comments
1.26      crook    4551: @cindex comments
1.21      crook    4552: 
1.29      crook    4553: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   4554: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    4555: 
1.44      crook    4556: 
1.23      crook    4557: doc-(
1.21      crook    4558: doc-\
1.23      crook    4559: doc-\G
1.21      crook    4560: 
1.44      crook    4561: 
1.21      crook    4562: @node Boolean Flags, Arithmetic, Comments, Words
                   4563: @section Boolean Flags
1.26      crook    4564: @cindex Boolean flags
1.21      crook    4565: 
                   4566: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   4567: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    4568: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    4569: a cell that has @i{any} bit set as @code{true}.
1.67      anton    4570: @c on and off to Memory? 
                   4571: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44      crook    4572: 
1.21      crook    4573: doc-true
                   4574: doc-false
1.29      crook    4575: doc-on
                   4576: doc-off
1.21      crook    4577: 
1.44      crook    4578: 
1.21      crook    4579: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    4580: @section Arithmetic
                   4581: @cindex arithmetic words
                   4582: 
                   4583: @cindex division with potentially negative operands
                   4584: Forth arithmetic is not checked, i.e., you will not hear about integer
                   4585: overflow on addition or multiplication, you may hear about division by
                   4586: zero if you are lucky. The operator is written after the operands, but
                   4587: the operands are still in the original order. I.e., the infix @code{2-1}
                   4588: corresponds to @code{2 1 -}. Forth offers a variety of division
                   4589: operators. If you perform division with potentially negative operands,
                   4590: you do not want to use @code{/} or @code{/mod} with its undefined
                   4591: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   4592: former, @pxref{Mixed precision}).
1.26      crook    4593: @comment TODO discuss the different division forms and the std approach
1.1       anton    4594: 
                   4595: @menu
                   4596: * Single precision::            
1.67      anton    4597: * Double precision::            Double-cell integer arithmetic
1.1       anton    4598: * Bitwise operations::          
1.67      anton    4599: * Numeric comparison::          
1.29      crook    4600: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    4601: * Floating Point::              
                   4602: @end menu
                   4603: 
1.67      anton    4604: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1       anton    4605: @subsection Single precision
                   4606: @cindex single precision arithmetic words
                   4607: 
1.67      anton    4608: @c !! cell undefined
                   4609: 
                   4610: By default, numbers in Forth are single-precision integers that are one
1.26      crook    4611: cell in size. They can be signed or unsigned, depending upon how you
1.49      anton    4612: treat them. For the rules used by the text interpreter for recognising
                   4613: single-precision integers see @ref{Number Conversion}.
1.21      crook    4614: 
1.67      anton    4615: These words are all defined for signed operands, but some of them also
                   4616: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
                   4617: @code{*}.
1.44      crook    4618: 
1.1       anton    4619: doc-+
1.21      crook    4620: doc-1+
1.128     anton    4621: doc-under+
1.1       anton    4622: doc--
1.21      crook    4623: doc-1-
1.1       anton    4624: doc-*
                   4625: doc-/
                   4626: doc-mod
                   4627: doc-/mod
                   4628: doc-negate
                   4629: doc-abs
                   4630: doc-min
                   4631: doc-max
1.27      crook    4632: doc-floored
1.1       anton    4633: 
1.44      crook    4634: 
1.67      anton    4635: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21      crook    4636: @subsection Double precision
                   4637: @cindex double precision arithmetic words
                   4638: 
1.49      anton    4639: For the rules used by the text interpreter for
                   4640: recognising double-precision integers, see @ref{Number Conversion}.
1.21      crook    4641: 
                   4642: A double precision number is represented by a cell pair, with the most
1.67      anton    4643: significant cell at the TOS. It is trivial to convert an unsigned single
                   4644: to a double: simply push a @code{0} onto the TOS. Since numbers are
                   4645: represented by Gforth using 2's complement arithmetic, converting a
                   4646: signed single to a (signed) double requires sign-extension across the
                   4647: most significant cell. This can be achieved using @code{s>d}. The moral
                   4648: of the story is that you cannot convert a number without knowing whether
                   4649: it represents an unsigned or a signed number.
1.21      crook    4650: 
1.67      anton    4651: These words are all defined for signed operands, but some of them also
                   4652: work for unsigned numbers: @code{d+}, @code{d-}.
1.44      crook    4653: 
1.21      crook    4654: doc-s>d
1.67      anton    4655: doc-d>s
1.21      crook    4656: doc-d+
                   4657: doc-d-
                   4658: doc-dnegate
                   4659: doc-dabs
                   4660: doc-dmin
                   4661: doc-dmax
                   4662: 
1.44      crook    4663: 
1.67      anton    4664: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
                   4665: @subsection Bitwise operations
                   4666: @cindex bitwise operation words
                   4667: 
                   4668: 
                   4669: doc-and
                   4670: doc-or
                   4671: doc-xor
                   4672: doc-invert
                   4673: doc-lshift
                   4674: doc-rshift
                   4675: doc-2*
                   4676: doc-d2*
                   4677: doc-2/
                   4678: doc-d2/
                   4679: 
                   4680: 
                   4681: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21      crook    4682: @subsection Numeric comparison
                   4683: @cindex numeric comparison words
                   4684: 
1.67      anton    4685: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
                   4686: d0= d0<>}) work for for both signed and unsigned numbers.
1.44      crook    4687: 
1.28      crook    4688: doc-<
                   4689: doc-<=
                   4690: doc-<>
                   4691: doc-=
                   4692: doc->
                   4693: doc->=
                   4694: 
1.21      crook    4695: doc-0<
1.23      crook    4696: doc-0<=
1.21      crook    4697: doc-0<>
                   4698: doc-0=
1.23      crook    4699: doc-0>
                   4700: doc-0>=
1.28      crook    4701: 
                   4702: doc-u<
                   4703: doc-u<=
1.44      crook    4704: @c u<> and u= exist but are the same as <> and =
1.31      anton    4705: @c doc-u<>
                   4706: @c doc-u=
1.28      crook    4707: doc-u>
                   4708: doc-u>=
                   4709: 
                   4710: doc-within
                   4711: 
                   4712: doc-d<
                   4713: doc-d<=
                   4714: doc-d<>
                   4715: doc-d=
                   4716: doc-d>
                   4717: doc-d>=
1.23      crook    4718: 
1.21      crook    4719: doc-d0<
1.23      crook    4720: doc-d0<=
                   4721: doc-d0<>
1.21      crook    4722: doc-d0=
1.23      crook    4723: doc-d0>
                   4724: doc-d0>=
                   4725: 
1.21      crook    4726: doc-du<
1.28      crook    4727: doc-du<=
1.44      crook    4728: @c du<> and du= exist but are the same as d<> and d=
1.31      anton    4729: @c doc-du<>
                   4730: @c doc-du=
1.28      crook    4731: doc-du>
                   4732: doc-du>=
1.1       anton    4733: 
1.44      crook    4734: 
1.21      crook    4735: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    4736: @subsection Mixed precision
                   4737: @cindex mixed precision arithmetic words
                   4738: 
1.44      crook    4739: 
1.1       anton    4740: doc-m+
                   4741: doc-*/
                   4742: doc-*/mod
                   4743: doc-m*
                   4744: doc-um*
                   4745: doc-m*/
                   4746: doc-um/mod
                   4747: doc-fm/mod
                   4748: doc-sm/rem
                   4749: 
1.44      crook    4750: 
1.21      crook    4751: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    4752: @subsection Floating Point
                   4753: @cindex floating point arithmetic words
                   4754: 
1.49      anton    4755: For the rules used by the text interpreter for
                   4756: recognising floating-point numbers see @ref{Number Conversion}.
1.1       anton    4757: 
1.67      anton    4758: Gforth has a separate floating point stack, but the documentation uses
                   4759: the unified notation.@footnote{It's easy to generate the separate
                   4760: notation from that by just separating the floating-point numbers out:
                   4761: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
                   4762: r3 )}.}
1.1       anton    4763: 
                   4764: @cindex floating-point arithmetic, pitfalls
                   4765: Floating point numbers have a number of unpleasant surprises for the
1.190     anton    4766: unwary (e.g., floating point addition is not associative) and even a
                   4767: few for the wary. You should not use them unless you know what you are
                   4768: doing or you don't care that the results you get are totally bogus. If
                   4769: you want to learn about the problems of floating point numbers (and
                   4770: how to avoid them), you might start with @cite{David Goldberg,
                   4771: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
                   4772: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
                   4773: Computing Surveys 23(1):5@minus{}48, March 1991}.
1.1       anton    4774: 
1.44      crook    4775: 
1.21      crook    4776: doc-d>f
                   4777: doc-f>d
1.1       anton    4778: doc-f+
                   4779: doc-f-
                   4780: doc-f*
                   4781: doc-f/
                   4782: doc-fnegate
                   4783: doc-fabs
                   4784: doc-fmax
                   4785: doc-fmin
                   4786: doc-floor
                   4787: doc-fround
                   4788: doc-f**
                   4789: doc-fsqrt
                   4790: doc-fexp
                   4791: doc-fexpm1
                   4792: doc-fln
                   4793: doc-flnp1
                   4794: doc-flog
                   4795: doc-falog
1.32      anton    4796: doc-f2*
                   4797: doc-f2/
                   4798: doc-1/f
                   4799: doc-precision
                   4800: doc-set-precision
                   4801: 
                   4802: @cindex angles in trigonometric operations
                   4803: @cindex trigonometric operations
                   4804: Angles in floating point operations are given in radians (a full circle
                   4805: has 2 pi radians).
                   4806: 
1.1       anton    4807: doc-fsin
                   4808: doc-fcos
                   4809: doc-fsincos
                   4810: doc-ftan
                   4811: doc-fasin
                   4812: doc-facos
                   4813: doc-fatan
                   4814: doc-fatan2
                   4815: doc-fsinh
                   4816: doc-fcosh
                   4817: doc-ftanh
                   4818: doc-fasinh
                   4819: doc-facosh
                   4820: doc-fatanh
1.21      crook    4821: doc-pi
1.28      crook    4822: 
1.32      anton    4823: @cindex equality of floats
                   4824: @cindex floating-point comparisons
1.31      anton    4825: One particular problem with floating-point arithmetic is that comparison
                   4826: for equality often fails when you would expect it to succeed.  For this
                   4827: reason approximate equality is often preferred (but you still have to
1.67      anton    4828: know what you are doing).  Also note that IEEE NaNs may compare
1.68      anton    4829: differently from what you might expect.  The comparison words are:
1.31      anton    4830: 
                   4831: doc-f~rel
                   4832: doc-f~abs
1.68      anton    4833: doc-f~
1.31      anton    4834: doc-f=
                   4835: doc-f<>
                   4836: 
                   4837: doc-f<
                   4838: doc-f<=
                   4839: doc-f>
                   4840: doc-f>=
                   4841: 
1.21      crook    4842: doc-f0<
1.28      crook    4843: doc-f0<=
                   4844: doc-f0<>
1.21      crook    4845: doc-f0=
1.28      crook    4846: doc-f0>
                   4847: doc-f0>=
                   4848: 
1.1       anton    4849: 
                   4850: @node Stack Manipulation, Memory, Arithmetic, Words
                   4851: @section Stack Manipulation
                   4852: @cindex stack manipulation words
                   4853: 
                   4854: @cindex floating-point stack in the standard
1.21      crook    4855: Gforth maintains a number of separate stacks:
                   4856: 
1.29      crook    4857: @cindex data stack
                   4858: @cindex parameter stack
1.21      crook    4859: @itemize @bullet
                   4860: @item
1.29      crook    4861: A data stack (also known as the @dfn{parameter stack}) -- for
                   4862: characters, cells, addresses, and double cells.
1.21      crook    4863: 
1.29      crook    4864: @cindex floating-point stack
1.21      crook    4865: @item
1.44      crook    4866: A floating point stack -- for holding floating point (FP) numbers.
1.21      crook    4867: 
1.29      crook    4868: @cindex return stack
1.21      crook    4869: @item
1.44      crook    4870: A return stack -- for holding the return addresses of colon
1.32      anton    4871: definitions and other (non-FP) data.
1.21      crook    4872: 
1.29      crook    4873: @cindex locals stack
1.21      crook    4874: @item
1.44      crook    4875: A locals stack -- for holding local variables.
1.21      crook    4876: @end itemize
                   4877: 
1.1       anton    4878: @menu
                   4879: * Data stack::                  
                   4880: * Floating point stack::        
                   4881: * Return stack::                
                   4882: * Locals stack::                
                   4883: * Stack pointer manipulation::  
                   4884: @end menu
                   4885: 
                   4886: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   4887: @subsection Data stack
                   4888: @cindex data stack manipulation words
                   4889: @cindex stack manipulations words, data stack
                   4890: 
1.44      crook    4891: 
1.1       anton    4892: doc-drop
                   4893: doc-nip
                   4894: doc-dup
                   4895: doc-over
                   4896: doc-tuck
                   4897: doc-swap
1.21      crook    4898: doc-pick
1.1       anton    4899: doc-rot
                   4900: doc--rot
                   4901: doc-?dup
                   4902: doc-roll
                   4903: doc-2drop
                   4904: doc-2nip
                   4905: doc-2dup
                   4906: doc-2over
                   4907: doc-2tuck
                   4908: doc-2swap
                   4909: doc-2rot
                   4910: 
1.44      crook    4911: 
1.1       anton    4912: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   4913: @subsection Floating point stack
                   4914: @cindex floating-point stack manipulation words
                   4915: @cindex stack manipulation words, floating-point stack
                   4916: 
1.32      anton    4917: Whilst every sane Forth has a separate floating-point stack, it is not
                   4918: strictly required; an ANS Forth system could theoretically keep
                   4919: floating-point numbers on the data stack. As an additional difficulty,
                   4920: you don't know how many cells a floating-point number takes. It is
                   4921: reportedly possible to write words in a way that they work also for a
                   4922: unified stack model, but we do not recommend trying it. Instead, just
                   4923: say that your program has an environmental dependency on a separate
                   4924: floating-point stack.
                   4925: 
                   4926: doc-floating-stack
                   4927: 
1.1       anton    4928: doc-fdrop
                   4929: doc-fnip
                   4930: doc-fdup
                   4931: doc-fover
                   4932: doc-ftuck
                   4933: doc-fswap
1.21      crook    4934: doc-fpick
1.1       anton    4935: doc-frot
                   4936: 
1.44      crook    4937: 
1.1       anton    4938: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   4939: @subsection Return stack
                   4940: @cindex return stack manipulation words
                   4941: @cindex stack manipulation words, return stack
                   4942: 
1.32      anton    4943: @cindex return stack and locals
                   4944: @cindex locals and return stack
                   4945: A Forth system is allowed to keep local variables on the
                   4946: return stack. This is reasonable, as local variables usually eliminate
                   4947: the need to use the return stack explicitly. So, if you want to produce
                   4948: a standard compliant program and you are using local variables in a
                   4949: word, forget about return stack manipulations in that word (refer to the
                   4950: standard document for the exact rules).
                   4951: 
1.1       anton    4952: doc->r
                   4953: doc-r>
                   4954: doc-r@
                   4955: doc-rdrop
                   4956: doc-2>r
                   4957: doc-2r>
                   4958: doc-2r@
                   4959: doc-2rdrop
                   4960: 
1.44      crook    4961: 
1.1       anton    4962: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   4963: @subsection Locals stack
                   4964: 
1.78      anton    4965: Gforth uses an extra locals stack.  It is described, along with the
                   4966: reasons for its existence, in @ref{Locals implementation}.
1.21      crook    4967: 
1.1       anton    4968: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   4969: @subsection Stack pointer manipulation
                   4970: @cindex stack pointer manipulation words
                   4971: 
1.44      crook    4972: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21      crook    4973: doc-sp0
1.1       anton    4974: doc-sp@
                   4975: doc-sp!
1.21      crook    4976: doc-fp0
1.1       anton    4977: doc-fp@
                   4978: doc-fp!
1.21      crook    4979: doc-rp0
1.1       anton    4980: doc-rp@
                   4981: doc-rp!
1.21      crook    4982: doc-lp0
1.1       anton    4983: doc-lp@
                   4984: doc-lp!
                   4985: 
1.44      crook    4986: 
1.1       anton    4987: @node Memory, Control Structures, Stack Manipulation, Words
                   4988: @section Memory
1.26      crook    4989: @cindex memory words
1.1       anton    4990: 
1.32      anton    4991: @menu
                   4992: * Memory model::                
                   4993: * Dictionary allocation::       
                   4994: * Heap Allocation::             
                   4995: * Memory Access::               
                   4996: * Address arithmetic::          
                   4997: * Memory Blocks::               
                   4998: @end menu
                   4999: 
1.67      anton    5000: In addition to the standard Forth memory allocation words, there is also
                   5001: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   5002: garbage collector}.
                   5003: 
1.32      anton    5004: @node Memory model, Dictionary allocation, Memory, Memory
                   5005: @subsection ANS Forth and Gforth memory models
                   5006: 
                   5007: @c The ANS Forth description is a mess (e.g., is the heap part of
                   5008: @c the dictionary?), so let's not stick to closely with it.
                   5009: 
1.67      anton    5010: ANS Forth considers a Forth system as consisting of several address
                   5011: spaces, of which only @dfn{data space} is managed and accessible with
                   5012: the memory words.  Memory not necessarily in data space includes the
                   5013: stacks, the code (called code space) and the headers (called name
                   5014: space). In Gforth everything is in data space, but the code for the
                   5015: primitives is usually read-only.
1.32      anton    5016: 
                   5017: Data space is divided into a number of areas: The (data space portion of
                   5018: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
                   5019: refer to the search data structure embodied in word lists and headers,
                   5020: because it is used for looking up names, just as you would in a
                   5021: conventional dictionary.}, the heap, and a number of system-allocated
                   5022: buffers.
                   5023: 
1.68      anton    5024: @cindex address arithmetic restrictions, ANS vs. Gforth
                   5025: @cindex contiguous regions, ANS vs. Gforth
1.32      anton    5026: In ANS Forth data space is also divided into contiguous regions.  You
                   5027: can only use address arithmetic within a contiguous region, not between
                   5028: them.  Usually each allocation gives you one contiguous region, but the
1.33      anton    5029: dictionary allocation words have additional rules (@pxref{Dictionary
1.32      anton    5030: allocation}).
                   5031: 
                   5032: Gforth provides one big address space, and address arithmetic can be
                   5033: performed between any addresses. However, in the dictionary headers or
                   5034: code are interleaved with data, so almost the only contiguous data space
                   5035: regions there are those described by ANS Forth as contiguous; but you
                   5036: can be sure that the dictionary is allocated towards increasing
                   5037: addresses even between contiguous regions.  The memory order of
                   5038: allocations in the heap is platform-dependent (and possibly different
                   5039: from one run to the next).
                   5040: 
1.27      crook    5041: 
1.32      anton    5042: @node Dictionary allocation, Heap Allocation, Memory model, Memory
                   5043: @subsection Dictionary allocation
1.27      crook    5044: @cindex reserving data space
                   5045: @cindex data space - reserving some
                   5046: 
1.32      anton    5047: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
                   5048: you want to deallocate X, you also deallocate everything
                   5049: allocated after X.
                   5050: 
1.68      anton    5051: @cindex contiguous regions in dictionary allocation
1.32      anton    5052: The allocations using the words below are contiguous and grow the region
                   5053: towards increasing addresses.  Other words that allocate dictionary
                   5054: memory of any kind (i.e., defining words including @code{:noname}) end
                   5055: the contiguous region and start a new one.
                   5056: 
                   5057: In ANS Forth only @code{create}d words are guaranteed to produce an
                   5058: address that is the start of the following contiguous region.  In
                   5059: particular, the cell allocated by @code{variable} is not guaranteed to
                   5060: be contiguous with following @code{allot}ed memory.
                   5061: 
                   5062: You can deallocate memory by using @code{allot} with a negative argument
                   5063: (with some restrictions, see @code{allot}). For larger deallocations use
                   5064: @code{marker}.
1.27      crook    5065: 
1.29      crook    5066: 
1.27      crook    5067: doc-here
                   5068: doc-unused
                   5069: doc-allot
                   5070: doc-c,
1.29      crook    5071: doc-f,
1.27      crook    5072: doc-,
                   5073: doc-2,
                   5074: 
1.32      anton    5075: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
                   5076: course you should allocate memory in an aligned way, too. I.e., before
                   5077: allocating allocating a cell, @code{here} must be cell-aligned, etc.
                   5078: The words below align @code{here} if it is not already.  Basically it is
                   5079: only already aligned for a type, if the last allocation was a multiple
                   5080: of the size of this type and if @code{here} was aligned for this type
                   5081: before.
                   5082: 
                   5083: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
                   5084: ANS Forth (@code{maxalign}ed in Gforth).
                   5085: 
                   5086: doc-align
                   5087: doc-falign
                   5088: doc-sfalign
                   5089: doc-dfalign
                   5090: doc-maxalign
                   5091: doc-cfalign
                   5092: 
                   5093: 
                   5094: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
                   5095: @subsection Heap allocation
                   5096: @cindex heap allocation
                   5097: @cindex dynamic allocation of memory
                   5098: @cindex memory-allocation word set
                   5099: 
1.68      anton    5100: @cindex contiguous regions and heap allocation
1.32      anton    5101: Heap allocation supports deallocation of allocated memory in any
                   5102: order. Dictionary allocation is not affected by it (i.e., it does not
                   5103: end a contiguous region). In Gforth, these words are implemented using
                   5104: the standard C library calls malloc(), free() and resize().
                   5105: 
1.68      anton    5106: The memory region produced by one invocation of @code{allocate} or
                   5107: @code{resize} is internally contiguous.  There is no contiguity between
                   5108: such a region and any other region (including others allocated from the
                   5109: heap).
                   5110: 
1.32      anton    5111: doc-allocate
                   5112: doc-free
                   5113: doc-resize
                   5114: 
1.27      crook    5115: 
1.32      anton    5116: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1       anton    5117: @subsection Memory Access
                   5118: @cindex memory access words
                   5119: 
                   5120: doc-@
                   5121: doc-!
                   5122: doc-+!
                   5123: doc-c@
                   5124: doc-c!
                   5125: doc-2@
                   5126: doc-2!
                   5127: doc-f@
                   5128: doc-f!
                   5129: doc-sf@
                   5130: doc-sf!
                   5131: doc-df@
                   5132: doc-df!
1.144     anton    5133: doc-sw@
                   5134: doc-uw@
                   5135: doc-w!
                   5136: doc-sl@
                   5137: doc-ul@
                   5138: doc-l!
1.68      anton    5139: 
1.32      anton    5140: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   5141: @subsection Address arithmetic
1.1       anton    5142: @cindex address arithmetic words
                   5143: 
1.67      anton    5144: Address arithmetic is the foundation on which you can build data
                   5145: structures like arrays, records (@pxref{Structures}) and objects
                   5146: (@pxref{Object-oriented Forth}).
1.32      anton    5147: 
1.68      anton    5148: @cindex address unit
                   5149: @cindex au (address unit)
1.1       anton    5150: ANS Forth does not specify the sizes of the data types. Instead, it
                   5151: offers a number of words for computing sizes and doing address
1.29      crook    5152: arithmetic. Address arithmetic is performed in terms of address units
                   5153: (aus); on most systems the address unit is one byte. Note that a
                   5154: character may have more than one au, so @code{chars} is no noop (on
1.68      anton    5155: platforms where it is a noop, it compiles to nothing).
1.1       anton    5156: 
1.67      anton    5157: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
                   5158: you have the address of a cell, perform @code{1 cells +}, and you will
                   5159: have the address of the next cell.
                   5160: 
1.68      anton    5161: @cindex contiguous regions and address arithmetic
1.67      anton    5162: In ANS Forth you can perform address arithmetic only within a contiguous
                   5163: region, i.e., if you have an address into one region, you can only add
                   5164: and subtract such that the result is still within the region; you can
                   5165: only subtract or compare addresses from within the same contiguous
                   5166: region.  Reasons: several contiguous regions can be arranged in memory
                   5167: in any way; on segmented systems addresses may have unusual
                   5168: representations, such that address arithmetic only works within a
                   5169: region.  Gforth provides a few more guarantees (linear address space,
                   5170: dictionary grows upwards), but in general I have found it easy to stay
                   5171: within contiguous regions (exception: computing and comparing to the
                   5172: address just beyond the end of an array).
                   5173: 
1.1       anton    5174: @cindex alignment of addresses for types
                   5175: ANS Forth also defines words for aligning addresses for specific
                   5176: types. Many computers require that accesses to specific data types
                   5177: must only occur at specific addresses; e.g., that cells may only be
                   5178: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   5179: accesses, it can usually perform aligned accesses faster. 
                   5180: 
                   5181: For the performance-conscious: alignment operations are usually only
                   5182: necessary during the definition of a data structure, not during the
                   5183: (more frequent) accesses to it.
                   5184: 
                   5185: ANS Forth defines no words for character-aligning addresses. This is not
                   5186: an oversight, but reflects the fact that addresses that are not
                   5187: char-aligned have no use in the standard and therefore will not be
                   5188: created.
                   5189: 
                   5190: @cindex @code{CREATE} and alignment
1.29      crook    5191: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    5192: are cell-aligned; in addition, Gforth guarantees that these addresses
                   5193: are aligned for all purposes.
                   5194: 
1.26      crook    5195: Note that the ANS Forth word @code{char} has nothing to do with address
                   5196: arithmetic.
1.1       anton    5197: 
1.44      crook    5198: 
1.1       anton    5199: doc-chars
                   5200: doc-char+
                   5201: doc-cells
                   5202: doc-cell+
                   5203: doc-cell
                   5204: doc-aligned
                   5205: doc-floats
                   5206: doc-float+
                   5207: doc-float
                   5208: doc-faligned
                   5209: doc-sfloats
                   5210: doc-sfloat+
                   5211: doc-sfaligned
                   5212: doc-dfloats
                   5213: doc-dfloat+
                   5214: doc-dfaligned
                   5215: doc-maxaligned
                   5216: doc-cfaligned
                   5217: doc-address-unit-bits
1.145     anton    5218: doc-/w
                   5219: doc-/l
1.44      crook    5220: 
1.32      anton    5221: @node Memory Blocks,  , Address arithmetic, Memory
1.1       anton    5222: @subsection Memory Blocks
                   5223: @cindex memory block words
1.27      crook    5224: @cindex character strings - moving and copying
                   5225: 
1.49      anton    5226: Memory blocks often represent character strings; For ways of storing
                   5227: character strings in memory see @ref{String Formats}.  For other
                   5228: string-processing words see @ref{Displaying characters and strings}.
1.1       anton    5229: 
1.67      anton    5230: A few of these words work on address unit blocks.  In that case, you
                   5231: usually have to insert @code{CHARS} before the word when working on
                   5232: character strings.  Most words work on character blocks, and expect a
                   5233: char-aligned address.
                   5234: 
                   5235: When copying characters between overlapping memory regions, use
                   5236: @code{chars move} or choose carefully between @code{cmove} and
                   5237: @code{cmove>}.
1.44      crook    5238: 
1.1       anton    5239: doc-move
                   5240: doc-erase
                   5241: doc-cmove
                   5242: doc-cmove>
                   5243: doc-fill
                   5244: doc-blank
1.21      crook    5245: doc-compare
1.111     anton    5246: doc-str=
                   5247: doc-str<
                   5248: doc-string-prefix?
1.21      crook    5249: doc-search
1.27      crook    5250: doc--trailing
                   5251: doc-/string
1.82      anton    5252: doc-bounds
1.141     anton    5253: doc-pad
1.111     anton    5254: 
1.27      crook    5255: @comment TODO examples
                   5256: 
1.1       anton    5257: 
1.26      crook    5258: @node Control Structures, Defining Words, Memory, Words
1.1       anton    5259: @section Control Structures
                   5260: @cindex control structures
                   5261: 
1.33      anton    5262: Control structures in Forth cannot be used interpretively, only in a
                   5263: colon definition@footnote{To be precise, they have no interpretation
                   5264: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
                   5265: not like this limitation, but have not seen a satisfying way around it
                   5266: yet, although many schemes have been proposed.
1.1       anton    5267: 
                   5268: @menu
1.33      anton    5269: * Selection::                   IF ... ELSE ... ENDIF
                   5270: * Simple Loops::                BEGIN ...
1.29      crook    5271: * Counted Loops::               DO
1.67      anton    5272: * Arbitrary control structures::  
                   5273: * Calls and returns::           
1.1       anton    5274: * Exception Handling::          
                   5275: @end menu
                   5276: 
                   5277: @node Selection, Simple Loops, Control Structures, Control Structures
                   5278: @subsection Selection
                   5279: @cindex selection control structures
                   5280: @cindex control structures for selection
                   5281: 
                   5282: @cindex @code{IF} control structure
                   5283: @example
1.29      crook    5284: @i{flag}
1.1       anton    5285: IF
1.29      crook    5286:   @i{code}
1.1       anton    5287: ENDIF
                   5288: @end example
1.21      crook    5289: @noindent
1.33      anton    5290: 
1.44      crook    5291: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
                   5292: with any bit set represents truth) @i{code} is executed.
1.33      anton    5293: 
1.1       anton    5294: @example
1.29      crook    5295: @i{flag}
1.1       anton    5296: IF
1.29      crook    5297:   @i{code1}
1.1       anton    5298: ELSE
1.29      crook    5299:   @i{code2}
1.1       anton    5300: ENDIF
                   5301: @end example
                   5302: 
1.44      crook    5303: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
                   5304: executed.
1.33      anton    5305: 
1.1       anton    5306: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   5307: standard, and @code{ENDIF} is not, although it is quite popular. We
                   5308: recommend using @code{ENDIF}, because it is less confusing for people
                   5309: who also know other languages (and is not prone to reinforcing negative
                   5310: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   5311: system that only supplies @code{THEN} is simple:
                   5312: @example
1.82      anton    5313: : ENDIF   POSTPONE then ; immediate
1.1       anton    5314: @end example
                   5315: 
                   5316: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   5317: (adv.)}  has the following meanings:
                   5318: @quotation
                   5319: ... 2b: following next after in order ... 3d: as a necessary consequence
                   5320: (if you were there, then you saw them).
                   5321: @end quotation
                   5322: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   5323: and many other programming languages has the meaning 3d.]
                   5324: 
1.21      crook    5325: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    5326: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    5327: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    5328: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   5329: @file{compat/control.fs}.
                   5330: 
                   5331: @cindex @code{CASE} control structure
                   5332: @example
1.29      crook    5333: @i{n}
1.1       anton    5334: CASE
1.29      crook    5335:   @i{n1} OF @i{code1} ENDOF
                   5336:   @i{n2} OF @i{code2} ENDOF
1.1       anton    5337:   @dots{}
1.68      anton    5338:   ( n ) @i{default-code} ( n )
1.131     anton    5339: ENDCASE ( )
1.1       anton    5340: @end example
                   5341: 
1.131     anton    5342: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If
                   5343: no @i{ni} matches, the optional @i{default-code} is executed. The
                   5344: optional default case can be added by simply writing the code after
                   5345: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
                   5346: but must not consume it.  The value @i{n} is consumed by this
                   5347: construction (either by a OF that matches, or by the ENDCASE, if no OF
                   5348: matches).
1.1       anton    5349: 
1.69      anton    5350: @progstyle
1.131     anton    5351: To keep the code understandable, you should ensure that you change the
                   5352: stack in the same way (wrt. number and types of stack items consumed
                   5353: and pushed) on all paths through a selection construct.
1.69      anton    5354: 
1.1       anton    5355: @node Simple Loops, Counted Loops, Selection, Control Structures
                   5356: @subsection Simple Loops
                   5357: @cindex simple loops
                   5358: @cindex loops without count 
                   5359: 
                   5360: @cindex @code{WHILE} loop
                   5361: @example
                   5362: BEGIN
1.29      crook    5363:   @i{code1}
                   5364:   @i{flag}
1.1       anton    5365: WHILE
1.29      crook    5366:   @i{code2}
1.1       anton    5367: REPEAT
                   5368: @end example
                   5369: 
1.29      crook    5370: @i{code1} is executed and @i{flag} is computed. If it is true,
                   5371: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    5372: false, execution continues after the @code{REPEAT}.
                   5373: 
                   5374: @cindex @code{UNTIL} loop
                   5375: @example
                   5376: BEGIN
1.29      crook    5377:   @i{code}
                   5378:   @i{flag}
1.1       anton    5379: UNTIL
                   5380: @end example
                   5381: 
1.29      crook    5382: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    5383: 
1.69      anton    5384: @progstyle
                   5385: To keep the code understandable, a complete iteration of the loop should
                   5386: not change the number and types of the items on the stacks.
                   5387: 
1.1       anton    5388: @cindex endless loop
                   5389: @cindex loops, endless
                   5390: @example
                   5391: BEGIN
1.29      crook    5392:   @i{code}
1.1       anton    5393: AGAIN
                   5394: @end example
                   5395: 
                   5396: This is an endless loop.
                   5397: 
                   5398: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   5399: @subsection Counted Loops
                   5400: @cindex counted loops
                   5401: @cindex loops, counted
                   5402: @cindex @code{DO} loops
                   5403: 
                   5404: The basic counted loop is:
                   5405: @example
1.29      crook    5406: @i{limit} @i{start}
1.1       anton    5407: ?DO
1.29      crook    5408:   @i{body}
1.1       anton    5409: LOOP
                   5410: @end example
                   5411: 
1.29      crook    5412: This performs one iteration for every integer, starting from @i{start}
                   5413: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    5414: accessed with @code{i}. For example, the loop:
1.1       anton    5415: @example
                   5416: 10 0 ?DO
                   5417:   i .
                   5418: LOOP
                   5419: @end example
1.21      crook    5420: @noindent
                   5421: prints @code{0 1 2 3 4 5 6 7 8 9}
                   5422: 
1.1       anton    5423: The index of the innermost loop can be accessed with @code{i}, the index
                   5424: of the next loop with @code{j}, and the index of the third loop with
                   5425: @code{k}.
                   5426: 
1.44      crook    5427: 
1.1       anton    5428: doc-i
                   5429: doc-j
                   5430: doc-k
                   5431: 
1.44      crook    5432: 
1.1       anton    5433: The loop control data are kept on the return stack, so there are some
1.21      crook    5434: restrictions on mixing return stack accesses and counted loop words. In
                   5435: particuler, if you put values on the return stack outside the loop, you
                   5436: cannot read them inside the loop@footnote{well, not in a way that is
                   5437: portable.}. If you put values on the return stack within a loop, you
                   5438: have to remove them before the end of the loop and before accessing the
                   5439: index of the loop.
1.1       anton    5440: 
                   5441: There are several variations on the counted loop:
                   5442: 
1.21      crook    5443: @itemize @bullet
                   5444: @item
                   5445: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   5446: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   5447: 
                   5448: @example
                   5449: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   5450: @end example
                   5451: prints @code{0 1 2 3}
                   5452: 
1.1       anton    5453: 
1.21      crook    5454: @item
                   5455: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   5456: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   5457: return stack so @code{EXIT} can get to its return address. For example:
                   5458: 
                   5459: @example
                   5460: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   5461: @end example
                   5462: prints @code{0 1 2 3}
                   5463: 
                   5464: 
                   5465: @item
1.29      crook    5466: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    5467: (and @code{LOOP} iterates until they become equal by wrap-around
                   5468: arithmetic). This behaviour is usually not what you want. Therefore,
                   5469: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    5470: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   5471: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    5472: unsigned loop parameters.
                   5473: 
1.21      crook    5474: @item
                   5475: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   5476: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   5477: if you know that the loop is entered in any case. Such knowledge tends
                   5478: to become invalid during maintenance of a program, and then the
                   5479: @code{DO} will make trouble.
                   5480: 
                   5481: @item
1.29      crook    5482: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   5483: index by @i{n} instead of by 1. The loop is terminated when the border
                   5484: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    5485: 
1.21      crook    5486: @example
                   5487: 4 0 +DO  i .  2 +LOOP
                   5488: @end example
                   5489: @noindent
                   5490: prints @code{0 2}
                   5491: 
                   5492: @example
                   5493: 4 1 +DO  i .  2 +LOOP
                   5494: @end example
                   5495: @noindent
                   5496: prints @code{1 3}
1.1       anton    5497: 
1.68      anton    5498: @item
1.1       anton    5499: @cindex negative increment for counted loops
                   5500: @cindex counted loops with negative increment
1.29      crook    5501: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    5502: 
1.21      crook    5503: @example
                   5504: -1 0 ?DO  i .  -1 +LOOP
                   5505: @end example
                   5506: @noindent
                   5507: prints @code{0 -1}
1.1       anton    5508: 
1.21      crook    5509: @example
                   5510: 0 0 ?DO  i .  -1 +LOOP
                   5511: @end example
                   5512: prints nothing.
1.1       anton    5513: 
1.29      crook    5514: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   5515: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   5516: index by @i{u} each iteration. The loop is terminated when the border
                   5517: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    5518: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   5519: 
1.21      crook    5520: @example
                   5521: -2 0 -DO  i .  1 -LOOP
                   5522: @end example
                   5523: @noindent
                   5524: prints @code{0 -1}
1.1       anton    5525: 
1.21      crook    5526: @example
                   5527: -1 0 -DO  i .  1 -LOOP
                   5528: @end example
                   5529: @noindent
                   5530: prints @code{0}
                   5531: 
                   5532: @example
                   5533: 0 0 -DO  i .  1 -LOOP
                   5534: @end example
                   5535: @noindent
                   5536: prints nothing.
1.1       anton    5537: 
1.21      crook    5538: @end itemize
1.1       anton    5539: 
                   5540: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    5541: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   5542: for these words that uses only standard words is provided in
                   5543: @file{compat/loops.fs}.
1.1       anton    5544: 
                   5545: 
                   5546: @cindex @code{FOR} loops
1.26      crook    5547: Another counted loop is:
1.1       anton    5548: @example
1.29      crook    5549: @i{n}
1.1       anton    5550: FOR
1.29      crook    5551:   @i{body}
1.1       anton    5552: NEXT
                   5553: @end example
                   5554: This is the preferred loop of native code compiler writers who are too
1.26      crook    5555: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    5556: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   5557: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    5558: Forth systems may behave differently, even if they support @code{FOR}
                   5559: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    5560: 
                   5561: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   5562: @subsection Arbitrary control structures
                   5563: @cindex control structures, user-defined
                   5564: 
                   5565: @cindex control-flow stack
                   5566: ANS Forth permits and supports using control structures in a non-nested
                   5567: way. Information about incomplete control structures is stored on the
                   5568: control-flow stack. This stack may be implemented on the Forth data
                   5569: stack, and this is what we have done in Gforth.
                   5570: 
                   5571: @cindex @code{orig}, control-flow stack item
                   5572: @cindex @code{dest}, control-flow stack item
                   5573: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   5574: entry represents a backward branch target. A few words are the basis for
                   5575: building any control structure possible (except control structures that
                   5576: need storage, like calls, coroutines, and backtracking).
                   5577: 
1.44      crook    5578: 
1.1       anton    5579: doc-if
                   5580: doc-ahead
                   5581: doc-then
                   5582: doc-begin
                   5583: doc-until
                   5584: doc-again
                   5585: doc-cs-pick
                   5586: doc-cs-roll
                   5587: 
1.44      crook    5588: 
1.21      crook    5589: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   5590: manipulate the control-flow stack in a portable way. Without them, you
                   5591: would need to know how many stack items are occupied by a control-flow
                   5592: entry (many systems use one cell. In Gforth they currently take three,
                   5593: but this may change in the future).
                   5594: 
1.1       anton    5595: Some standard control structure words are built from these words:
                   5596: 
1.44      crook    5597: 
1.1       anton    5598: doc-else
                   5599: doc-while
                   5600: doc-repeat
                   5601: 
1.44      crook    5602: 
                   5603: @noindent
1.1       anton    5604: Gforth adds some more control-structure words:
                   5605: 
1.44      crook    5606: 
1.1       anton    5607: doc-endif
                   5608: doc-?dup-if
                   5609: doc-?dup-0=-if
                   5610: 
1.44      crook    5611: 
                   5612: @noindent
1.1       anton    5613: Counted loop words constitute a separate group of words:
                   5614: 
1.44      crook    5615: 
1.1       anton    5616: doc-?do
                   5617: doc-+do
                   5618: doc-u+do
                   5619: doc--do
                   5620: doc-u-do
                   5621: doc-do
                   5622: doc-for
                   5623: doc-loop
                   5624: doc-+loop
                   5625: doc--loop
                   5626: doc-next
                   5627: doc-leave
                   5628: doc-?leave
                   5629: doc-unloop
                   5630: doc-done
                   5631: 
1.44      crook    5632: 
1.21      crook    5633: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   5634: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    5635: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   5636: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   5637: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   5638: resolved (by using one of the loop-ending words or @code{DONE}).
                   5639: 
1.44      crook    5640: @noindent
1.26      crook    5641: Another group of control structure words are:
1.1       anton    5642: 
1.44      crook    5643: 
1.1       anton    5644: doc-case
                   5645: doc-endcase
                   5646: doc-of
                   5647: doc-endof
                   5648: 
1.44      crook    5649: 
1.21      crook    5650: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   5651: @code{CS-ROLL}.
1.1       anton    5652: 
                   5653: @subsubsection Programming Style
1.47      crook    5654: @cindex control structures programming style
                   5655: @cindex programming style, arbitrary control structures
1.1       anton    5656: 
                   5657: In order to ensure readability we recommend that you do not create
                   5658: arbitrary control structures directly, but define new control structure
                   5659: words for the control structure you want and use these words in your
1.26      crook    5660: program. For example, instead of writing:
1.1       anton    5661: 
                   5662: @example
1.26      crook    5663: BEGIN
1.1       anton    5664:   ...
1.26      crook    5665: IF [ 1 CS-ROLL ]
1.1       anton    5666:   ...
1.26      crook    5667: AGAIN THEN
1.1       anton    5668: @end example
                   5669: 
1.21      crook    5670: @noindent
1.1       anton    5671: we recommend defining control structure words, e.g.,
                   5672: 
                   5673: @example
1.26      crook    5674: : WHILE ( DEST -- ORIG DEST )
                   5675:  POSTPONE IF
                   5676:  1 CS-ROLL ; immediate
                   5677: 
                   5678: : REPEAT ( orig dest -- )
                   5679:  POSTPONE AGAIN
                   5680:  POSTPONE THEN ; immediate
1.1       anton    5681: @end example
                   5682: 
1.21      crook    5683: @noindent
1.1       anton    5684: and then using these to create the control structure:
                   5685: 
                   5686: @example
1.26      crook    5687: BEGIN
1.1       anton    5688:   ...
1.26      crook    5689: WHILE
1.1       anton    5690:   ...
1.26      crook    5691: REPEAT
1.1       anton    5692: @end example
                   5693: 
                   5694: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   5695: @code{WHILE} are predefined, so in this example it would not be
                   5696: necessary to define them.
                   5697: 
                   5698: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   5699: @subsection Calls and returns
                   5700: @cindex calling a definition
                   5701: @cindex returning from a definition
                   5702: 
1.3       anton    5703: @cindex recursive definitions
                   5704: A definition can be called simply be writing the name of the definition
1.26      crook    5705: to be called. Normally a definition is invisible during its own
1.3       anton    5706: definition. If you want to write a directly recursive definition, you
1.26      crook    5707: can use @code{recursive} to make the current definition visible, or
                   5708: @code{recurse} to call the current definition directly.
1.3       anton    5709: 
1.44      crook    5710: 
1.3       anton    5711: doc-recursive
                   5712: doc-recurse
                   5713: 
1.44      crook    5714: 
1.21      crook    5715: @comment TODO add example of the two recursion methods
1.12      anton    5716: @quotation
                   5717: @progstyle
                   5718: I prefer using @code{recursive} to @code{recurse}, because calling the
                   5719: definition by name is more descriptive (if the name is well-chosen) than
                   5720: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   5721: implementation, it is much better to read (and think) ``now sort the
                   5722: partitions'' than to read ``now do a recursive call''.
                   5723: @end quotation
1.3       anton    5724: 
1.29      crook    5725: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    5726: 
                   5727: @example
1.28      crook    5728: Defer foo
1.3       anton    5729: 
                   5730: : bar ( ... -- ... )
                   5731:  ... foo ... ;
                   5732: 
                   5733: :noname ( ... -- ... )
                   5734:  ... bar ... ;
                   5735: IS foo
                   5736: @end example
                   5737: 
1.170     pazsan   5738: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33      anton    5739: 
1.26      crook    5740: The current definition returns control to the calling definition when
1.33      anton    5741: the end of the definition is reached or @code{EXIT} is encountered.
1.1       anton    5742: 
                   5743: doc-exit
                   5744: doc-;s
                   5745: 
1.44      crook    5746: 
1.1       anton    5747: @node Exception Handling,  , Calls and returns, Control Structures
                   5748: @subsection Exception Handling
1.26      crook    5749: @cindex exceptions
1.1       anton    5750: 
1.68      anton    5751: @c quit is a very bad idea for error handling, 
                   5752: @c because it does not translate into a THROW
                   5753: @c it also does not belong into this chapter
                   5754: 
                   5755: If a word detects an error condition that it cannot handle, it can
                   5756: @code{throw} an exception.  In the simplest case, this will terminate
                   5757: your program, and report an appropriate error.
1.21      crook    5758: 
1.68      anton    5759: doc-throw
1.1       anton    5760: 
1.69      anton    5761: @code{Throw} consumes a cell-sized error number on the stack. There are
                   5762: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
                   5763: Gforth (and most other systems) you can use the iors produced by various
                   5764: words as error numbers (e.g., a typical use of @code{allocate} is
                   5765: @code{allocate throw}).  Gforth also provides the word @code{exception}
                   5766: to define your own error numbers (with decent error reporting); an ANS
                   5767: Forth version of this word (but without the error messages) is available
                   5768: in @code{compat/except.fs}.  And finally, you can use your own error
1.68      anton    5769: numbers (anything outside the range -4095..0), but won't get nice error
                   5770: messages, only numbers.  For example, try:
                   5771: 
                   5772: @example
1.69      anton    5773: -10 throw                    \ ANS defined
                   5774: -267 throw                   \ system defined
                   5775: s" my error" exception throw \ user defined
                   5776: 7 throw                      \ arbitrary number
1.68      anton    5777: @end example
                   5778: 
                   5779: doc---exception-exception
1.1       anton    5780: 
1.69      anton    5781: A common idiom to @code{THROW} a specific error if a flag is true is
                   5782: this:
                   5783: 
                   5784: @example
                   5785: @code{( flag ) 0<> @i{errno} and throw}
                   5786: @end example
                   5787: 
                   5788: Your program can provide exception handlers to catch exceptions.  An
                   5789: exception handler can be used to correct the problem, or to clean up
                   5790: some data structures and just throw the exception to the next exception
                   5791: handler.  Note that @code{throw} jumps to the dynamically innermost
                   5792: exception handler.  The system's exception handler is outermost, and just
                   5793: prints an error and restarts command-line interpretation (or, in batch
                   5794: mode (i.e., while processing the shell command line), leaves Gforth).
1.1       anton    5795: 
1.68      anton    5796: The ANS Forth way to catch exceptions is @code{catch}:
1.1       anton    5797: 
1.68      anton    5798: doc-catch
1.160     anton    5799: doc-nothrow
1.68      anton    5800: 
                   5801: The most common use of exception handlers is to clean up the state when
                   5802: an error happens.  E.g.,
1.1       anton    5803: 
1.26      crook    5804: @example
1.68      anton    5805: base @ >r hex \ actually the hex should be inside foo, or we h
                   5806: ['] foo catch ( nerror|0 )
                   5807: r> base !
1.69      anton    5808: ( nerror|0 ) throw \ pass it on
1.26      crook    5809: @end example
1.1       anton    5810: 
1.69      anton    5811: A use of @code{catch} for handling the error @code{myerror} might look
                   5812: like this:
1.44      crook    5813: 
1.68      anton    5814: @example
1.69      anton    5815: ['] foo catch
                   5816: CASE
1.160     anton    5817:   myerror OF ... ( do something about it ) nothrow ENDOF
1.69      anton    5818:   dup throw \ default: pass other errors on, do nothing on non-errors
                   5819: ENDCASE
1.68      anton    5820: @end example
1.44      crook    5821: 
1.68      anton    5822: Having to wrap the code into a separate word is often cumbersome,
                   5823: therefore Gforth provides an alternative syntax:
1.1       anton    5824: 
                   5825: @example
1.69      anton    5826: TRY
1.68      anton    5827:   @i{code1}
1.172     anton    5828:   IFERROR
                   5829:     @i{code2}
                   5830:   THEN
                   5831:   @i{code3}
1.69      anton    5832: ENDTRY
1.1       anton    5833: @end example
                   5834: 
1.172     anton    5835: This performs @i{code1}.  If @i{code1} completes normally, execution
1.201     anton    5836: continues with @i{code3}.  If there is an exception in @i{code1} or
                   5837: before @code{endtry}, the stacks are reset to the depth during
1.172     anton    5838: @code{try}, the throw value is pushed on the data stack, and execution
1.201     anton    5839: constinues at @i{code2}, and finally falls through to @i{code3}.
1.26      crook    5840: 
1.68      anton    5841: doc-try
                   5842: doc-endtry
1.172     anton    5843: doc-iferror
                   5844: 
                   5845: If you don't need @i{code2}, you can write @code{restore} instead of
                   5846: @code{iferror then}:
                   5847: 
                   5848: @example
                   5849: TRY
                   5850:   @i{code1}
                   5851: RESTORE
                   5852:   @i{code3}
                   5853: ENDTRY
                   5854: @end example
1.26      crook    5855: 
1.172     anton    5856: @cindex unwind-protect
1.69      anton    5857: The cleanup example from above in this syntax:
1.26      crook    5858: 
1.68      anton    5859: @example
1.174     anton    5860: base @@ @{ oldbase @}
1.172     anton    5861: TRY
1.68      anton    5862:   hex foo \ now the hex is placed correctly
1.69      anton    5863:   0       \ value for throw
1.172     anton    5864: RESTORE
                   5865:   oldbase base !
                   5866: ENDTRY
                   5867: throw
1.1       anton    5868: @end example
                   5869: 
1.172     anton    5870: An additional advantage of this variant is that an exception between
                   5871: @code{restore} and @code{endtry} (e.g., from the user pressing
                   5872: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
                   5873: so the base will be restored under all circumstances.
                   5874: 
                   5875: However, you have to ensure that this code does not cause an exception
                   5876: itself, otherwise the @code{iferror}/@code{restore} code will loop.
                   5877: Moreover, you should also make sure that the stack contents needed by
                   5878: the @code{iferror}/@code{restore} code exist everywhere between
                   5879: @code{try} and @code{endtry}; in our example this is achived by
                   5880: putting the data in a local before the @code{try} (you cannot use the
                   5881: return stack because the exception frame (@i{sys1}) is in the way
                   5882: there).
                   5883: 
                   5884: This kind of usage corresponds to Lisp's @code{unwind-protect}.
                   5885: 
                   5886: @cindex @code{recover} (old Gforth versions)
                   5887: If you do not want this exception-restarting behaviour, you achieve
                   5888: this as follows:
                   5889: 
                   5890: @example
                   5891: TRY
                   5892:   @i{code1}
                   5893: ENDTRY-IFERROR
                   5894:   @i{code2}
                   5895: THEN
                   5896: @end example
                   5897: 
                   5898: If there is an exception in @i{code1}, then @i{code2} is executed,
                   5899: otherwise execution continues behind the @code{then} (or in a possible
                   5900: @code{else} branch).  This corresponds to the construct
                   5901: 
                   5902: @example
                   5903: TRY
                   5904:   @i{code1}
                   5905: RECOVER
                   5906:   @i{code2}
                   5907: ENDTRY
                   5908: @end example
                   5909: 
                   5910: in Gforth before version 0.7.  So you can directly replace
                   5911: @code{recover}-using code; however, we recommend that you check if it
                   5912: would not be better to use one of the other @code{try} variants while
                   5913: you are at it.
                   5914: 
1.173     anton    5915: To ease the transition, Gforth provides two compatibility files:
                   5916: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
                   5917: ... then} syntax (but not @code{iferror} or @code{restore}) for old
                   5918: systems; @file{recover-endtry.fs} provides the @code{try ... recover
                   5919: ... endtry} syntax on new systems, so you can use that file as a
                   5920: stopgap to run old programs.  Both files work on any system (they just
                   5921: do nothing if the system already has the syntax it implements), so you
                   5922: can unconditionally @code{require} one of these files, even if you use
                   5923: a mix old and new systems.
                   5924: 
1.172     anton    5925: doc-restore
                   5926: doc-endtry-iferror
                   5927: 
                   5928: Here's the error handling example:
1.1       anton    5929: 
1.68      anton    5930: @example
1.69      anton    5931: TRY
1.68      anton    5932:   foo
1.172     anton    5933: ENDTRY-IFERROR
1.69      anton    5934:   CASE
1.160     anton    5935:     myerror OF ... ( do something about it ) nothrow ENDOF
1.69      anton    5936:     throw \ pass other errors on
                   5937:   ENDCASE
1.172     anton    5938: THEN
1.68      anton    5939: @end example
1.1       anton    5940: 
1.69      anton    5941: @progstyle
                   5942: As usual, you should ensure that the stack depth is statically known at
                   5943: the end: either after the @code{throw} for passing on errors, or after
                   5944: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
                   5945: selection construct for handling the error).
                   5946: 
1.68      anton    5947: There are two alternatives to @code{throw}: @code{Abort"} is conditional
                   5948: and you can provide an error message.  @code{Abort} just produces an
                   5949: ``Aborted'' error.
1.1       anton    5950: 
1.68      anton    5951: The problem with these words is that exception handlers cannot
                   5952: differentiate between different @code{abort"}s; they just look like
                   5953: @code{-2 throw} to them (the error message cannot be accessed by
                   5954: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
                   5955: exception handlers.
1.44      crook    5956: 
1.68      anton    5957: doc-abort"
1.26      crook    5958: doc-abort
1.29      crook    5959: 
                   5960: 
1.44      crook    5961: 
1.29      crook    5962: @c -------------------------------------------------------------
1.47      crook    5963: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29      crook    5964: @section Defining Words
                   5965: @cindex defining words
                   5966: 
1.47      crook    5967: Defining words are used to extend Forth by creating new entries in the dictionary.
                   5968: 
1.29      crook    5969: @menu
1.67      anton    5970: * CREATE::                      
1.44      crook    5971: * Variables::                   Variables and user variables
1.67      anton    5972: * Constants::                   
1.44      crook    5973: * Values::                      Initialised variables
1.67      anton    5974: * Colon Definitions::           
1.44      crook    5975: * Anonymous Definitions::       Definitions without names
1.69      anton    5976: * Supplying names::             Passing definition names as strings
1.67      anton    5977: * User-defined Defining Words::  
1.170     pazsan   5978: * Deferred Words::              Allow forward references
1.67      anton    5979: * Aliases::                     
1.29      crook    5980: @end menu
                   5981: 
1.44      crook    5982: @node CREATE, Variables, Defining Words, Defining Words
                   5983: @subsection @code{CREATE}
1.29      crook    5984: @cindex simple defining words
                   5985: @cindex defining words, simple
                   5986: 
                   5987: Defining words are used to create new entries in the dictionary. The
                   5988: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   5989: this:
                   5990: 
                   5991: @example
                   5992: CREATE new-word1
                   5993: @end example
                   5994: 
1.69      anton    5995: @code{CREATE} is a parsing word, i.e., it takes an argument from the
                   5996: input stream (@code{new-word1} in our example).  It generates a
                   5997: dictionary entry for @code{new-word1}. When @code{new-word1} is
                   5998: executed, all that it does is leave an address on the stack. The address
                   5999: represents the value of the data space pointer (@code{HERE}) at the time
                   6000: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
                   6001: associating a name with the address of a region of memory.
1.29      crook    6002: 
1.34      anton    6003: doc-create
                   6004: 
1.69      anton    6005: Note that in ANS Forth guarantees only for @code{create} that its body
                   6006: is in dictionary data space (i.e., where @code{here}, @code{allot}
                   6007: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
                   6008: @code{create}d words can be modified with @code{does>}
                   6009: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
                   6010: can only be applied to @code{create}d words.
                   6011: 
1.29      crook    6012: By extending this example to reserve some memory in data space, we end
1.69      anton    6013: up with something like a @i{variable}. Here are two different ways to do
                   6014: it:
1.29      crook    6015: 
                   6016: @example
                   6017: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   6018: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   6019: @end example
                   6020: 
                   6021: The variable can be examined and modified using @code{@@} (``fetch'') and
                   6022: @code{!} (``store'') like this:
                   6023: 
                   6024: @example
                   6025: new-word2 @@ .      \ get address, fetch from it and display
                   6026: 1234 new-word2 !   \ new value, get address, store to it
                   6027: @end example
                   6028: 
1.44      crook    6029: @cindex arrays
                   6030: A similar mechanism can be used to create arrays. For example, an
                   6031: 80-character text input buffer:
1.29      crook    6032: 
                   6033: @example
1.44      crook    6034: CREATE text-buf 80 chars allot
                   6035: 
1.168     anton    6036: text-buf 0 chars + c@@ \ the 1st character (offset 0)
                   6037: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44      crook    6038: @end example
1.29      crook    6039: 
1.44      crook    6040: You can build arbitrarily complex data structures by allocating
1.49      anton    6041: appropriate areas of memory. For further discussions of this, and to
1.66      anton    6042: learn about some Gforth tools that make it easier,
1.49      anton    6043: @xref{Structures}.
1.44      crook    6044: 
                   6045: 
                   6046: @node Variables, Constants, CREATE, Defining Words
                   6047: @subsection Variables
                   6048: @cindex variables
                   6049: 
                   6050: The previous section showed how a sequence of commands could be used to
                   6051: generate a variable.  As a final refinement, the whole code sequence can
                   6052: be wrapped up in a defining word (pre-empting the subject of the next
                   6053: section), making it easier to create new variables:
                   6054: 
                   6055: @example
                   6056: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
                   6057: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
                   6058: 
                   6059: myvariableX foo \ variable foo starts off with an unknown value
                   6060: myvariable0 joe \ whilst joe is initialised to 0
1.29      crook    6061: 
                   6062: 45 3 * foo !   \ set foo to 135
                   6063: 1234 joe !     \ set joe to 1234
                   6064: 3 joe +!       \ increment joe by 3.. to 1237
                   6065: @end example
                   6066: 
                   6067: Not surprisingly, there is no need to define @code{myvariable}, since
1.44      crook    6068: Forth already has a definition @code{Variable}. ANS Forth does not
1.69      anton    6069: guarantee that a @code{Variable} is initialised when it is created
                   6070: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
                   6071: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
                   6072: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47      crook    6073: @code{fvariable} for double and floating-point variables, respectively
1.69      anton    6074: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47      crook    6075: store a boolean, you can use @code{on} and @code{off} to toggle its
                   6076: state.
1.29      crook    6077: 
1.34      anton    6078: doc-variable
                   6079: doc-2variable
                   6080: doc-fvariable
                   6081: 
1.29      crook    6082: @cindex user variables
                   6083: @cindex user space
                   6084: The defining word @code{User} behaves in the same way as @code{Variable}.
                   6085: The difference is that it reserves space in @i{user (data) space} rather
                   6086: than normal data space. In a Forth system that has a multi-tasker, each
                   6087: task has its own set of user variables.
                   6088: 
1.34      anton    6089: doc-user
1.67      anton    6090: @c doc-udp
                   6091: @c doc-uallot
1.34      anton    6092: 
1.29      crook    6093: @comment TODO is that stuff about user variables strictly correct? Is it
                   6094: @comment just terminal tasks that have user variables?
                   6095: @comment should document tasker.fs (with some examples) elsewhere
                   6096: @comment in this manual, then expand on user space and user variables.
                   6097: 
1.44      crook    6098: @node Constants, Values, Variables, Defining Words
                   6099: @subsection Constants
                   6100: @cindex constants
                   6101: 
                   6102: @code{Constant} allows you to declare a fixed value and refer to it by
                   6103: name. For example:
1.29      crook    6104: 
                   6105: @example
                   6106: 12 Constant INCHES-PER-FOOT
                   6107: 3E+08 fconstant SPEED-O-LIGHT
                   6108: @end example
                   6109: 
                   6110: A @code{Variable} can be both read and written, so its run-time
                   6111: behaviour is to supply an address through which its current value can be
                   6112: manipulated. In contrast, the value of a @code{Constant} cannot be
                   6113: changed once it has been declared@footnote{Well, often it can be -- but
                   6114: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   6115: on).} so it's not necessary to supply the address -- it is more
                   6116: efficient to return the value of the constant directly. That's exactly
                   6117: what happens; the run-time effect of a constant is to put its value on
1.49      anton    6118: the top of the stack (You can find one
                   6119: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29      crook    6120: 
1.69      anton    6121: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29      crook    6122: double and floating-point constants, respectively.
                   6123: 
1.34      anton    6124: doc-constant
                   6125: doc-2constant
                   6126: doc-fconstant
                   6127: 
                   6128: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44      crook    6129: @c nac-> How could that not be true in an ANS Forth? You can't define a
                   6130: @c constant, use it and then delete the definition of the constant..
1.69      anton    6131: 
                   6132: @c anton->An ANS Forth system can compile a constant to a literal; On
                   6133: @c decompilation you would see only the number, just as if it had been used
                   6134: @c in the first place.  The word will stay, of course, but it will only be
                   6135: @c used by the text interpreter (no run-time duties, except when it is 
                   6136: @c POSTPONEd or somesuch).
                   6137: 
                   6138: @c nac:
1.44      crook    6139: @c I agree that it's rather deep, but IMO it is an important difference
                   6140: @c relative to other programming languages.. often it's annoying: it
                   6141: @c certainly changes my programming style relative to C.
                   6142: 
1.69      anton    6143: @c anton: In what way?
                   6144: 
1.29      crook    6145: Constants in Forth behave differently from their equivalents in other
                   6146: programming languages. In other languages, a constant (such as an EQU in
                   6147: assembler or a #define in C) only exists at compile-time; in the
                   6148: executable program the constant has been translated into an absolute
                   6149: number and, unless you are using a symbolic debugger, it's impossible to
                   6150: know what abstract thing that number represents. In Forth a constant has
1.44      crook    6151: an entry in the header space and remains there after the code that uses
                   6152: it has been defined. In fact, it must remain in the dictionary since it
                   6153: has run-time duties to perform. For example:
1.29      crook    6154: 
                   6155: @example
                   6156: 12 Constant INCHES-PER-FOOT
                   6157: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   6158: @end example
                   6159: 
                   6160: @cindex in-lining of constants
                   6161: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   6162: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   6163: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   6164: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   6165: attempt to optimise constants by in-lining them where they are used. You
                   6166: can force Gforth to in-line a constant like this:
                   6167: 
                   6168: @example
                   6169: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   6170: @end example
                   6171: 
                   6172: If you use @code{see} to decompile @i{this} version of
                   6173: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49      anton    6174: longer present. To understand how this works, read
                   6175: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29      crook    6176: 
                   6177: In-lining constants in this way might improve execution time
                   6178: fractionally, and can ensure that a constant is now only referenced at
                   6179: compile-time. However, the definition of the constant still remains in
                   6180: the dictionary. Some Forth compilers provide a mechanism for controlling
                   6181: a second dictionary for holding transient words such that this second
                   6182: dictionary can be deleted later in order to recover memory
                   6183: space. However, there is no standard way of doing this.
                   6184: 
                   6185: 
1.44      crook    6186: @node Values, Colon Definitions, Constants, Defining Words
                   6187: @subsection Values
                   6188: @cindex values
1.34      anton    6189: 
1.69      anton    6190: A @code{Value} behaves like a @code{Constant}, but it can be changed.
                   6191: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
                   6192: (not in ANS Forth) you can access (and change) a @code{value} also with
                   6193: @code{>body}.
                   6194: 
                   6195: Here are some
                   6196: examples:
1.29      crook    6197: 
                   6198: @example
1.69      anton    6199: 12 Value APPLES     \ Define APPLES with an initial value of 12
                   6200: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
                   6201: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
                   6202: APPLES              \ puts 35 on the top of the stack.
1.29      crook    6203: @end example
                   6204: 
1.44      crook    6205: doc-value
                   6206: doc-to
1.29      crook    6207: 
1.35      anton    6208: 
1.69      anton    6209: 
1.44      crook    6210: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
                   6211: @subsection Colon Definitions
                   6212: @cindex colon definitions
1.35      anton    6213: 
                   6214: @example
1.44      crook    6215: : name ( ... -- ... )
                   6216:     word1 word2 word3 ;
1.29      crook    6217: @end example
                   6218: 
1.44      crook    6219: @noindent
                   6220: Creates a word called @code{name} that, upon execution, executes
                   6221: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29      crook    6222: 
1.49      anton    6223: The explanation above is somewhat superficial. For simple examples of
                   6224: colon definitions see @ref{Your first definition}.  For an in-depth
1.66      anton    6225: discussion of some of the issues involved, @xref{Interpretation and
1.49      anton    6226: Compilation Semantics}.
1.29      crook    6227: 
1.44      crook    6228: doc-:
                   6229: doc-;
1.1       anton    6230: 
1.34      anton    6231: 
1.69      anton    6232: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44      crook    6233: @subsection Anonymous Definitions
                   6234: @cindex colon definitions
                   6235: @cindex defining words without name
1.34      anton    6236: 
1.44      crook    6237: Sometimes you want to define an @dfn{anonymous word}; a word without a
                   6238: name. You can do this with:
1.1       anton    6239: 
1.44      crook    6240: doc-:noname
1.1       anton    6241: 
1.44      crook    6242: This leaves the execution token for the word on the stack after the
                   6243: closing @code{;}. Here's an example in which a deferred word is
                   6244: initialised with an @code{xt} from an anonymous colon definition:
1.1       anton    6245: 
1.29      crook    6246: @example
1.44      crook    6247: Defer deferred
                   6248: :noname ( ... -- ... )
                   6249:   ... ;
                   6250: IS deferred
1.29      crook    6251: @end example
1.26      crook    6252: 
1.44      crook    6253: @noindent
                   6254: Gforth provides an alternative way of doing this, using two separate
                   6255: words:
1.27      crook    6256: 
1.44      crook    6257: doc-noname
                   6258: @cindex execution token of last defined word
1.116     anton    6259: doc-latestxt
1.1       anton    6260: 
1.44      crook    6261: @noindent
                   6262: The previous example can be rewritten using @code{noname} and
1.116     anton    6263: @code{latestxt}:
1.1       anton    6264: 
1.26      crook    6265: @example
1.44      crook    6266: Defer deferred
                   6267: noname : ( ... -- ... )
                   6268:   ... ;
1.116     anton    6269: latestxt IS deferred
1.26      crook    6270: @end example
1.1       anton    6271: 
1.29      crook    6272: @noindent
1.44      crook    6273: @code{noname} works with any defining word, not just @code{:}.
                   6274: 
1.116     anton    6275: @code{latestxt} also works when the last word was not defined as
1.71      anton    6276: @code{noname}.  It does not work for combined words, though.  It also has
                   6277: the useful property that is is valid as soon as the header for a
                   6278: definition has been built. Thus:
1.44      crook    6279: 
                   6280: @example
1.116     anton    6281: latestxt . : foo [ latestxt . ] ; ' foo .
1.44      crook    6282: @end example
1.1       anton    6283: 
1.44      crook    6284: @noindent
                   6285: prints 3 numbers; the last two are the same.
1.26      crook    6286: 
1.69      anton    6287: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
                   6288: @subsection Supplying the name of a defined word
                   6289: @cindex names for defined words
                   6290: @cindex defining words, name given in a string
                   6291: 
                   6292: By default, a defining word takes the name for the defined word from the
                   6293: input stream. Sometimes you want to supply the name from a string. You
                   6294: can do this with:
                   6295: 
                   6296: doc-nextname
                   6297: 
                   6298: For example:
                   6299: 
                   6300: @example
                   6301: s" foo" nextname create
                   6302: @end example
                   6303: 
                   6304: @noindent
                   6305: is equivalent to:
                   6306: 
                   6307: @example
                   6308: create foo
                   6309: @end example
                   6310: 
                   6311: @noindent
                   6312: @code{nextname} works with any defining word.
                   6313: 
1.1       anton    6314: 
1.170     pazsan   6315: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26      crook    6316: @subsection User-defined Defining Words
                   6317: @cindex user-defined defining words
                   6318: @cindex defining words, user-defined
1.1       anton    6319: 
1.29      crook    6320: You can create a new defining word by wrapping defining-time code around
                   6321: an existing defining word and putting the sequence in a colon
1.69      anton    6322: definition. 
                   6323: 
                   6324: @c anton: This example is very complex and leads in a quite different
                   6325: @c direction from the CREATE-DOES> stuff that follows.  It should probably
                   6326: @c be done elsewhere, or as a subsubsection of this subsection (or as a
                   6327: @c subsection of Defining Words)
                   6328: 
                   6329: For example, suppose that you have a word @code{stats} that
1.29      crook    6330: gathers statistics about colon definitions given the @i{xt} of the
                   6331: definition, and you want every colon definition in your application to
                   6332: make a call to @code{stats}. You can define and use a new version of
                   6333: @code{:} like this:
                   6334: 
                   6335: @example
                   6336: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   6337:   ... ;  \ other code
                   6338: 
1.116     anton    6339: : my: : latestxt postpone literal ['] stats compile, ;
1.29      crook    6340: 
                   6341: my: foo + - ;
                   6342: @end example
                   6343: 
                   6344: When @code{foo} is defined using @code{my:} these steps occur:
                   6345: 
                   6346: @itemize @bullet
                   6347: @item
                   6348: @code{my:} is executed.
                   6349: @item
                   6350: The @code{:} within the definition (the one between @code{my:} and
1.116     anton    6351: @code{latestxt}) is executed, and does just what it always does; it parses
1.29      crook    6352: the input stream for a name, builds a dictionary header for the name
                   6353: @code{foo} and switches @code{state} from interpret to compile.
                   6354: @item
1.116     anton    6355: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29      crook    6356: being defined -- @code{foo} -- onto the stack.
                   6357: @item
                   6358: The code that was produced by @code{postpone literal} is executed; this
                   6359: causes the value on the stack to be compiled as a literal in the code
                   6360: area of @code{foo}.
                   6361: @item
                   6362: The code @code{['] stats} compiles a literal into the definition of
                   6363: @code{my:}. When @code{compile,} is executed, that literal -- the
                   6364: execution token for @code{stats} -- is layed down in the code area of
                   6365: @code{foo} , following the literal@footnote{Strictly speaking, the
                   6366: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   6367: in the code area is implementation-dependent. A threaded implementation
                   6368: might spit out the execution token directly whilst another
                   6369: implementation might spit out a native code sequence.}.
                   6370: @item
                   6371: At this point, the execution of @code{my:} is complete, and control
                   6372: returns to the text interpreter. The text interpreter is in compile
                   6373: state, so subsequent text @code{+ -} is compiled into the definition of
                   6374: @code{foo} and the @code{;} terminates the definition as always.
                   6375: @end itemize
                   6376: 
                   6377: You can use @code{see} to decompile a word that was defined using
                   6378: @code{my:} and see how it is different from a normal @code{:}
                   6379: definition. For example:
                   6380: 
                   6381: @example
                   6382: : bar + - ;  \ like foo but using : rather than my:
                   6383: see bar
                   6384: : bar
                   6385:   + - ;
                   6386: see foo
                   6387: : foo
                   6388:   107645672 stats + - ;
                   6389: 
1.140     anton    6390: \ use ' foo . to show that 107645672 is the xt for foo
1.29      crook    6391: @end example
                   6392: 
                   6393: You can use techniques like this to make new defining words in terms of
                   6394: @i{any} existing defining word.
1.1       anton    6395: 
                   6396: 
1.29      crook    6397: @cindex defining defining words
1.26      crook    6398: @cindex @code{CREATE} ... @code{DOES>}
                   6399: If you want the words defined with your defining words to behave
                   6400: differently from words defined with standard defining words, you can
                   6401: write your defining word like this:
1.1       anton    6402: 
                   6403: @example
1.26      crook    6404: : def-word ( "name" -- )
1.29      crook    6405:     CREATE @i{code1}
1.26      crook    6406: DOES> ( ... -- ... )
1.29      crook    6407:     @i{code2} ;
1.26      crook    6408: 
                   6409: def-word name
1.1       anton    6410: @end example
                   6411: 
1.29      crook    6412: @cindex child words
                   6413: This fragment defines a @dfn{defining word} @code{def-word} and then
                   6414: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   6415: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   6416: is not executed at this time. The word @code{name} is sometimes called a
                   6417: @dfn{child} of @code{def-word}.
                   6418: 
                   6419: When you execute @code{name}, the address of the body of @code{name} is
                   6420: put on the data stack and @i{code2} is executed (the address of the body
                   6421: of @code{name} is the address @code{HERE} returns immediately after the
1.69      anton    6422: @code{CREATE}, i.e., the address a @code{create}d word returns by
                   6423: default).
                   6424: 
                   6425: @c anton:
                   6426: @c www.dictionary.com says:
                   6427: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
                   6428: @c several generations of absence, usually caused by the chance
                   6429: @c recombination of genes.  2.An individual or a part that exhibits
                   6430: @c atavism. Also called throwback.  3.The return of a trait or recurrence
                   6431: @c of previous behavior after a period of absence.
                   6432: @c
                   6433: @c Doesn't seem to fit.
1.29      crook    6434: 
1.69      anton    6435: @c @cindex atavism in child words
1.33      anton    6436: You can use @code{def-word} to define a set of child words that behave
1.69      anton    6437: similarly; they all have a common run-time behaviour determined by
                   6438: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
                   6439: body of the child word. The structure of the data is common to all
                   6440: children of @code{def-word}, but the data values are specific -- and
                   6441: private -- to each child word. When a child word is executed, the
                   6442: address of its private data area is passed as a parameter on TOS to be
                   6443: used and manipulated@footnote{It is legitimate both to read and write to
                   6444: this data area.} by @i{code2}.
1.29      crook    6445: 
                   6446: The two fragments of code that make up the defining words act (are
                   6447: executed) at two completely separate times:
1.1       anton    6448: 
1.29      crook    6449: @itemize @bullet
                   6450: @item
                   6451: At @i{define time}, the defining word executes @i{code1} to generate a
                   6452: child word
                   6453: @item
                   6454: At @i{child execution time}, when a child word is invoked, @i{code2}
                   6455: is executed, using parameters (data) that are private and specific to
                   6456: the child word.
                   6457: @end itemize
                   6458: 
1.44      crook    6459: Another way of understanding the behaviour of @code{def-word} and
                   6460: @code{name} is to say that, if you make the following definitions:
1.33      anton    6461: @example
                   6462: : def-word1 ( "name" -- )
                   6463:     CREATE @i{code1} ;
                   6464: 
                   6465: : action1 ( ... -- ... )
                   6466:     @i{code2} ;
                   6467: 
                   6468: def-word1 name1
                   6469: @end example
                   6470: 
1.44      crook    6471: @noindent
                   6472: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    6473: 
1.29      crook    6474: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    6475: 
1.1       anton    6476: @example
1.29      crook    6477: : CONSTANT ( w "name" -- )
                   6478:     CREATE ,
1.26      crook    6479: DOES> ( -- w )
                   6480:     @@ ;
1.1       anton    6481: @end example
                   6482: 
1.29      crook    6483: @comment There is a beautiful description of how this works and what
                   6484: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   6485: @comment commentary on the Counting Fruits problem.
                   6486: 
                   6487: When you create a constant with @code{5 CONSTANT five}, a set of
                   6488: define-time actions take place; first a new word @code{five} is created,
                   6489: then the value 5 is laid down in the body of @code{five} with
1.44      crook    6490: @code{,}. When @code{five} is executed, the address of the body is put on
1.29      crook    6491: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   6492: no code of its own; it simply contains a data field and a pointer to the
                   6493: code that follows @code{DOES>} in its defining word. That makes words
                   6494: created in this way very compact.
                   6495: 
                   6496: The final example in this section is intended to remind you that space
                   6497: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   6498: both read and written by a Standard program@footnote{Exercise: use this
                   6499: example as a starting point for your own implementation of @code{Value}
                   6500: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   6501: @code{[']}.}:
                   6502: 
                   6503: @example
                   6504: : foo ( "name" -- )
                   6505:     CREATE -1 ,
                   6506: DOES> ( -- )
1.33      anton    6507:     @@ . ;
1.29      crook    6508: 
                   6509: foo first-word
                   6510: foo second-word
                   6511: 
                   6512: 123 ' first-word >BODY !
                   6513: @end example
                   6514: 
                   6515: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   6516: have executed it to get the address of its data field. However, since it
                   6517: was defined to have @code{DOES>} actions, its execution semantics are to
                   6518: perform those @code{DOES>} actions. To get the address of its data field
                   6519: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   6520: translate the xt into the address of the data field.  When you execute
                   6521: @code{first-word}, it will display @code{123}. When you execute
                   6522: @code{second-word} it will display @code{-1}.
1.26      crook    6523: 
                   6524: @cindex stack effect of @code{DOES>}-parts
                   6525: @cindex @code{DOES>}-parts, stack effect
1.29      crook    6526: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    6527: the stack effect of the defined words, not the stack effect of the
                   6528: following code (the following code expects the address of the body on
                   6529: the top of stack, which is not reflected in the stack comment). This is
                   6530: the convention that I use and recommend (it clashes a bit with using
                   6531: locals declarations for stack effect specification, though).
1.1       anton    6532: 
1.53      anton    6533: @menu
                   6534: * CREATE..DOES> applications::  
                   6535: * CREATE..DOES> details::       
1.63      anton    6536: * Advanced does> usage example::  
1.155     anton    6537: * Const-does>::                 
1.53      anton    6538: @end menu
                   6539: 
                   6540: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26      crook    6541: @subsubsection Applications of @code{CREATE..DOES>}
                   6542: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    6543: 
1.26      crook    6544: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    6545: 
1.26      crook    6546: @cindex factoring similar colon definitions
                   6547: When you see a sequence of code occurring several times, and you can
                   6548: identify a meaning, you will factor it out as a colon definition. When
                   6549: you see similar colon definitions, you can factor them using
                   6550: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   6551: that look very similar:
1.1       anton    6552: @example
1.26      crook    6553: : ori, ( reg-target reg-source n -- )
                   6554:     0 asm-reg-reg-imm ;
                   6555: : andi, ( reg-target reg-source n -- )
                   6556:     1 asm-reg-reg-imm ;
1.1       anton    6557: @end example
                   6558: 
1.26      crook    6559: @noindent
                   6560: This could be factored with:
                   6561: @example
                   6562: : reg-reg-imm ( op-code -- )
                   6563:     CREATE ,
                   6564: DOES> ( reg-target reg-source n -- )
                   6565:     @@ asm-reg-reg-imm ;
                   6566: 
                   6567: 0 reg-reg-imm ori,
                   6568: 1 reg-reg-imm andi,
                   6569: @end example
1.1       anton    6570: 
1.26      crook    6571: @cindex currying
                   6572: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   6573: supply a part of the parameters for a word (known as @dfn{currying} in
                   6574: the functional language community). E.g., @code{+} needs two
                   6575: parameters. Creating versions of @code{+} with one parameter fixed can
                   6576: be done like this:
1.82      anton    6577: 
1.1       anton    6578: @example
1.82      anton    6579: : curry+ ( n1 "name" -- )
1.26      crook    6580:     CREATE ,
                   6581: DOES> ( n2 -- n1+n2 )
                   6582:     @@ + ;
                   6583: 
                   6584:  3 curry+ 3+
                   6585: -2 curry+ 2-
1.1       anton    6586: @end example
                   6587: 
1.91      anton    6588: 
1.63      anton    6589: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26      crook    6590: @subsubsection The gory details of @code{CREATE..DOES>}
                   6591: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    6592: 
1.26      crook    6593: doc-does>
1.1       anton    6594: 
1.26      crook    6595: @cindex @code{DOES>} in a separate definition
                   6596: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   6597: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    6598: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    6599: @example
                   6600: : does1 
                   6601: DOES> ( ... -- ... )
1.44      crook    6602:     ... ;
                   6603: 
                   6604: : does2
                   6605: DOES> ( ... -- ... )
                   6606:     ... ;
                   6607: 
                   6608: : def-word ( ... -- ... )
                   6609:     create ...
                   6610:     IF
                   6611:        does1
                   6612:     ELSE
                   6613:        does2
                   6614:     ENDIF ;
                   6615: @end example
                   6616: 
                   6617: In this example, the selection of whether to use @code{does1} or
1.69      anton    6618: @code{does2} is made at definition-time; at the time that the child word is
1.44      crook    6619: @code{CREATE}d.
                   6620: 
                   6621: @cindex @code{DOES>} in interpretation state
                   6622: In a standard program you can apply a @code{DOES>}-part only if the last
                   6623: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   6624: will override the behaviour of the last word defined in any case. In a
                   6625: standard program, you can use @code{DOES>} only in a colon
                   6626: definition. In Gforth, you can also use it in interpretation state, in a
                   6627: kind of one-shot mode; for example:
                   6628: @example
                   6629: CREATE name ( ... -- ... )
                   6630:   @i{initialization}
                   6631: DOES>
                   6632:   @i{code} ;
                   6633: @end example
                   6634: 
                   6635: @noindent
                   6636: is equivalent to the standard:
                   6637: @example
                   6638: :noname
                   6639: DOES>
                   6640:     @i{code} ;
                   6641: CREATE name EXECUTE ( ... -- ... )
                   6642:     @i{initialization}
                   6643: @end example
                   6644: 
1.53      anton    6645: doc->body
                   6646: 
1.152     pazsan   6647: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63      anton    6648: @subsubsection Advanced does> usage example
                   6649: 
                   6650: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
                   6651: for disassembling instructions, that follow a very repetetive scheme:
                   6652: 
                   6653: @example
                   6654: :noname @var{disasm-operands} s" @var{inst-name}" type ;
                   6655: @var{entry-num} cells @var{table} + !
                   6656: @end example
                   6657: 
                   6658: Of course, this inspires the idea to factor out the commonalities to
                   6659: allow a definition like
                   6660: 
                   6661: @example
                   6662: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
                   6663: @end example
                   6664: 
                   6665: The parameters @var{disasm-operands} and @var{table} are usually
1.69      anton    6666: correlated.  Moreover, before I wrote the disassembler, there already
                   6667: existed code that defines instructions like this:
1.63      anton    6668: 
                   6669: @example
                   6670: @var{entry-num} @var{inst-format} @var{inst-name}
                   6671: @end example
                   6672: 
                   6673: This code comes from the assembler and resides in
                   6674: @file{arch/mips/insts.fs}.
                   6675: 
                   6676: So I had to define the @var{inst-format} words that performed the scheme
                   6677: above when executed.  At first I chose to use run-time code-generation:
                   6678: 
                   6679: @example
                   6680: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
                   6681:   :noname Postpone @var{disasm-operands}
                   6682:   name Postpone sliteral Postpone type Postpone ;
                   6683:   swap cells @var{table} + ! ;
                   6684: @end example
                   6685: 
                   6686: Note that this supplies the other two parameters of the scheme above.
1.44      crook    6687: 
1.63      anton    6688: An alternative would have been to write this using
                   6689: @code{create}/@code{does>}:
                   6690: 
                   6691: @example
                   6692: : @var{inst-format} ( entry-num "name" -- )
                   6693:   here name string, ( entry-num c-addr ) \ parse and save "name"
                   6694:   noname create , ( entry-num )
1.116     anton    6695:   latestxt swap cells @var{table} + !
1.63      anton    6696: does> ( addr w -- )
                   6697:   \ disassemble instruction w at addr
                   6698:   @@ >r 
                   6699:   @var{disasm-operands}
                   6700:   r> count type ;
                   6701: @end example
                   6702: 
                   6703: Somehow the first solution is simpler, mainly because it's simpler to
                   6704: shift a string from definition-time to use-time with @code{sliteral}
                   6705: than with @code{string,} and friends.
                   6706: 
                   6707: I wrote a lot of words following this scheme and soon thought about
                   6708: factoring out the commonalities among them.  Note that this uses a
                   6709: two-level defining word, i.e., a word that defines ordinary defining
                   6710: words.
                   6711: 
                   6712: This time a solution involving @code{postpone} and friends seemed more
                   6713: difficult (try it as an exercise), so I decided to use a
                   6714: @code{create}/@code{does>} word; since I was already at it, I also used
                   6715: @code{create}/@code{does>} for the lower level (try using
                   6716: @code{postpone} etc. as an exercise), resulting in the following
                   6717: definition:
                   6718: 
                   6719: @example
                   6720: : define-format ( disasm-xt table-xt -- )
                   6721:     \ define an instruction format that uses disasm-xt for
                   6722:     \ disassembling and enters the defined instructions into table
                   6723:     \ table-xt
                   6724:     create 2,
                   6725: does> ( u "inst" -- )
                   6726:     \ defines an anonymous word for disassembling instruction inst,
                   6727:     \ and enters it as u-th entry into table-xt
                   6728:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
                   6729:     noname create 2,      \ define anonymous word
1.116     anton    6730:     execute latestxt swap ! \ enter xt of defined word into table-xt
1.63      anton    6731: does> ( addr w -- )
                   6732:     \ disassemble instruction w at addr
                   6733:     2@@ >r ( addr w disasm-xt R: c-addr )
                   6734:     execute ( R: c-addr ) \ disassemble operands
                   6735:     r> count type ; \ print name 
                   6736: @end example
                   6737: 
                   6738: Note that the tables here (in contrast to above) do the @code{cells +}
                   6739: by themselves (that's why you have to pass an xt).  This word is used in
                   6740: the following way:
                   6741: 
                   6742: @example
                   6743: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
                   6744: @end example
                   6745: 
1.71      anton    6746: As shown above, the defined instruction format is then used like this:
                   6747: 
                   6748: @example
                   6749: @var{entry-num} @var{inst-format} @var{inst-name}
                   6750: @end example
                   6751: 
1.63      anton    6752: In terms of currying, this kind of two-level defining word provides the
                   6753: parameters in three stages: first @var{disasm-operands} and @var{table},
                   6754: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
                   6755: the instruction to be disassembled.  
                   6756: 
                   6757: Of course this did not quite fit all the instruction format names used
                   6758: in @file{insts.fs}, so I had to define a few wrappers that conditioned
                   6759: the parameters into the right form.
                   6760: 
                   6761: If you have trouble following this section, don't worry.  First, this is
                   6762: involved and takes time (and probably some playing around) to
                   6763: understand; second, this is the first two-level
                   6764: @code{create}/@code{does>} word I have written in seventeen years of
                   6765: Forth; and if I did not have @file{insts.fs} to start with, I may well
                   6766: have elected to use just a one-level defining word (with some repeating
                   6767: of parameters when using the defining word). So it is not necessary to
                   6768: understand this, but it may improve your understanding of Forth.
1.44      crook    6769: 
                   6770: 
1.152     pazsan   6771: @node Const-does>,  , Advanced does> usage example, User-defined Defining Words
1.91      anton    6772: @subsubsection @code{Const-does>}
                   6773: 
                   6774: A frequent use of @code{create}...@code{does>} is for transferring some
                   6775: values from definition-time to run-time.  Gforth supports this use with
                   6776: 
                   6777: doc-const-does>
                   6778: 
                   6779: A typical use of this word is:
                   6780: 
                   6781: @example
                   6782: : curry+ ( n1 "name" -- )
                   6783: 1 0 CONST-DOES> ( n2 -- n1+n2 )
                   6784:     + ;
                   6785: 
                   6786: 3 curry+ 3+
                   6787: @end example
                   6788: 
                   6789: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
                   6790: definition to run-time.
                   6791: 
                   6792: The advantages of using @code{const-does>} are:
                   6793: 
                   6794: @itemize
                   6795: 
                   6796: @item
                   6797: You don't have to deal with storing and retrieving the values, i.e.,
                   6798: your program becomes more writable and readable.
                   6799: 
                   6800: @item
                   6801: When using @code{does>}, you have to introduce a @code{@@} that cannot
                   6802: be optimized away (because you could change the data using
                   6803: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
                   6804: 
                   6805: @end itemize
                   6806: 
                   6807: An ANS Forth implementation of @code{const-does>} is available in
                   6808: @file{compat/const-does.fs}.
                   6809: 
                   6810: 
1.170     pazsan   6811: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
                   6812: @subsection Deferred Words
1.44      crook    6813: @cindex deferred words
                   6814: 
                   6815: The defining word @code{Defer} allows you to define a word by name
                   6816: without defining its behaviour; the definition of its behaviour is
                   6817: deferred. Here are two situation where this can be useful:
                   6818: 
                   6819: @itemize @bullet
                   6820: @item
                   6821: Where you want to allow the behaviour of a word to be altered later, and
                   6822: for all precompiled references to the word to change when its behaviour
                   6823: is changed.
                   6824: @item
                   6825: For mutual recursion; @xref{Calls and returns}.
                   6826: @end itemize
                   6827: 
                   6828: In the following example, @code{foo} always invokes the version of
                   6829: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
                   6830: always invokes the version that prints ``@code{Hello}''. There is no way
                   6831: of getting @code{foo} to use the later version without re-ordering the
                   6832: source code and recompiling it.
                   6833: 
                   6834: @example
                   6835: : greet ." Good morning" ;
                   6836: : foo ... greet ... ;
                   6837: : greet ." Hello" ;
                   6838: : bar ... greet ... ;
                   6839: @end example
                   6840: 
                   6841: This problem can be solved by defining @code{greet} as a @code{Defer}red
                   6842: word. The behaviour of a @code{Defer}red word can be defined and
                   6843: redefined at any time by using @code{IS} to associate the xt of a
                   6844: previously-defined word with it. The previous example becomes:
                   6845: 
                   6846: @example
1.69      anton    6847: Defer greet ( -- )
1.44      crook    6848: : foo ... greet ... ;
                   6849: : bar ... greet ... ;
1.69      anton    6850: : greet1 ( -- ) ." Good morning" ;
                   6851: : greet2 ( -- ) ." Hello" ;
1.132     anton    6852: ' greet2 IS greet  \ make greet behave like greet2
1.44      crook    6853: @end example
                   6854: 
1.69      anton    6855: @progstyle
                   6856: You should write a stack comment for every deferred word, and put only
                   6857: XTs into deferred words that conform to this stack effect.  Otherwise
                   6858: it's too difficult to use the deferred word.
                   6859: 
1.44      crook    6860: A deferred word can be used to improve the statistics-gathering example
                   6861: from @ref{User-defined Defining Words}; rather than edit the
                   6862: application's source code to change every @code{:} to a @code{my:}, do
                   6863: this:
                   6864: 
                   6865: @example
                   6866: : real: : ;     \ retain access to the original
                   6867: defer :         \ redefine as a deferred word
1.132     anton    6868: ' my: IS :      \ use special version of :
1.44      crook    6869: \
                   6870: \ load application here
                   6871: \
1.132     anton    6872: ' real: IS :    \ go back to the original
1.44      crook    6873: @end example
                   6874: 
                   6875: 
1.132     anton    6876: One thing to note is that @code{IS} has special compilation semantics,
                   6877: such that it parses the name at compile time (like @code{TO}):
1.44      crook    6878: 
                   6879: @example
                   6880: : set-greet ( xt -- )
1.132     anton    6881:   IS greet ;
1.44      crook    6882: 
                   6883: ' greet1 set-greet
                   6884: @end example
                   6885: 
1.132     anton    6886: In situations where @code{IS} does not fit, use @code{defer!} instead.
                   6887: 
1.69      anton    6888: A deferred word can only inherit execution semantics from the xt
                   6889: (because that is all that an xt can represent -- for more discussion of
                   6890: this @pxref{Tokens for Words}); by default it will have default
                   6891: interpretation and compilation semantics deriving from this execution
                   6892: semantics.  However, you can change the interpretation and compilation
                   6893: semantics of the deferred word in the usual ways:
1.44      crook    6894: 
                   6895: @example
1.132     anton    6896: : bar .... ; immediate
1.44      crook    6897: Defer fred immediate
                   6898: Defer jim
                   6899: 
1.132     anton    6900: ' bar IS jim  \ jim has default semantics
                   6901: ' bar IS fred \ fred is immediate
1.44      crook    6902: @end example
                   6903: 
                   6904: doc-defer
1.132     anton    6905: doc-defer!
1.44      crook    6906: doc-is
1.132     anton    6907: doc-defer@
                   6908: doc-action-of
1.44      crook    6909: @comment TODO document these: what's defers [is]
                   6910: doc-defers
                   6911: 
                   6912: @c Use @code{words-deferred} to see a list of deferred words.
                   6913: 
1.132     anton    6914: Definitions of these words (except @code{defers}) in ANS Forth are
                   6915: provided in @file{compat/defer.fs}.
1.44      crook    6916: 
                   6917: 
1.170     pazsan   6918: @node Aliases,  , Deferred Words, Defining Words
1.44      crook    6919: @subsection Aliases
                   6920: @cindex aliases
1.1       anton    6921: 
1.44      crook    6922: The defining word @code{Alias} allows you to define a word by name that
                   6923: has the same behaviour as some other word. Here are two situation where
                   6924: this can be useful:
1.1       anton    6925: 
1.44      crook    6926: @itemize @bullet
                   6927: @item
                   6928: When you want access to a word's definition from a different word list
                   6929: (for an example of this, see the definition of the @code{Root} word list
                   6930: in the Gforth source).
                   6931: @item
                   6932: When you want to create a synonym; a definition that can be known by
                   6933: either of two names (for example, @code{THEN} and @code{ENDIF} are
                   6934: aliases).
                   6935: @end itemize
1.1       anton    6936: 
1.69      anton    6937: Like deferred words, an alias has default compilation and interpretation
                   6938: semantics at the beginning (not the modifications of the other word),
                   6939: but you can change them in the usual ways (@code{immediate},
                   6940: @code{compile-only}). For example:
1.1       anton    6941: 
                   6942: @example
1.44      crook    6943: : foo ... ; immediate
                   6944: 
                   6945: ' foo Alias bar \ bar is not an immediate word
                   6946: ' foo Alias fooby immediate \ fooby is an immediate word
1.1       anton    6947: @end example
                   6948: 
1.44      crook    6949: Words that are aliases have the same xt, different headers in the
                   6950: dictionary, and consequently different name tokens (@pxref{Tokens for
                   6951: Words}) and possibly different immediate flags.  An alias can only have
                   6952: default or immediate compilation semantics; you can define aliases for
                   6953: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1       anton    6954: 
1.44      crook    6955: doc-alias
1.1       anton    6956: 
                   6957: 
1.47      crook    6958: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
                   6959: @section Interpretation and Compilation Semantics
1.26      crook    6960: @cindex semantics, interpretation and compilation
1.1       anton    6961: 
1.71      anton    6962: @c !! state and ' are used without explanation
                   6963: @c example for immediate/compile-only? or is the tutorial enough
                   6964: 
1.26      crook    6965: @cindex interpretation semantics
1.71      anton    6966: The @dfn{interpretation semantics} of a (named) word are what the text
1.26      crook    6967: interpreter does when it encounters the word in interpret state. It also
                   6968: appears in some other contexts, e.g., the execution token returned by
1.71      anton    6969: @code{' @i{word}} identifies the interpretation semantics of @i{word}
                   6970: (in other words, @code{' @i{word} execute} is equivalent to
1.29      crook    6971: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    6972: 
1.26      crook    6973: @cindex compilation semantics
1.71      anton    6974: The @dfn{compilation semantics} of a (named) word are what the text
                   6975: interpreter does when it encounters the word in compile state. It also
                   6976: appears in other contexts, e.g, @code{POSTPONE @i{word}}
                   6977: compiles@footnote{In standard terminology, ``appends to the current
                   6978: definition''.} the compilation semantics of @i{word}.
1.1       anton    6979: 
1.26      crook    6980: @cindex execution semantics
                   6981: The standard also talks about @dfn{execution semantics}. They are used
                   6982: only for defining the interpretation and compilation semantics of many
                   6983: words. By default, the interpretation semantics of a word are to
                   6984: @code{execute} its execution semantics, and the compilation semantics of
                   6985: a word are to @code{compile,} its execution semantics.@footnote{In
                   6986: standard terminology: The default interpretation semantics are its
                   6987: execution semantics; the default compilation semantics are to append its
                   6988: execution semantics to the execution semantics of the current
                   6989: definition.}
                   6990: 
1.71      anton    6991: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
                   6992: the text interpreter, ticked, or @code{postpone}d, so they have no
                   6993: interpretation or compilation semantics.  Their behaviour is represented
                   6994: by their XT (@pxref{Tokens for Words}), and we call it execution
                   6995: semantics, too.
                   6996: 
1.26      crook    6997: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   6998: 
                   6999: @cindex immediate words
                   7000: @cindex compile-only words
                   7001: You can change the semantics of the most-recently defined word:
                   7002: 
1.44      crook    7003: 
1.26      crook    7004: doc-immediate
                   7005: doc-compile-only
                   7006: doc-restrict
                   7007: 
1.82      anton    7008: By convention, words with non-default compilation semantics (e.g.,
                   7009: immediate words) often have names surrounded with brackets (e.g.,
                   7010: @code{[']}, @pxref{Execution token}).
1.44      crook    7011: 
1.26      crook    7012: Note that ticking (@code{'}) a compile-only word gives an error
                   7013: (``Interpreting a compile-only word'').
1.1       anton    7014: 
1.47      crook    7015: @menu
1.67      anton    7016: * Combined words::              
1.47      crook    7017: @end menu
1.44      crook    7018: 
1.71      anton    7019: 
1.48      anton    7020: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44      crook    7021: @subsection Combined Words
                   7022: @cindex combined words
                   7023: 
                   7024: Gforth allows you to define @dfn{combined words} -- words that have an
                   7025: arbitrary combination of interpretation and compilation semantics.
                   7026: 
1.26      crook    7027: doc-interpret/compile:
1.1       anton    7028: 
1.26      crook    7029: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   7030: recommend that you do not define such words, as cute as they may be:
                   7031: they make it hard to get at both parts of the word in some contexts.
                   7032: E.g., assume you want to get an execution token for the compilation
                   7033: part. Instead, define two words, one that embodies the interpretation
                   7034: part, and one that embodies the compilation part.  Once you have done
                   7035: that, you can define a combined word with @code{interpret/compile:} for
                   7036: the convenience of your users.
1.1       anton    7037: 
1.26      crook    7038: You might try to use this feature to provide an optimizing
                   7039: implementation of the default compilation semantics of a word. For
                   7040: example, by defining:
1.1       anton    7041: @example
1.26      crook    7042: :noname
                   7043:    foo bar ;
                   7044: :noname
                   7045:    POSTPONE foo POSTPONE bar ;
1.29      crook    7046: interpret/compile: opti-foobar
1.1       anton    7047: @end example
1.26      crook    7048: 
1.23      crook    7049: @noindent
1.26      crook    7050: as an optimizing version of:
                   7051: 
1.1       anton    7052: @example
1.26      crook    7053: : foobar
                   7054:     foo bar ;
1.1       anton    7055: @end example
                   7056: 
1.26      crook    7057: Unfortunately, this does not work correctly with @code{[compile]},
                   7058: because @code{[compile]} assumes that the compilation semantics of all
                   7059: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    7060: opti-foobar} would compile compilation semantics, whereas
                   7061: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    7062: 
1.26      crook    7063: @cindex state-smart words (are a bad idea)
1.82      anton    7064: @anchor{state-smartness}
1.29      crook    7065: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    7066: by @code{interpret/compile:} (words are state-smart if they check
                   7067: @code{STATE} during execution). E.g., they would try to code
                   7068: @code{foobar} like this:
1.1       anton    7069: 
1.26      crook    7070: @example
                   7071: : foobar
                   7072:   STATE @@
                   7073:   IF ( compilation state )
                   7074:     POSTPONE foo POSTPONE bar
                   7075:   ELSE
                   7076:     foo bar
                   7077:   ENDIF ; immediate
                   7078: @end example
1.1       anton    7079: 
1.26      crook    7080: Although this works if @code{foobar} is only processed by the text
                   7081: interpreter, it does not work in other contexts (like @code{'} or
                   7082: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   7083: for a state-smart word, not for the interpretation semantics of the
                   7084: original @code{foobar}; when you execute this execution token (directly
                   7085: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   7086: state, the result will not be what you expected (i.e., it will not
                   7087: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   7088: write them@footnote{For a more detailed discussion of this topic, see
1.66      anton    7089: M. Anton Ertl,
                   7090: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
                   7091: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1       anton    7092: 
1.26      crook    7093: @cindex defining words with arbitrary semantics combinations
                   7094: It is also possible to write defining words that define words with
                   7095: arbitrary combinations of interpretation and compilation semantics. In
                   7096: general, they look like this:
1.1       anton    7097: 
1.26      crook    7098: @example
                   7099: : def-word
                   7100:     create-interpret/compile
1.29      crook    7101:     @i{code1}
1.26      crook    7102: interpretation>
1.29      crook    7103:     @i{code2}
1.26      crook    7104: <interpretation
                   7105: compilation>
1.29      crook    7106:     @i{code3}
1.26      crook    7107: <compilation ;
                   7108: @end example
1.1       anton    7109: 
1.29      crook    7110: For a @i{word} defined with @code{def-word}, the interpretation
                   7111: semantics are to push the address of the body of @i{word} and perform
                   7112: @i{code2}, and the compilation semantics are to push the address of
                   7113: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    7114: can also be defined like this (except that the defined constants don't
                   7115: behave correctly when @code{[compile]}d):
1.1       anton    7116: 
1.26      crook    7117: @example
                   7118: : constant ( n "name" -- )
                   7119:     create-interpret/compile
                   7120:     ,
                   7121: interpretation> ( -- n )
                   7122:     @@
                   7123: <interpretation
                   7124: compilation> ( compilation. -- ; run-time. -- n )
                   7125:     @@ postpone literal
                   7126: <compilation ;
                   7127: @end example
1.1       anton    7128: 
1.44      crook    7129: 
1.26      crook    7130: doc-create-interpret/compile
                   7131: doc-interpretation>
                   7132: doc-<interpretation
                   7133: doc-compilation>
                   7134: doc-<compilation
1.1       anton    7135: 
1.44      crook    7136: 
1.29      crook    7137: Words defined with @code{interpret/compile:} and
1.26      crook    7138: @code{create-interpret/compile} have an extended header structure that
                   7139: differs from other words; however, unless you try to access them with
                   7140: plain address arithmetic, you should not notice this. Words for
                   7141: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    7142: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   7143: with @code{create-interpret/compile}.
1.1       anton    7144: 
1.44      crook    7145: 
1.47      crook    7146: @c -------------------------------------------------------------
1.81      anton    7147: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47      crook    7148: @section Tokens for Words
                   7149: @cindex tokens for words
                   7150: 
                   7151: This section describes the creation and use of tokens that represent
                   7152: words.
                   7153: 
1.71      anton    7154: @menu
                   7155: * Execution token::             represents execution/interpretation semantics
                   7156: * Compilation token::           represents compilation semantics
                   7157: * Name token::                  represents named words
                   7158: @end menu
1.47      crook    7159: 
1.71      anton    7160: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
                   7161: @subsection Execution token
1.47      crook    7162: 
                   7163: @cindex xt
                   7164: @cindex execution token
1.71      anton    7165: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
                   7166: You can use @code{execute} to invoke this behaviour.
1.47      crook    7167: 
1.71      anton    7168: @cindex tick (')
                   7169: You can use @code{'} to get an execution token that represents the
                   7170: interpretation semantics of a named word:
1.47      crook    7171: 
                   7172: @example
1.97      anton    7173: 5 ' .   ( n xt ) 
                   7174: execute ( )      \ execute the xt (i.e., ".")
1.71      anton    7175: @end example
1.47      crook    7176: 
1.71      anton    7177: doc-'
                   7178: 
                   7179: @code{'} parses at run-time; there is also a word @code{[']} that parses
                   7180: when it is compiled, and compiles the resulting XT:
                   7181: 
                   7182: @example
                   7183: : foo ['] . execute ;
                   7184: 5 foo
                   7185: : bar ' execute ; \ by contrast,
                   7186: 5 bar .           \ ' parses "." when bar executes
                   7187: @end example
                   7188: 
                   7189: doc-[']
                   7190: 
                   7191: If you want the execution token of @i{word}, write @code{['] @i{word}}
                   7192: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
                   7193: @code{'} and @code{[']} behave somewhat unusually by complaining about
                   7194: compile-only words (because these words have no interpretation
                   7195: semantics).  You might get what you want by using @code{COMP' @i{word}
                   7196: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
                   7197: token}).
                   7198: 
1.116     anton    7199: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71      anton    7200: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
                   7201: for the only behaviour the word has (the execution semantics).  For
1.116     anton    7202: named words, @code{latestxt} produces an XT for the same behaviour it
1.71      anton    7203: would produce if the word was defined anonymously.
                   7204: 
                   7205: @example
                   7206: :noname ." hello" ;
                   7207: execute
1.47      crook    7208: @end example
                   7209: 
1.71      anton    7210: An XT occupies one cell and can be manipulated like any other cell.
                   7211: 
1.47      crook    7212: @cindex code field address
                   7213: @cindex CFA
1.71      anton    7214: In ANS Forth the XT is just an abstract data type (i.e., defined by the
                   7215: operations that produce or consume it).  For old hands: In Gforth, the
                   7216: XT is implemented as a code field address (CFA).
                   7217: 
                   7218: doc-execute
                   7219: doc-perform
                   7220: 
                   7221: @node Compilation token, Name token, Execution token, Tokens for Words
                   7222: @subsection Compilation token
1.47      crook    7223: 
                   7224: @cindex compilation token
1.71      anton    7225: @cindex CT (compilation token)
                   7226: Gforth represents the compilation semantics of a named word by a
1.47      crook    7227: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   7228: @i{xt} is an execution token. The compilation semantics represented by
                   7229: the compilation token can be performed with @code{execute}, which
                   7230: consumes the whole compilation token, with an additional stack effect
                   7231: determined by the represented compilation semantics.
                   7232: 
                   7233: At present, the @i{w} part of a compilation token is an execution token,
                   7234: and the @i{xt} part represents either @code{execute} or
                   7235: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   7236: word. If the word has default compilation semantics, the @i{xt} will
                   7237: represent @code{compile,}. Otherwise (e.g., for immediate words), the
                   7238: @i{xt} will represent @code{execute}.}. However, don't rely on that
                   7239: knowledge, unless necessary; future versions of Gforth may introduce
                   7240: unusual compilation tokens (e.g., a compilation token that represents
                   7241: the compilation semantics of a literal).
                   7242: 
1.71      anton    7243: You can perform the compilation semantics represented by the compilation
                   7244: token with @code{execute}.  You can compile the compilation semantics
                   7245: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
                   7246: equivalent to @code{postpone @i{word}}.
                   7247: 
                   7248: doc-[comp']
                   7249: doc-comp'
                   7250: doc-postpone,
                   7251: 
                   7252: @node Name token,  , Compilation token, Tokens for Words
                   7253: @subsection Name token
1.47      crook    7254: 
                   7255: @cindex name token
1.116     anton    7256: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
                   7257: token is an abstract data type that occurs as argument or result of the
                   7258: words below.
                   7259: 
                   7260: @c !! put this elswhere?
1.47      crook    7261: @cindex name field address
                   7262: @cindex NFA
1.116     anton    7263: The closest thing to the nt in older Forth systems is the name field
                   7264: address (NFA), but there are significant differences: in older Forth
                   7265: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
                   7266: LFA, NFA, CFA, PFA) and there were words for getting from one to the
                   7267: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
                   7268: is a link field in the structure identified by the name token, but
                   7269: searching usually uses a hash table external to these structures; the
                   7270: name in Gforth has a cell-wide count-and-flags field, and the nt is not
                   7271: implemented as the address of that count field.
1.47      crook    7272: 
                   7273: doc-find-name
1.116     anton    7274: doc-latest
                   7275: doc->name
1.47      crook    7276: doc-name>int
                   7277: doc-name?int
                   7278: doc-name>comp
                   7279: doc-name>string
1.109     anton    7280: doc-id.
                   7281: doc-.name
                   7282: doc-.id
1.47      crook    7283: 
1.81      anton    7284: @c ----------------------------------------------------------
                   7285: @node Compiling words, The Text Interpreter, Tokens for Words, Words
                   7286: @section Compiling words
                   7287: @cindex compiling words
                   7288: @cindex macros
                   7289: 
                   7290: In contrast to most other languages, Forth has no strict boundary
1.82      anton    7291: between compilation and run-time.  E.g., you can run arbitrary code
                   7292: between defining words (or for computing data used by defining words
                   7293: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
                   7294: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
                   7295: running arbitrary code while compiling a colon definition (exception:
                   7296: you must not allot dictionary space).
                   7297: 
                   7298: @menu
                   7299: * Literals::                    Compiling data values
                   7300: * Macros::                      Compiling words
                   7301: @end menu
                   7302: 
                   7303: @node Literals, Macros, Compiling words, Compiling words
                   7304: @subsection Literals
                   7305: @cindex Literals
                   7306: 
                   7307: The simplest and most frequent example is to compute a literal during
                   7308: compilation.  E.g., the following definition prints an array of strings,
                   7309: one string per line:
                   7310: 
                   7311: @example
                   7312: : .strings ( addr u -- ) \ gforth
                   7313:     2* cells bounds U+DO
                   7314:        cr i 2@@ type
                   7315:     2 cells +LOOP ;  
                   7316: @end example
1.81      anton    7317: 
1.82      anton    7318: With a simple-minded compiler like Gforth's, this computes @code{2
                   7319: cells} on every loop iteration.  You can compute this value once and for
                   7320: all at compile time and compile it into the definition like this:
                   7321: 
                   7322: @example
                   7323: : .strings ( addr u -- ) \ gforth
                   7324:     2* cells bounds U+DO
                   7325:        cr i 2@@ type
                   7326:     [ 2 cells ] literal +LOOP ;  
                   7327: @end example
                   7328: 
                   7329: @code{[} switches the text interpreter to interpret state (you will get
                   7330: an @code{ok} prompt if you type this example interactively and insert a
                   7331: newline between @code{[} and @code{]}), so it performs the
                   7332: interpretation semantics of @code{2 cells}; this computes a number.
                   7333: @code{]} switches the text interpreter back into compile state.  It then
                   7334: performs @code{Literal}'s compilation semantics, which are to compile
                   7335: this number into the current word.  You can decompile the word with
                   7336: @code{see .strings} to see the effect on the compiled code.
1.81      anton    7337: 
1.82      anton    7338: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
                   7339: *} in this way.
1.81      anton    7340: 
1.82      anton    7341: doc-[
                   7342: doc-]
1.81      anton    7343: doc-literal
                   7344: doc-]L
1.82      anton    7345: 
                   7346: There are also words for compiling other data types than single cells as
                   7347: literals:
                   7348: 
1.81      anton    7349: doc-2literal
                   7350: doc-fliteral
1.82      anton    7351: doc-sliteral
                   7352: 
                   7353: @cindex colon-sys, passing data across @code{:}
                   7354: @cindex @code{:}, passing data across
                   7355: You might be tempted to pass data from outside a colon definition to the
                   7356: inside on the data stack.  This does not work, because @code{:} puhes a
                   7357: colon-sys, making stuff below unaccessible.  E.g., this does not work:
                   7358: 
                   7359: @example
                   7360: 5 : foo literal ; \ error: "unstructured"
                   7361: @end example
                   7362: 
                   7363: Instead, you have to pass the value in some other way, e.g., through a
                   7364: variable:
                   7365: 
                   7366: @example
                   7367: variable temp
                   7368: 5 temp !
                   7369: : foo [ temp @@ ] literal ;
                   7370: @end example
                   7371: 
                   7372: 
                   7373: @node Macros,  , Literals, Compiling words
                   7374: @subsection Macros
                   7375: @cindex Macros
                   7376: @cindex compiling compilation semantics
                   7377: 
                   7378: @code{Literal} and friends compile data values into the current
                   7379: definition.  You can also write words that compile other words into the
                   7380: current definition.  E.g.,
                   7381: 
                   7382: @example
                   7383: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
                   7384:   POSTPONE + ;
                   7385: 
                   7386: : foo ( n1 n2 -- n )
                   7387:   [ compile-+ ] ;
                   7388: 1 2 foo .
                   7389: @end example
                   7390: 
                   7391: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
                   7392: What happens in this example?  @code{Postpone} compiles the compilation
                   7393: semantics of @code{+} into @code{compile-+}; later the text interpreter
                   7394: executes @code{compile-+} and thus the compilation semantics of +, which
                   7395: compile (the execution semantics of) @code{+} into
                   7396: @code{foo}.@footnote{A recent RFI answer requires that compiling words
                   7397: should only be executed in compile state, so this example is not
                   7398: guaranteed to work on all standard systems, but on any decent system it
                   7399: will work.}
                   7400: 
                   7401: doc-postpone
                   7402: 
                   7403: Compiling words like @code{compile-+} are usually immediate (or similar)
                   7404: so you do not have to switch to interpret state to execute them;
1.206     anton    7405: modifying the last example accordingly produces:
1.82      anton    7406: 
                   7407: @example
                   7408: : [compile-+] ( compilation: --; interpretation: -- )
                   7409:   \ compiled code: ( n1 n2 -- n )
                   7410:   POSTPONE + ; immediate
                   7411: 
                   7412: : foo ( n1 n2 -- n )
                   7413:   [compile-+] ;
                   7414: 1 2 foo .
                   7415: @end example
                   7416: 
1.206     anton    7417: You will occassionally find the need to POSTPONE several words;
                   7418: putting POSTPONE before each such word is cumbersome, so Gforth
                   7419: provides a more convenient syntax: @code{]] ... [[}.  This
                   7420: allows us to write @code{[compile-+]} as:
                   7421: 
                   7422: @example
                   7423: : [compile-+] ( compilation: --; interpretation: -- )
                   7424:   ]] + [[ ; immediate
                   7425: @end example
                   7426: 
                   7427: doc-]]
                   7428: doc-[[
                   7429: 
                   7430: The unusual direction of the brackets indicates their function:
                   7431: @code{]]} switches from compilation to postponing (i.e., compilation
                   7432: of compilation), just like @code{]} switches from immediate execution
                   7433: (interpretation) to compilation.  Conversely, @code{[[} switches from
                   7434: postponing to compilation, ananlogous to @code{[} which switches from
                   7435: compilation to immediate execution.
                   7436: 
                   7437: The real advantage of @code{]] }...@code{ [[} becomes apparent when
                   7438: there are many words to POSTPONE.  E.g., the word
                   7439: @code{compile-map-array} (@pxref{Advanced macros Tutorial}) can be
                   7440: written much shorter as follows:
                   7441: 
                   7442: @example
                   7443: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
                   7444: \ at run-time, execute xt ( ... x -- ... ) for each element of the
                   7445: \ array beginning at addr and containing u elements
                   7446:   @{ xt @}
                   7447:   ]] cells over + swap ?do
                   7448:     i @@ [[ xt compile, 
                   7449:   1 cells ]]L +loop [[ ;
                   7450: @end example
                   7451: 
                   7452: This example also uses @code{]]L} as a shortcut for @code{]] literal}.
                   7453: There are also other shortcuts
                   7454: 
                   7455: doc-]]L
                   7456: doc-]]2L
                   7457: doc-]]FL
                   7458: doc-]]SL
                   7459: 
                   7460: Note that parsing words don't parse at postpone time; if you want to
                   7461: provide the parsed string right away, you have to switch back to
                   7462: compilation:
                   7463: 
                   7464: @example
                   7465: ]] ... [[ s" some string" ]]2L ... [[
                   7466: ]] ... [[ ['] + ]]L ... [[
                   7467: @end example
                   7468: 
                   7469: Definitions of @code{]]} and friends in ANS Forth are provided in
                   7470: @file{compat/macros.fs}.
                   7471: 
1.82      anton    7472: Immediate compiling words are similar to macros in other languages (in
                   7473: particular, Lisp).  The important differences to macros in, e.g., C are:
                   7474: 
                   7475: @itemize @bullet
                   7476: 
                   7477: @item
                   7478: You use the same language for defining and processing macros, not a
                   7479: separate preprocessing language and processor.
                   7480: 
                   7481: @item
                   7482: Consequently, the full power of Forth is available in macro definitions.
                   7483: E.g., you can perform arbitrarily complex computations, or generate
                   7484: different code conditionally or in a loop (e.g., @pxref{Advanced macros
                   7485: Tutorial}).  This power is very useful when writing a parser generators
                   7486: or other code-generating software.
                   7487: 
                   7488: @item
                   7489: Macros defined using @code{postpone} etc. deal with the language at a
                   7490: higher level than strings; name binding happens at macro definition
                   7491: time, so you can avoid the pitfalls of name collisions that can happen
                   7492: in C macros.  Of course, Forth is a liberal language and also allows to
                   7493: shoot yourself in the foot with text-interpreted macros like
                   7494: 
                   7495: @example
                   7496: : [compile-+] s" +" evaluate ; immediate
                   7497: @end example
                   7498: 
                   7499: Apart from binding the name at macro use time, using @code{evaluate}
                   7500: also makes your definition @code{state}-smart (@pxref{state-smartness}).
                   7501: @end itemize
                   7502: 
                   7503: You may want the macro to compile a number into a word.  The word to do
                   7504: it is @code{literal}, but you have to @code{postpone} it, so its
                   7505: compilation semantics take effect when the macro is executed, not when
                   7506: it is compiled:
                   7507: 
                   7508: @example
                   7509: : [compile-5] ( -- ) \ compiled code: ( -- n )
                   7510:   5 POSTPONE literal ; immediate
                   7511: 
                   7512: : foo [compile-5] ;
                   7513: foo .
                   7514: @end example
                   7515: 
                   7516: You may want to pass parameters to a macro, that the macro should
                   7517: compile into the current definition.  If the parameter is a number, then
                   7518: you can use @code{postpone literal} (similar for other values).
                   7519: 
                   7520: If you want to pass a word that is to be compiled, the usual way is to
                   7521: pass an execution token and @code{compile,} it:
                   7522: 
                   7523: @example
                   7524: : twice1 ( xt -- ) \ compiled code: ... -- ...
                   7525:   dup compile, compile, ;
                   7526: 
                   7527: : 2+ ( n1 -- n2 )
                   7528:   [ ' 1+ twice1 ] ;
                   7529: @end example
                   7530: 
                   7531: doc-compile,
                   7532: 
                   7533: An alternative available in Gforth, that allows you to pass compile-only
                   7534: words as parameters is to use the compilation token (@pxref{Compilation
                   7535: token}).  The same example in this technique:
                   7536: 
                   7537: @example
                   7538: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
                   7539:   2dup 2>r execute 2r> execute ;
                   7540: 
                   7541: : 2+ ( n1 -- n2 )
                   7542:   [ comp' 1+ twice ] ;
                   7543: @end example
                   7544: 
                   7545: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
                   7546: works even if the executed compilation semantics has an effect on the
                   7547: data stack.
                   7548: 
                   7549: You can also define complete definitions with these words; this provides
                   7550: an alternative to using @code{does>} (@pxref{User-defined Defining
                   7551: Words}).  E.g., instead of
                   7552: 
                   7553: @example
                   7554: : curry+ ( n1 "name" -- )
                   7555:     CREATE ,
                   7556: DOES> ( n2 -- n1+n2 )
                   7557:     @@ + ;
                   7558: @end example
                   7559: 
                   7560: you could define
                   7561: 
                   7562: @example
                   7563: : curry+ ( n1 "name" -- )
                   7564:   \ name execution: ( n2 -- n1+n2 )
                   7565:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81      anton    7566: 
1.82      anton    7567: -3 curry+ 3-
                   7568: see 3-
                   7569: @end example
1.81      anton    7570: 
1.82      anton    7571: The sequence @code{>r : r>} is necessary, because @code{:} puts a
                   7572: colon-sys on the data stack that makes everything below it unaccessible.
1.81      anton    7573: 
1.82      anton    7574: This way of writing defining words is sometimes more, sometimes less
                   7575: convenient than using @code{does>} (@pxref{Advanced does> usage
                   7576: example}).  One advantage of this method is that it can be optimized
                   7577: better, because the compiler knows that the value compiled with
                   7578: @code{literal} is fixed, whereas the data associated with a
                   7579: @code{create}d word can be changed.
1.47      crook    7580: 
1.206     anton    7581: @c doc-[compile] !! not properly documented
                   7582: 
1.26      crook    7583: @c ----------------------------------------------------------
1.111     anton    7584: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26      crook    7585: @section  The Text Interpreter
                   7586: @cindex interpreter - outer
                   7587: @cindex text interpreter
                   7588: @cindex outer interpreter
1.1       anton    7589: 
1.34      anton    7590: @c Should we really describe all these ugly details?  IMO the text
                   7591: @c interpreter should be much cleaner, but that may not be possible within
                   7592: @c ANS Forth. - anton
1.44      crook    7593: @c nac-> I wanted to explain how it works to show how you can exploit
                   7594: @c it in your own programs. When I was writing a cross-compiler, figuring out
                   7595: @c some of these gory details was very helpful to me. None of the textbooks
                   7596: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
                   7597: @c seems to positively avoid going into too much detail for some of
                   7598: @c the internals.
1.34      anton    7599: 
1.71      anton    7600: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
                   7601: @c it is; for the ugly details, I would prefer another place.  I wonder
                   7602: @c whether we should have a chapter before "Words" that describes some
                   7603: @c basic concepts referred to in words, and a chapter after "Words" that
                   7604: @c describes implementation details.
                   7605: 
1.29      crook    7606: The text interpreter@footnote{This is an expanded version of the
                   7607: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34      anton    7608: that processes input from the current input device. It is also called
                   7609: the outer interpreter, in contrast to the inner interpreter
                   7610: (@pxref{Engine}) which executes the compiled Forth code on interpretive
                   7611: implementations.
1.27      crook    7612: 
1.29      crook    7613: @cindex interpret state
                   7614: @cindex compile state
                   7615: The text interpreter operates in one of two states: @dfn{interpret
                   7616: state} and @dfn{compile state}. The current state is defined by the
1.71      anton    7617: aptly-named variable @code{state}.
1.29      crook    7618: 
                   7619: This section starts by describing how the text interpreter behaves when
                   7620: it is in interpret state, processing input from the user input device --
                   7621: the keyboard. This is the mode that a Forth system is in after it starts
                   7622: up.
                   7623: 
                   7624: @cindex input buffer
                   7625: @cindex terminal input buffer
                   7626: The text interpreter works from an area of memory called the @dfn{input
                   7627: buffer}@footnote{When the text interpreter is processing input from the
                   7628: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   7629: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   7630: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    7631: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    7632: leading spaces (called @dfn{delimiters}) then parses a string (a
                   7633: sequence of non-space characters) until it reaches either a space
                   7634: character or the end of the buffer. Having parsed a string, it makes two
                   7635: attempts to process it:
1.27      crook    7636: 
1.29      crook    7637: @cindex dictionary
1.27      crook    7638: @itemize @bullet
                   7639: @item
1.29      crook    7640: It looks for the string in a @dfn{dictionary} of definitions. If the
                   7641: string is found, the string names a @dfn{definition} (also known as a
                   7642: @dfn{word}) and the dictionary search returns information that allows
                   7643: the text interpreter to perform the word's @dfn{interpretation
                   7644: semantics}. In most cases, this simply means that the word will be
                   7645: executed.
1.27      crook    7646: @item
                   7647: If the string is not found in the dictionary, the text interpreter
1.29      crook    7648: attempts to treat it as a number, using the rules described in
                   7649: @ref{Number Conversion}. If the string represents a legal number in the
                   7650: current radix, the number is pushed onto a parameter stack (the data
                   7651: stack for integers, the floating-point stack for floating-point
                   7652: numbers).
                   7653: @end itemize
                   7654: 
                   7655: If both attempts fail, or if the word is found in the dictionary but has
                   7656: no interpretation semantics@footnote{This happens if the word was
                   7657: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   7658: remainder of the input buffer, issues an error message and waits for
                   7659: more input. If one of the attempts succeeds, the text interpreter
                   7660: repeats the parsing process until the whole of the input buffer has been
                   7661: processed, at which point it prints the status message ``@code{ ok}''
                   7662: and waits for more input.
                   7663: 
1.71      anton    7664: @c anton: this should be in the input stream subsection (or below it)
                   7665: 
1.29      crook    7666: @cindex parse area
                   7667: The text interpreter keeps track of its position in the input buffer by
                   7668: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   7669: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   7670: of the input buffer. The region from offset @code{>IN @@} to the end of
                   7671: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   7672: the text interpreter processes the contents of the input buffer by
                   7673: parsing strings from the parse area until the parse area is empty.}.
                   7674: This example shows how @code{>IN} changes as the text interpreter parses
                   7675: the input buffer:
                   7676: 
                   7677: @example
                   7678: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   7679:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   7680: 
                   7681: 1 2 3 remaining + remaining . 
                   7682: 
                   7683: : foo 1 2 3 remaining SWAP remaining ;
                   7684: @end example
                   7685: 
                   7686: @noindent
                   7687: The result is:
                   7688: 
                   7689: @example
                   7690: ->+ remaining .<-
                   7691: ->.<-5  ok
                   7692: 
                   7693: ->SWAP remaining ;-<
                   7694: ->;<-  ok
                   7695: @end example
                   7696: 
                   7697: @cindex parsing words
                   7698: The value of @code{>IN} can also be modified by a word in the input
                   7699: buffer that is executed by the text interpreter.  This means that a word
                   7700: can ``trick'' the text interpreter into either skipping a section of the
                   7701: input buffer@footnote{This is how parsing words work.} or into parsing a
                   7702: section twice. For example:
1.27      crook    7703: 
1.29      crook    7704: @example
1.71      anton    7705: : lat ." <<foo>>" ;
                   7706: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29      crook    7707: @end example
                   7708: 
                   7709: @noindent
                   7710: When @code{flat} is executed, this output is produced@footnote{Exercise
                   7711: for the reader: what would happen if the @code{3} were replaced with
                   7712: @code{4}?}:
                   7713: 
                   7714: @example
1.71      anton    7715: <<bar>><<foo>>
1.29      crook    7716: @end example
                   7717: 
1.71      anton    7718: This technique can be used to work around some of the interoperability
                   7719: problems of parsing words.  Of course, it's better to avoid parsing
                   7720: words where possible.
                   7721: 
1.29      crook    7722: @noindent
                   7723: Two important notes about the behaviour of the text interpreter:
1.27      crook    7724: 
                   7725: @itemize @bullet
                   7726: @item
                   7727: It processes each input string to completion before parsing additional
1.29      crook    7728: characters from the input buffer.
                   7729: @item
                   7730: It treats the input buffer as a read-only region (and so must your code).
                   7731: @end itemize
                   7732: 
                   7733: @noindent
                   7734: When the text interpreter is in compile state, its behaviour changes in
                   7735: these ways:
                   7736: 
                   7737: @itemize @bullet
                   7738: @item
                   7739: If a parsed string is found in the dictionary, the text interpreter will
                   7740: perform the word's @dfn{compilation semantics}. In most cases, this
                   7741: simply means that the execution semantics of the word will be appended
                   7742: to the current definition.
1.27      crook    7743: @item
1.29      crook    7744: When a number is encountered, it is compiled into the current definition
                   7745: (as a literal) rather than being pushed onto a parameter stack.
                   7746: @item
                   7747: If an error occurs, @code{state} is modified to put the text interpreter
                   7748: back into interpret state.
                   7749: @item
                   7750: Each time a line is entered from the keyboard, Gforth prints
                   7751: ``@code{ compiled}'' rather than `` @code{ok}''.
                   7752: @end itemize
                   7753: 
                   7754: @cindex text interpreter - input sources
                   7755: When the text interpreter is using an input device other than the
                   7756: keyboard, its behaviour changes in these ways:
                   7757: 
                   7758: @itemize @bullet
                   7759: @item
                   7760: When the parse area is empty, the text interpreter attempts to refill
                   7761: the input buffer from the input source. When the input source is
1.71      anton    7762: exhausted, the input source is set back to the previous input source.
1.29      crook    7763: @item
                   7764: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   7765: time the parse area is emptied.
                   7766: @item
                   7767: If an error occurs, the input source is set back to the user input
                   7768: device.
1.27      crook    7769: @end itemize
1.21      crook    7770: 
1.49      anton    7771: You can read about this in more detail in @ref{Input Sources}.
1.44      crook    7772: 
1.26      crook    7773: doc->in
1.27      crook    7774: doc-source
                   7775: 
1.26      crook    7776: doc-tib
                   7777: doc-#tib
1.1       anton    7778: 
1.44      crook    7779: 
1.26      crook    7780: @menu
1.67      anton    7781: * Input Sources::               
                   7782: * Number Conversion::           
                   7783: * Interpret/Compile states::    
                   7784: * Interpreter Directives::      
1.26      crook    7785: @end menu
1.1       anton    7786: 
1.29      crook    7787: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   7788: @subsection Input Sources
                   7789: @cindex input sources
                   7790: @cindex text interpreter - input sources
                   7791: 
1.44      crook    7792: By default, the text interpreter processes input from the user input
1.29      crook    7793: device (the keyboard) when Forth starts up. The text interpreter can
                   7794: process input from any of these sources:
                   7795: 
                   7796: @itemize @bullet
                   7797: @item
                   7798: The user input device -- the keyboard.
                   7799: @item
                   7800: A file, using the words described in @ref{Forth source files}.
                   7801: @item
                   7802: A block, using the words described in @ref{Blocks}.
                   7803: @item
                   7804: A text string, using @code{evaluate}.
                   7805: @end itemize
                   7806: 
                   7807: A program can identify the current input device from the values of
                   7808: @code{source-id} and @code{blk}.
                   7809: 
1.44      crook    7810: 
1.29      crook    7811: doc-source-id
                   7812: doc-blk
                   7813: 
                   7814: doc-save-input
                   7815: doc-restore-input
                   7816: 
                   7817: doc-evaluate
1.111     anton    7818: doc-query
1.1       anton    7819: 
1.29      crook    7820: 
1.44      crook    7821: 
1.29      crook    7822: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    7823: @subsection Number Conversion
                   7824: @cindex number conversion
                   7825: @cindex double-cell numbers, input format
                   7826: @cindex input format for double-cell numbers
                   7827: @cindex single-cell numbers, input format
                   7828: @cindex input format for single-cell numbers
                   7829: @cindex floating-point numbers, input format
                   7830: @cindex input format for floating-point numbers
1.1       anton    7831: 
1.29      crook    7832: This section describes the rules that the text interpreter uses when it
                   7833: tries to convert a string into a number.
1.1       anton    7834: 
1.26      crook    7835: Let <digit> represent any character that is a legal digit in the current
1.29      crook    7836: number base@footnote{For example, 0-9 when the number base is decimal or
                   7837: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    7838: 
1.26      crook    7839: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    7840: 
1.29      crook    7841: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   7842: in the braces (@i{a} or @i{b} or neither).
1.1       anton    7843: 
1.26      crook    7844: Let * represent any number of instances of the previous character
                   7845: (including none).
1.1       anton    7846: 
1.26      crook    7847: Let any other character represent itself.
1.1       anton    7848: 
1.29      crook    7849: @noindent
1.26      crook    7850: Now, the conversion rules are:
1.21      crook    7851: 
1.26      crook    7852: @itemize @bullet
                   7853: @item
                   7854: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    7855: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    7856: @item
                   7857: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    7858: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    7859: arithmetic. Examples are -45 -5681 -0
                   7860: @item
                   7861: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    7862: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   7863: (all three of these represent the same number).
1.26      crook    7864: @item
                   7865: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    7866: double-precision (double-cell-sized) negative integer, and is
1.26      crook    7867: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    7868: -34.65 (all three of these represent the same number).
1.26      crook    7869: @item
1.29      crook    7870: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   7871: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35      anton    7872: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    7873: number) +12.E-4
1.26      crook    7874: @end itemize
1.1       anton    7875: 
1.174     anton    7876: By default, the number base used for integer number conversion is
                   7877: given by the contents of the variable @code{base}.  Note that a lot of
1.35      anton    7878: confusion can result from unexpected values of @code{base}.  If you
1.174     anton    7879: change @code{base} anywhere, make sure to save the old value and
                   7880: restore it afterwards; better yet, use @code{base-execute}, which does
                   7881: this for you.  In general I recommend keeping @code{base} decimal, and
1.35      anton    7882: using the prefixes described below for the popular non-decimal bases.
1.1       anton    7883: 
1.29      crook    7884: doc-dpl
1.174     anton    7885: doc-base-execute
1.26      crook    7886: doc-base
                   7887: doc-hex
                   7888: doc-decimal
1.1       anton    7889: 
1.26      crook    7890: @cindex '-prefix for character strings
                   7891: @cindex &-prefix for decimal numbers
1.133     anton    7892: @cindex #-prefix for decimal numbers
1.26      crook    7893: @cindex %-prefix for binary numbers
                   7894: @cindex $-prefix for hexadecimal numbers
1.133     anton    7895: @cindex 0x-prefix for hexadecimal numbers
1.35      anton    7896: Gforth allows you to override the value of @code{base} by using a
1.29      crook    7897: prefix@footnote{Some Forth implementations provide a similar scheme by
                   7898: implementing @code{$} etc. as parsing words that process the subsequent
                   7899: number in the input stream and push it onto the stack. For example, see
                   7900: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   7901: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   7902: is required between the prefix and the number.} before the first digit
1.133     anton    7903: of an (integer) number. The following prefixes are supported:
1.1       anton    7904: 
1.26      crook    7905: @itemize @bullet
                   7906: @item
1.35      anton    7907: @code{&} -- decimal
1.26      crook    7908: @item
1.133     anton    7909: @code{#} -- decimal
                   7910: @item
1.35      anton    7911: @code{%} -- binary
1.26      crook    7912: @item
1.35      anton    7913: @code{$} -- hexadecimal
1.26      crook    7914: @item
1.133     anton    7915: @code{0x} -- hexadecimal, if base<33.
                   7916: @item
                   7917: @code{'} -- numeric value (e.g., ASCII code) of next character; an
                   7918: optional @code{'} may be present after the character.
1.26      crook    7919: @end itemize
1.1       anton    7920: 
1.26      crook    7921: Here are some examples, with the equivalent decimal number shown after
                   7922: in braces:
1.1       anton    7923: 
1.26      crook    7924: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133     anton    7925: 'A (65),
                   7926: -'a' (-97),
1.26      crook    7927: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    7928: 
1.26      crook    7929: @cindex number conversion - traps for the unwary
1.29      crook    7930: @noindent
1.26      crook    7931: Number conversion has a number of traps for the unwary:
1.1       anton    7932: 
1.26      crook    7933: @itemize @bullet
                   7934: @item
                   7935: You cannot determine the current number base using the code sequence
1.35      anton    7936: @code{base @@ .} -- the number base is always 10 in the current number
                   7937: base. Instead, use something like @code{base @@ dec.}
1.26      crook    7938: @item
                   7939: If the number base is set to a value greater than 14 (for example,
                   7940: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   7941: it to be intepreted as either a single-precision integer or a
                   7942: floating-point number (Gforth treats it as an integer). The ambiguity
                   7943: can be resolved by explicitly stating the sign of the mantissa and/or
                   7944: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   7945: ambiguity arises; either representation will be treated as a
                   7946: floating-point number.
                   7947: @item
1.29      crook    7948: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    7949: It is used to specify file types.
                   7950: @item
1.72      anton    7951: ANS Forth requires the @code{.} of a double-precision number to be the
                   7952: final character in the string.  Gforth allows the @code{.} to be
                   7953: anywhere after the first digit.
1.26      crook    7954: @item
                   7955: The number conversion process does not check for overflow.
                   7956: @item
1.72      anton    7957: In an ANS Forth program @code{base} is required to be decimal when
                   7958: converting floating-point numbers.  In Gforth, number conversion to
                   7959: floating-point numbers always uses base &10, irrespective of the value
                   7960: of @code{base}.
1.26      crook    7961: @end itemize
1.1       anton    7962: 
1.49      anton    7963: You can read numbers into your programs with the words described in
1.181     anton    7964: @ref{Line input and conversion}.
1.1       anton    7965: 
1.82      anton    7966: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26      crook    7967: @subsection Interpret/Compile states
                   7968: @cindex Interpret/Compile states
1.1       anton    7969: 
1.29      crook    7970: A standard program is not permitted to change @code{state}
                   7971: explicitly. However, it can change @code{state} implicitly, using the
                   7972: words @code{[} and @code{]}. When @code{[} is executed it switches
                   7973: @code{state} to interpret state, and therefore the text interpreter
                   7974: starts interpreting. When @code{]} is executed it switches @code{state}
                   7975: to compile state and therefore the text interpreter starts
1.44      crook    7976: compiling. The most common usage for these words is for switching into
                   7977: interpret state and back from within a colon definition; this technique
1.49      anton    7978: can be used to compile a literal (for an example, @pxref{Literals}) or
                   7979: for conditional compilation (for an example, @pxref{Interpreter
                   7980: Directives}).
1.44      crook    7981: 
1.35      anton    7982: 
                   7983: @c This is a bad example: It's non-standard, and it's not necessary.
                   7984: @c However, I can't think of a good example for switching into compile
                   7985: @c state when there is no current word (@code{state}-smart words are not a
                   7986: @c good reason).  So maybe we should use an example for switching into
                   7987: @c interpret @code{state} in a colon def. - anton
1.44      crook    7988: @c nac-> I agree. I started out by putting in the example, then realised
                   7989: @c that it was non-ANS, so wrote more words around it. I hope this
                   7990: @c re-written version is acceptable to you. I do want to keep the example
                   7991: @c as it is helpful for showing what is and what is not portable, particularly
                   7992: @c where it outlaws a style in common use.
                   7993: 
1.72      anton    7994: @c anton: it's more important to show what's portable.  After we have done
1.83      anton    7995: @c that, we can also show what's not.  In any case, I have written a
                   7996: @c section Compiling Words which also deals with [ ].
1.35      anton    7997: 
1.95      anton    7998: @c  !! The following example does not work in Gforth 0.5.9 or later.
1.29      crook    7999: 
1.95      anton    8000: @c  @code{[} and @code{]} also give you the ability to switch into compile
                   8001: @c  state and back, but we cannot think of any useful Standard application
                   8002: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
                   8003: 
                   8004: @c  @example
                   8005: @c  : AA ." this is A" ;
                   8006: @c  : BB ." this is B" ;
                   8007: @c  : CC ." this is C" ;
                   8008: 
                   8009: @c  create table ] aa bb cc [
                   8010: 
                   8011: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   8012: @c    cells table + @@ execute ;
                   8013: @c  @end example
                   8014: 
                   8015: @c  This example builds a jump table; @code{0 go} will display ``@code{this
                   8016: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
                   8017: @c  defining @code{table} like this:
                   8018: 
                   8019: @c  @example
                   8020: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
                   8021: @c  @end example
                   8022: 
                   8023: @c  The problem with this code is that the definition of @code{table} is not
                   8024: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
                   8025: @c  @i{may} work on systems where code space and data space co-incide, the
                   8026: @c  Standard only allows data space to be assigned for a @code{CREATE}d
                   8027: @c  word. In addition, the Standard only allows @code{@@} to access data
                   8028: @c  space, whilst this example is using it to access code space. The only
                   8029: @c  portable, Standard way to build this table is to build it in data space,
                   8030: @c  like this:
                   8031: 
                   8032: @c  @example
                   8033: @c  create table ' aa , ' bb , ' cc ,
                   8034: @c  @end example
1.29      crook    8035: 
1.95      anton    8036: @c  doc-state
1.44      crook    8037: 
1.29      crook    8038: 
1.82      anton    8039: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
1.26      crook    8040: @subsection Interpreter Directives
                   8041: @cindex interpreter directives
1.72      anton    8042: @cindex conditional compilation
1.1       anton    8043: 
1.29      crook    8044: These words are usually used in interpret state; typically to control
                   8045: which parts of a source file are processed by the text
1.26      crook    8046: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   8047: supplements these with a rich set of immediate control structure words
                   8048: to compensate for the fact that the non-immediate versions can only be
1.29      crook    8049: used in compile state (@pxref{Control Structures}). Typical usages:
                   8050: 
                   8051: @example
1.72      anton    8052: FALSE Constant HAVE-ASSEMBLER
1.29      crook    8053: .
                   8054: .
1.72      anton    8055: HAVE-ASSEMBLER [IF]
1.29      crook    8056: : ASSEMBLER-FEATURE
                   8057:   ...
                   8058: ;
                   8059: [ENDIF]
                   8060: .
                   8061: .
                   8062: : SEE
                   8063:   ... \ general-purpose SEE code
1.72      anton    8064:   [ HAVE-ASSEMBLER [IF] ]
1.29      crook    8065:   ... \ assembler-specific SEE code
                   8066:   [ [ENDIF] ]
                   8067: ;
                   8068: @end example
1.1       anton    8069: 
1.44      crook    8070: 
1.26      crook    8071: doc-[IF]
                   8072: doc-[ELSE]
                   8073: doc-[THEN]
                   8074: doc-[ENDIF]
1.1       anton    8075: 
1.26      crook    8076: doc-[IFDEF]
                   8077: doc-[IFUNDEF]
1.1       anton    8078: 
1.26      crook    8079: doc-[?DO]
                   8080: doc-[DO]
                   8081: doc-[FOR]
                   8082: doc-[LOOP]
                   8083: doc-[+LOOP]
                   8084: doc-[NEXT]
1.1       anton    8085: 
1.26      crook    8086: doc-[BEGIN]
                   8087: doc-[UNTIL]
                   8088: doc-[AGAIN]
                   8089: doc-[WHILE]
                   8090: doc-[REPEAT]
1.1       anton    8091: 
1.27      crook    8092: 
1.26      crook    8093: @c -------------------------------------------------------------
1.111     anton    8094: @node The Input Stream, Word Lists, The Text Interpreter, Words
                   8095: @section The Input Stream
                   8096: @cindex input stream
                   8097: 
                   8098: @c !! integrate this better with the "Text Interpreter" section
                   8099: The text interpreter reads from the input stream, which can come from
                   8100: several sources (@pxref{Input Sources}).  Some words, in particular
                   8101: defining words, but also words like @code{'}, read parameters from the
                   8102: input stream instead of from the stack.
                   8103: 
                   8104: Such words are called parsing words, because they parse the input
                   8105: stream.  Parsing words are hard to use in other words, because it is
                   8106: hard to pass program-generated parameters through the input stream.
                   8107: They also usually have an unintuitive combination of interpretation and
                   8108: compilation semantics when implemented naively, leading to various
                   8109: approaches that try to produce a more intuitive behaviour
                   8110: (@pxref{Combined words}).
                   8111: 
                   8112: It should be obvious by now that parsing words are a bad idea.  If you
                   8113: want to implement a parsing word for convenience, also provide a factor
                   8114: of the word that does not parse, but takes the parameters on the stack.
                   8115: To implement the parsing word on top if it, you can use the following
                   8116: words:
                   8117: 
                   8118: @c anton: these belong in the input stream section
                   8119: doc-parse
1.138     anton    8120: doc-parse-name
1.111     anton    8121: doc-parse-word
                   8122: doc-name
                   8123: doc-word
                   8124: doc-refill
                   8125: 
                   8126: Conversely, if you have the bad luck (or lack of foresight) to have to
                   8127: deal with parsing words without having such factors, how do you pass a
                   8128: string that is not in the input stream to it?
                   8129: 
                   8130: doc-execute-parsing
                   8131: 
1.146     anton    8132: A definition of this word in ANS Forth is provided in
                   8133: @file{compat/execute-parsing.fs}.
                   8134: 
1.111     anton    8135: If you want to run a parsing word on a file, the following word should
                   8136: help:
                   8137: 
                   8138: doc-execute-parsing-file
                   8139: 
                   8140: @c -------------------------------------------------------------
                   8141: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26      crook    8142: @section Word Lists
                   8143: @cindex word lists
1.32      anton    8144: @cindex header space
1.1       anton    8145: 
1.36      anton    8146: A wordlist is a list of named words; you can add new words and look up
                   8147: words by name (and you can remove words in a restricted way with
                   8148: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
                   8149: 
                   8150: @cindex search order stack
                   8151: The text interpreter searches the wordlists present in the search order
                   8152: (a stack of wordlists), from the top to the bottom.  Within each
                   8153: wordlist, the search starts conceptually at the newest word; i.e., if
                   8154: two words in a wordlist have the same name, the newer word is found.
1.1       anton    8155: 
1.26      crook    8156: @cindex compilation word list
1.36      anton    8157: New words are added to the @dfn{compilation wordlist} (aka current
                   8158: wordlist).
1.1       anton    8159: 
1.36      anton    8160: @cindex wid
                   8161: A word list is identified by a cell-sized word list identifier (@i{wid})
                   8162: in much the same way as a file is identified by a file handle. The
                   8163: numerical value of the wid has no (portable) meaning, and might change
                   8164: from session to session.
1.1       anton    8165: 
1.29      crook    8166: The ANS Forth ``Search order'' word set is intended to provide a set of
                   8167: low-level tools that allow various different schemes to be
1.74      anton    8168: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26      crook    8169: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
1.45      crook    8170: Forth.
1.1       anton    8171: 
1.27      crook    8172: @comment TODO: locals section refers to here, saying that every word list (aka
                   8173: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78      anton    8174: @c anton: but better in a separate subsection on wordlist internals
1.1       anton    8175: 
1.45      crook    8176: @comment TODO: document markers, reveal, tables, mappedwordlist
                   8177: 
                   8178: @comment the gforthman- prefix is used to pick out the true definition of a
1.27      crook    8179: @comment word from the source files, rather than some alias.
1.44      crook    8180: 
1.26      crook    8181: doc-forth-wordlist
                   8182: doc-definitions
                   8183: doc-get-current
                   8184: doc-set-current
                   8185: doc-get-order
1.185     anton    8186: doc-set-order
1.26      crook    8187: doc-wordlist
1.30      anton    8188: doc-table
1.79      anton    8189: doc->order
1.36      anton    8190: doc-previous
1.26      crook    8191: doc-also
1.185     anton    8192: doc-forth
1.26      crook    8193: doc-only
1.185     anton    8194: doc-order
1.15      anton    8195: 
1.26      crook    8196: doc-find
                   8197: doc-search-wordlist
1.15      anton    8198: 
1.26      crook    8199: doc-words
                   8200: doc-vlist
1.44      crook    8201: @c doc-words-deferred
1.1       anton    8202: 
1.74      anton    8203: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26      crook    8204: doc-root
                   8205: doc-vocabulary
                   8206: doc-seal
                   8207: doc-vocs
                   8208: doc-current
                   8209: doc-context
1.1       anton    8210: 
1.44      crook    8211: 
1.26      crook    8212: @menu
1.75      anton    8213: * Vocabularies::                
1.67      anton    8214: * Why use word lists?::         
1.75      anton    8215: * Word list example::           
1.26      crook    8216: @end menu
                   8217: 
1.75      anton    8218: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
                   8219: @subsection Vocabularies
                   8220: @cindex Vocabularies, detailed explanation
                   8221: 
                   8222: Here is an example of creating and using a new wordlist using ANS
                   8223: Forth words:
                   8224: 
                   8225: @example
                   8226: wordlist constant my-new-words-wordlist
                   8227: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
                   8228: 
                   8229: \ add it to the search order
                   8230: also my-new-words
                   8231: 
                   8232: \ alternatively, add it to the search order and make it
                   8233: \ the compilation word list
                   8234: also my-new-words definitions
                   8235: \ type "order" to see the problem
                   8236: @end example
                   8237: 
                   8238: The problem with this example is that @code{order} has no way to
                   8239: associate the name @code{my-new-words} with the wid of the word list (in
                   8240: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   8241: that has no associated name). There is no Standard way of associating a
                   8242: name with a wid.
                   8243: 
                   8244: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   8245: associates a name with a wid:
                   8246: 
                   8247: @example
                   8248: vocabulary my-new-words
                   8249: 
                   8250: \ add it to the search order
                   8251: also my-new-words
                   8252: 
                   8253: \ alternatively, add it to the search order and make it
                   8254: \ the compilation word list
                   8255: my-new-words definitions
                   8256: \ type "order" to see that the problem is solved
                   8257: @end example
                   8258: 
                   8259: 
                   8260: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26      crook    8261: @subsection Why use word lists?
                   8262: @cindex word lists - why use them?
                   8263: 
1.74      anton    8264: Here are some reasons why people use wordlists:
1.26      crook    8265: 
                   8266: @itemize @bullet
1.74      anton    8267: 
                   8268: @c anton: Gforth's hashing implementation makes the search speed
                   8269: @c independent from the number of words.  But it is linear with the number
                   8270: @c of wordlists that have to be searched, so in effect using more wordlists
                   8271: @c actually slows down compilation.
                   8272: 
                   8273: @c @item
                   8274: @c To improve compilation speed by reducing the number of header space
                   8275: @c entries that must be searched. This is achieved by creating a new
                   8276: @c word list that contains all of the definitions that are used in the
                   8277: @c definition of a Forth system but which would not usually be used by
                   8278: @c programs running on that system. That word list would be on the search
                   8279: @c list when the Forth system was compiled but would be removed from the
                   8280: @c search list for normal operation. This can be a useful technique for
                   8281: @c low-performance systems (for example, 8-bit processors in embedded
                   8282: @c systems) but is unlikely to be necessary in high-performance desktop
                   8283: @c systems.
                   8284: 
1.26      crook    8285: @item
                   8286: To prevent a set of words from being used outside the context in which
                   8287: they are valid. Two classic examples of this are an integrated editor
                   8288: (all of the edit commands are defined in a separate word list; the
                   8289: search order is set to the editor word list when the editor is invoked;
                   8290: the old search order is restored when the editor is terminated) and an
                   8291: integrated assembler (the op-codes for the machine are defined in a
                   8292: separate word list which is used when a @code{CODE} word is defined).
1.74      anton    8293: 
                   8294: @item
                   8295: To organize the words of an application or library into a user-visible
                   8296: set (in @code{forth-wordlist} or some other common wordlist) and a set
                   8297: of helper words used just for the implementation (hidden in a separate
1.75      anton    8298: wordlist).  This keeps @code{words}' output smaller, separates
                   8299: implementation and interface, and reduces the chance of name conflicts
                   8300: within the common wordlist.
1.74      anton    8301: 
1.26      crook    8302: @item
                   8303: To prevent a name-space clash between multiple definitions with the same
                   8304: name. For example, when building a cross-compiler you might have a word
                   8305: @code{IF} that generates conditional code for your target system. By
                   8306: placing this definition in a different word list you can control whether
                   8307: the host system's @code{IF} or the target system's @code{IF} get used in
                   8308: any particular context by controlling the order of the word lists on the
                   8309: search order stack.
1.74      anton    8310: 
1.26      crook    8311: @end itemize
1.1       anton    8312: 
1.74      anton    8313: The downsides of using wordlists are:
                   8314: 
                   8315: @itemize
                   8316: 
                   8317: @item
                   8318: Debugging becomes more cumbersome.
                   8319: 
                   8320: @item
                   8321: Name conflicts worked around with wordlists are still there, and you
                   8322: have to arrange the search order carefully to get the desired results;
                   8323: if you forget to do that, you get hard-to-find errors (as in any case
                   8324: where you read the code differently from the compiler; @code{see} can
1.75      anton    8325: help seeing which of several possible words the name resolves to in such
                   8326: cases).  @code{See} displays just the name of the words, not what
                   8327: wordlist they belong to, so it might be misleading.  Using unique names
                   8328: is a better approach to avoid name conflicts.
1.74      anton    8329: 
                   8330: @item
                   8331: You have to explicitly undo any changes to the search order.  In many
                   8332: cases it would be more convenient if this happened implicitly.  Gforth
                   8333: currently does not provide such a feature, but it may do so in the
                   8334: future.
                   8335: @end itemize
                   8336: 
                   8337: 
1.75      anton    8338: @node Word list example,  , Why use word lists?, Word Lists
                   8339: @subsection Word list example
                   8340: @cindex word lists - example
1.1       anton    8341: 
1.74      anton    8342: The following example is from the
                   8343: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   8344: garbage collector} and uses wordlists to separate public words from
                   8345: helper words:
                   8346: 
                   8347: @example
                   8348: get-current ( wid )
                   8349: vocabulary garbage-collector also garbage-collector definitions
                   8350: ... \ define helper words
                   8351: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
                   8352: ... \ define the public (i.e., API) words
                   8353:     \ they can refer to the helper words
                   8354: previous \ restore original search order (helper words become invisible)
                   8355: @end example
                   8356: 
1.26      crook    8357: @c -------------------------------------------------------------
                   8358: @node Environmental Queries, Files, Word Lists, Words
                   8359: @section Environmental Queries
                   8360: @cindex environmental queries
1.21      crook    8361: 
1.26      crook    8362: ANS Forth introduced the idea of ``environmental queries'' as a way
                   8363: for a program running on a system to determine certain characteristics of the system.
                   8364: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    8365: 
1.32      anton    8366: The Standard requires that the header space used for environmental queries
                   8367: be distinct from the header space used for definitions.
1.21      crook    8368: 
1.26      crook    8369: Typically, environmental queries are supported by creating a set of
1.29      crook    8370: definitions in a word list that is @i{only} used during environmental
1.26      crook    8371: queries; that is what Gforth does. There is no Standard way of adding
                   8372: definitions to the set of recognised environmental queries, but any
                   8373: implementation that supports the loading of optional word sets must have
                   8374: some mechanism for doing this (after loading the word set, the
                   8375: associated environmental query string must return @code{true}). In
                   8376: Gforth, the word list used to honour environmental queries can be
                   8377: manipulated just like any other word list.
1.21      crook    8378: 
1.44      crook    8379: 
1.26      crook    8380: doc-environment?
                   8381: doc-environment-wordlist
1.21      crook    8382: 
1.26      crook    8383: doc-gforth
                   8384: doc-os-class
1.21      crook    8385: 
1.44      crook    8386: 
1.26      crook    8387: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   8388: returning two items on the stack, querying it using @code{environment?}
                   8389: will return an additional item; the @code{true} flag that shows that the
                   8390: string was recognised.
1.21      crook    8391: 
1.26      crook    8392: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    8393: 
1.26      crook    8394: Here are some examples of using environmental queries:
1.21      crook    8395: 
1.26      crook    8396: @example
                   8397: s" address-unit-bits" environment? 0=
                   8398: [IF]
                   8399:      cr .( environmental attribute address-units-bits unknown... ) cr
1.75      anton    8400: [ELSE]
                   8401:      drop \ ensure balanced stack effect
1.26      crook    8402: [THEN]
1.21      crook    8403: 
1.75      anton    8404: \ this might occur in the prelude of a standard program that uses THROW
                   8405: s" exception" environment? [IF]
                   8406:    0= [IF]
                   8407:       : throw abort" exception thrown" ;
                   8408:    [THEN]
                   8409: [ELSE] \ we don't know, so make sure
                   8410:    : throw abort" exception thrown" ;
                   8411: [THEN]
1.21      crook    8412: 
1.26      crook    8413: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   8414:                         [ELSE] .( Not Gforth..) [THEN]
1.75      anton    8415: 
                   8416: \ a program using v*
                   8417: s" gforth" environment? [IF]
                   8418:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
                   8419:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8420:      >r swap 2swap swap 0e r> 0 ?DO
1.190     anton    8421:        dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
1.75      anton    8422:      LOOP
                   8423:      2drop 2drop ; 
                   8424:   [THEN]
                   8425: [ELSE] \ 
                   8426:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8427:   ...
                   8428: [THEN]
1.26      crook    8429: @end example
1.21      crook    8430: 
1.26      crook    8431: Here is an example of adding a definition to the environment word list:
1.21      crook    8432: 
1.26      crook    8433: @example
                   8434: get-current environment-wordlist set-current
                   8435: true constant block
                   8436: true constant block-ext
                   8437: set-current
                   8438: @end example
1.21      crook    8439: 
1.26      crook    8440: You can see what definitions are in the environment word list like this:
1.21      crook    8441: 
1.26      crook    8442: @example
1.79      anton    8443: environment-wordlist >order words previous
1.26      crook    8444: @end example
1.21      crook    8445: 
                   8446: 
1.26      crook    8447: @c -------------------------------------------------------------
                   8448: @node Files, Blocks, Environmental Queries, Words
                   8449: @section Files
1.28      crook    8450: @cindex files
                   8451: @cindex I/O - file-handling
1.21      crook    8452: 
1.26      crook    8453: Gforth provides facilities for accessing files that are stored in the
                   8454: host operating system's file-system. Files that are processed by Gforth
                   8455: can be divided into two categories:
1.21      crook    8456: 
1.23      crook    8457: @itemize @bullet
                   8458: @item
1.29      crook    8459: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    8460: @item
1.29      crook    8461: Files that are processed by some other program (@dfn{general files}).
1.26      crook    8462: @end itemize
                   8463: 
                   8464: @menu
1.48      anton    8465: * Forth source files::          
                   8466: * General files::               
1.167     anton    8467: * Redirection::                 
1.48      anton    8468: * Search Paths::                
1.26      crook    8469: @end menu
                   8470: 
                   8471: @c -------------------------------------------------------------
                   8472: @node Forth source files, General files, Files, Files
                   8473: @subsection Forth source files
                   8474: @cindex including files
                   8475: @cindex Forth source files
1.21      crook    8476: 
1.26      crook    8477: The simplest way to interpret the contents of a file is to use one of
                   8478: these two formats:
1.21      crook    8479: 
1.26      crook    8480: @example
                   8481: include mysource.fs
                   8482: s" mysource.fs" included
                   8483: @end example
1.21      crook    8484: 
1.75      anton    8485: You usually want to include a file only if it is not included already
1.26      crook    8486: (by, say, another source file). In that case, you can use one of these
1.45      crook    8487: three formats:
1.21      crook    8488: 
1.26      crook    8489: @example
                   8490: require mysource.fs
                   8491: needs mysource.fs
                   8492: s" mysource.fs" required
                   8493: @end example
1.21      crook    8494: 
1.26      crook    8495: @cindex stack effect of included files
                   8496: @cindex including files, stack effect
1.45      crook    8497: It is good practice to write your source files such that interpreting them
                   8498: does not change the stack. Source files designed in this way can be used with
1.26      crook    8499: @code{required} and friends without complications. For example:
1.21      crook    8500: 
1.26      crook    8501: @example
1.75      anton    8502: 1024 require foo.fs drop
1.26      crook    8503: @end example
1.21      crook    8504: 
1.75      anton    8505: Here you want to pass the argument 1024 (e.g., a buffer size) to
                   8506: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
                   8507: ), which allows its use with @code{require}.  Of course with such
                   8508: parameters to required files, you have to ensure that the first
                   8509: @code{require} fits for all uses (i.e., @code{require} it early in the
                   8510: master load file).
1.44      crook    8511: 
1.26      crook    8512: doc-include-file
                   8513: doc-included
1.28      crook    8514: doc-included?
1.26      crook    8515: doc-include
                   8516: doc-required
                   8517: doc-require
                   8518: doc-needs
1.75      anton    8519: @c doc-init-included-files @c internal
                   8520: doc-sourcefilename
                   8521: doc-sourceline#
1.44      crook    8522: 
1.26      crook    8523: A definition in ANS Forth for @code{required} is provided in
                   8524: @file{compat/required.fs}.
1.21      crook    8525: 
1.26      crook    8526: @c -------------------------------------------------------------
1.167     anton    8527: @node General files, Redirection, Forth source files, Files
1.26      crook    8528: @subsection General files
                   8529: @cindex general files
                   8530: @cindex file-handling
1.21      crook    8531: 
1.75      anton    8532: Files are opened/created by name and type. The following file access
                   8533: methods (FAMs) are recognised:
1.44      crook    8534: 
1.75      anton    8535: @cindex fam (file access method)
1.26      crook    8536: doc-r/o
                   8537: doc-r/w
                   8538: doc-w/o
                   8539: doc-bin
1.1       anton    8540: 
1.44      crook    8541: 
1.26      crook    8542: When a file is opened/created, it returns a file identifier,
1.29      crook    8543: @i{wfileid} that is used for all other file commands. All file
                   8544: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    8545: successful operation and an implementation-defined non-zero value in the
                   8546: case of an error.
1.21      crook    8547: 
1.44      crook    8548: 
1.26      crook    8549: doc-open-file
                   8550: doc-create-file
1.21      crook    8551: 
1.26      crook    8552: doc-close-file
                   8553: doc-delete-file
                   8554: doc-rename-file
                   8555: doc-read-file
                   8556: doc-read-line
1.154     anton    8557: doc-key-file
                   8558: doc-key?-file
1.26      crook    8559: doc-write-file
                   8560: doc-write-line
                   8561: doc-emit-file
                   8562: doc-flush-file
1.21      crook    8563: 
1.26      crook    8564: doc-file-status
                   8565: doc-file-position
                   8566: doc-reposition-file
                   8567: doc-file-size
                   8568: doc-resize-file
1.21      crook    8569: 
1.93      anton    8570: doc-slurp-file
                   8571: doc-slurp-fid
1.112     anton    8572: doc-stdin
                   8573: doc-stdout
                   8574: doc-stderr
1.44      crook    8575: 
1.26      crook    8576: @c ---------------------------------------------------------
1.167     anton    8577: @node Redirection, Search Paths, General files, Files
                   8578: @subsection Redirection
                   8579: @cindex Redirection
                   8580: @cindex Input Redirection
                   8581: @cindex Output Redirection
                   8582: 
                   8583: You can redirect the output of @code{type} and @code{emit} and all the
                   8584: words that use them (all output words that don't have an explicit
1.174     anton    8585: target file) to an arbitrary file with the @code{outfile-execute},
                   8586: used like this:
1.167     anton    8587: 
                   8588: @example
1.174     anton    8589: : some-warning ( n -- )
                   8590:     cr ." warning# " . ;
                   8591: 
1.167     anton    8592: : print-some-warning ( n -- )
1.174     anton    8593:     ['] some-warning stderr outfile-execute ;
1.167     anton    8594: @end example
                   8595: 
1.174     anton    8596: After @code{some-warning} is executed, the original output direction
                   8597: is restored; this construct is safe against exceptions.  Similarly,
                   8598: there is @code{infile-execute} for redirecting the input of @code{key}
                   8599: and its users (any input word that does not take a file explicitly).
                   8600: 
                   8601: doc-outfile-execute
                   8602: doc-infile-execute
1.167     anton    8603: 
                   8604: If you do not want to redirect the input or output to a file, you can
                   8605: also make use of the fact that @code{key}, @code{emit} and @code{type}
                   8606: are deferred words (@pxref{Deferred Words}).  However, in that case
                   8607: you have to worry about the restoration and the protection against
                   8608: exceptions yourself; also, note that for redirecting the output in
                   8609: this way, you have to redirect both @code{emit} and @code{type}.
                   8610: 
                   8611: @c ---------------------------------------------------------
                   8612: @node Search Paths,  , Redirection, Files
1.26      crook    8613: @subsection Search Paths
                   8614: @cindex path for @code{included}
                   8615: @cindex file search path
                   8616: @cindex @code{include} search path
                   8617: @cindex search path for files
1.21      crook    8618: 
1.26      crook    8619: If you specify an absolute filename (i.e., a filename starting with
                   8620: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   8621: @samp{C:...})) for @code{included} and friends, that file is included
                   8622: just as you would expect.
1.21      crook    8623: 
1.75      anton    8624: If the filename starts with @file{./}, this refers to the directory that
                   8625: the present file was @code{included} from.  This allows files to include
                   8626: other files relative to their own position (irrespective of the current
                   8627: working directory or the absolute position).  This feature is essential
                   8628: for libraries consisting of several files, where a file may include
                   8629: other files from the library.  It corresponds to @code{#include "..."}
                   8630: in C. If the current input source is not a file, @file{.} refers to the
                   8631: directory of the innermost file being included, or, if there is no file
                   8632: being included, to the current working directory.
                   8633: 
                   8634: For relative filenames (not starting with @file{./}), Gforth uses a
                   8635: search path similar to Forth's search order (@pxref{Word Lists}). It
                   8636: tries to find the given filename in the directories present in the path,
                   8637: and includes the first one it finds. There are separate search paths for
                   8638: Forth source files and general files.  If the search path contains the
                   8639: directory @file{.}, this refers to the directory of the current file, or
                   8640: the working directory, as if the file had been specified with @file{./}.
1.21      crook    8641: 
1.26      crook    8642: Use @file{~+} to refer to the current working directory (as in the
                   8643: @code{bash}).
1.1       anton    8644: 
1.75      anton    8645: @c anton: fold the following subsubsections into this subsection?
1.1       anton    8646: 
1.48      anton    8647: @menu
1.75      anton    8648: * Source Search Paths::         
1.48      anton    8649: * General Search Paths::        
                   8650: @end menu
                   8651: 
1.26      crook    8652: @c ---------------------------------------------------------
1.75      anton    8653: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
                   8654: @subsubsection Source Search Paths
                   8655: @cindex search path control, source files
1.5       anton    8656: 
1.26      crook    8657: The search path is initialized when you start Gforth (@pxref{Invoking
1.75      anton    8658: Gforth}). You can display it and change it using @code{fpath} in
                   8659: combination with the general path handling words.
1.5       anton    8660: 
1.75      anton    8661: doc-fpath
                   8662: @c the functionality of the following words is easily available through
                   8663: @c   fpath and the general path words.  The may go away.
                   8664: @c doc-.fpath
                   8665: @c doc-fpath+
                   8666: @c doc-fpath=
                   8667: @c doc-open-fpath-file
1.44      crook    8668: 
                   8669: @noindent
1.26      crook    8670: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    8671: 
1.26      crook    8672: @example
1.75      anton    8673: fpath path= /usr/lib/forth/|./
1.26      crook    8674: require timer.fs
                   8675: @end example
1.5       anton    8676: 
1.75      anton    8677: 
1.26      crook    8678: @c ---------------------------------------------------------
1.75      anton    8679: @node General Search Paths,  , Source Search Paths, Search Paths
1.26      crook    8680: @subsubsection General Search Paths
1.75      anton    8681: @cindex search path control, source files
1.5       anton    8682: 
1.26      crook    8683: Your application may need to search files in several directories, like
                   8684: @code{included} does. To facilitate this, Gforth allows you to define
                   8685: and use your own search paths, by providing generic equivalents of the
                   8686: Forth search path words:
1.5       anton    8687: 
1.75      anton    8688: doc-open-path-file
                   8689: doc-path-allot
                   8690: doc-clear-path
                   8691: doc-also-path
1.26      crook    8692: doc-.path
                   8693: doc-path+
                   8694: doc-path=
1.5       anton    8695: 
1.75      anton    8696: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44      crook    8697: 
1.75      anton    8698: Here's an example of creating an empty search path:
                   8699: @c
1.26      crook    8700: @example
1.75      anton    8701: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26      crook    8702: @end example
1.5       anton    8703: 
1.26      crook    8704: @c -------------------------------------------------------------
                   8705: @node Blocks, Other I/O, Files, Words
                   8706: @section Blocks
1.28      crook    8707: @cindex I/O - blocks
                   8708: @cindex blocks
                   8709: 
                   8710: When you run Gforth on a modern desk-top computer, it runs under the
                   8711: control of an operating system which provides certain services.  One of
                   8712: these services is @var{file services}, which allows Forth source code
                   8713: and data to be stored in files and read into Gforth (@pxref{Files}).
                   8714: 
                   8715: Traditionally, Forth has been an important programming language on
                   8716: systems where it has interfaced directly to the underlying hardware with
                   8717: no intervening operating system. Forth provides a mechanism, called
1.29      crook    8718: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    8719: 
                   8720: A block is a 1024-byte data area, which can be used to hold data or
                   8721: Forth source code. No structure is imposed on the contents of the
                   8722: block. A block is identified by its number; blocks are numbered
                   8723: contiguously from 1 to an implementation-defined maximum.
                   8724: 
                   8725: A typical system that used blocks but no operating system might use a
                   8726: single floppy-disk drive for mass storage, with the disks formatted to
                   8727: provide 256-byte sectors. Blocks would be implemented by assigning the
                   8728: first four sectors of the disk to block 1, the second four sectors to
                   8729: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   8730: would not contain any file system information, just the set of blocks.
                   8731: 
1.29      crook    8732: @cindex blocks file
1.28      crook    8733: On systems that do provide file services, blocks are typically
1.29      crook    8734: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    8735: file}.  The size of the blocks file will be an exact multiple of 1024
                   8736: bytes, corresponding to the number of blocks it contains. This is the
                   8737: mechanism that Gforth uses.
                   8738: 
1.29      crook    8739: @cindex @file{blocks.fb}
1.75      anton    8740: Only one blocks file can be open at a time. If you use block words without
1.28      crook    8741: having specified a blocks file, Gforth defaults to the blocks file
                   8742: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75      anton    8743: locate a blocks file (@pxref{Source Search Paths}).
1.28      crook    8744: 
1.29      crook    8745: @cindex block buffers
1.28      crook    8746: When you read and write blocks under program control, Gforth uses a
1.29      crook    8747: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    8748: not used when you use @code{load} to interpret the contents of a block.
                   8749: 
1.75      anton    8750: The behaviour of the block buffers is analagous to that of a cache.
                   8751: Each block buffer has three states:
1.28      crook    8752: 
                   8753: @itemize @bullet
                   8754: @item
                   8755: Unassigned
                   8756: @item
                   8757: Assigned-clean
                   8758: @item
                   8759: Assigned-dirty
                   8760: @end itemize
                   8761: 
1.29      crook    8762: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    8763: block, the block (specified by its block number) must be assigned to a
                   8764: block buffer.
                   8765: 
                   8766: The assignment of a block to a block buffer is performed by @code{block}
                   8767: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   8768: contents of a block. Use @code{buffer} when you don't care about the
                   8769: existing contents of the block@footnote{The ANS Forth definition of
1.35      anton    8770: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28      crook    8771: with the particular block is already stored in a block buffer due to an
                   8772: earlier @code{block} command, @code{buffer} will return that block
                   8773: buffer and the existing contents of the block will be
                   8774: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    8775: block buffer for the block.}.
1.28      crook    8776: 
1.47      crook    8777: Once a block has been assigned to a block buffer using @code{block} or
1.75      anton    8778: @code{buffer}, that block buffer becomes the @i{current block
                   8779: buffer}. Data may only be manipulated (read or written) within the
                   8780: current block buffer.
1.47      crook    8781: 
                   8782: When the contents of the current block buffer has been modified it is
1.48      anton    8783: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75      anton    8784: either abandon the changes (by doing nothing) or mark the block as
                   8785: changed (assigned-dirty), using @code{update}. Using @code{update} does
                   8786: not change the blocks file; it simply changes a block buffer's state to
                   8787: @i{assigned-dirty}.  The block will be written implicitly when it's
                   8788: buffer is needed for another block, or explicitly by @code{flush} or
                   8789: @code{save-buffers}.
                   8790: 
                   8791: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
                   8792: blocks file on disk. Leaving Gforth with @code{bye} also performs a
                   8793: @code{flush}.
1.28      crook    8794: 
1.29      crook    8795: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    8796: algorithm to assign a block buffer to a block. That means that any
                   8797: particular block can only be assigned to one specific block buffer,
1.29      crook    8798: called (for the particular operation) the @i{victim buffer}. If the
1.47      crook    8799: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
                   8800: the new block immediately. If it is @i{assigned-dirty} its current
                   8801: contents are written back to the blocks file on disk before it is
1.28      crook    8802: allocated to the new block.
                   8803: 
                   8804: Although no structure is imposed on the contents of a block, it is
                   8805: traditional to display the contents as 16 lines each of 64 characters.  A
                   8806: block provides a single, continuous stream of input (for example, it
                   8807: acts as a single parse area) -- there are no end-of-line characters
                   8808: within a block, and no end-of-file character at the end of a
                   8809: block. There are two consequences of this:
1.26      crook    8810: 
1.28      crook    8811: @itemize @bullet
                   8812: @item
                   8813: The last character of one line wraps straight into the first character
                   8814: of the following line
                   8815: @item
                   8816: The word @code{\} -- comment to end of line -- requires special
                   8817: treatment; in the context of a block it causes all characters until the
                   8818: end of the current 64-character ``line'' to be ignored.
                   8819: @end itemize
                   8820: 
                   8821: In Gforth, when you use @code{block} with a non-existent block number,
1.45      crook    8822: the current blocks file will be extended to the appropriate size and the
1.28      crook    8823: block buffer will be initialised with spaces.
                   8824: 
1.47      crook    8825: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
                   8826: for details) but doesn't encourage the use of blocks; the mechanism is
                   8827: only provided for backward compatibility -- ANS Forth requires blocks to
                   8828: be available when files are.
1.28      crook    8829: 
                   8830: Common techniques that are used when working with blocks include:
                   8831: 
                   8832: @itemize @bullet
                   8833: @item
                   8834: A screen editor that allows you to edit blocks without leaving the Forth
                   8835: environment.
                   8836: @item
                   8837: Shadow screens; where every code block has an associated block
                   8838: containing comments (for example: code in odd block numbers, comments in
                   8839: even block numbers). Typically, the block editor provides a convenient
                   8840: mechanism to toggle between code and comments.
                   8841: @item
                   8842: Load blocks; a single block (typically block 1) contains a number of
                   8843: @code{thru} commands which @code{load} the whole of the application.
                   8844: @end itemize
1.26      crook    8845: 
1.29      crook    8846: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   8847: integrated into a Forth programming environment.
1.26      crook    8848: 
                   8849: @comment TODO what about errors on open-blocks?
1.44      crook    8850: 
1.26      crook    8851: doc-open-blocks
                   8852: doc-use
1.75      anton    8853: doc-block-offset
1.26      crook    8854: doc-get-block-fid
                   8855: doc-block-position
1.28      crook    8856: 
1.75      anton    8857: doc-list
1.28      crook    8858: doc-scr
                   8859: 
1.184     anton    8860: doc-block
1.28      crook    8861: doc-buffer
                   8862: 
1.75      anton    8863: doc-empty-buffers
                   8864: doc-empty-buffer
1.26      crook    8865: doc-update
1.28      crook    8866: doc-updated?
1.26      crook    8867: doc-save-buffers
1.75      anton    8868: doc-save-buffer
1.26      crook    8869: doc-flush
1.28      crook    8870: 
1.26      crook    8871: doc-load
                   8872: doc-thru
                   8873: doc-+load
                   8874: doc-+thru
1.45      crook    8875: doc---gforthman--->
1.26      crook    8876: doc-block-included
                   8877: 
1.44      crook    8878: 
1.26      crook    8879: @c -------------------------------------------------------------
1.126     pazsan   8880: @node Other I/O, OS command line arguments, Blocks, Words
1.26      crook    8881: @section Other I/O
1.28      crook    8882: @cindex I/O - keyboard and display
1.26      crook    8883: 
                   8884: @menu
                   8885: * Simple numeric output::       Predefined formats
                   8886: * Formatted numeric output::    Formatted (pictured) output
                   8887: * String Formats::              How Forth stores strings in memory
1.67      anton    8888: * Displaying characters and strings::  Other stuff
1.175     anton    8889: * Terminal output::             Cursor positioning etc.
1.181     anton    8890: * Single-key input::            
                   8891: * Line input and conversion::   
1.112     anton    8892: * Pipes::                       How to create your own pipes
1.149     pazsan   8893: * Xchars and Unicode::          Non-ASCII characters
1.26      crook    8894: @end menu
                   8895: 
                   8896: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   8897: @subsection Simple numeric output
1.28      crook    8898: @cindex numeric output - simple/free-format
1.5       anton    8899: 
1.26      crook    8900: The simplest output functions are those that display numbers from the
                   8901: data or floating-point stacks. Floating-point output is always displayed
                   8902: using base 10. Numbers displayed from the data stack use the value stored
                   8903: in @code{base}.
1.5       anton    8904: 
1.44      crook    8905: 
1.26      crook    8906: doc-.
                   8907: doc-dec.
                   8908: doc-hex.
                   8909: doc-u.
                   8910: doc-.r
                   8911: doc-u.r
                   8912: doc-d.
                   8913: doc-ud.
                   8914: doc-d.r
                   8915: doc-ud.r
                   8916: doc-f.
                   8917: doc-fe.
                   8918: doc-fs.
1.111     anton    8919: doc-f.rdp
1.44      crook    8920: 
1.26      crook    8921: Examples of printing the number 1234.5678E23 in the different floating-point output
                   8922: formats are shown below:
1.5       anton    8923: 
                   8924: @example
1.26      crook    8925: f. 123456779999999000000000000.
                   8926: fe. 123.456779999999E24
                   8927: fs. 1.23456779999999E26
1.5       anton    8928: @end example
                   8929: 
                   8930: 
1.26      crook    8931: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   8932: @subsection Formatted numeric output
1.28      crook    8933: @cindex formatted numeric output
1.26      crook    8934: @cindex pictured numeric output
1.28      crook    8935: @cindex numeric output - formatted
1.26      crook    8936: 
1.29      crook    8937: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    8938: output} for formatted printing of integers.  In this technique, digits
                   8939: are extracted from the number (using the current output radix defined by
                   8940: @code{base}), converted to ASCII codes and appended to a string that is
                   8941: built in a scratch-pad area of memory (@pxref{core-idef,
                   8942: Implementation-defined options, Implementation-defined
                   8943: options}). Arbitrary characters can be appended to the string during the
                   8944: extraction process. The completed string is specified by an address
                   8945: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   8946: under program control.
1.5       anton    8947: 
1.75      anton    8948: All of the integer output words described in the previous section
                   8949: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
                   8950: numeric output.
1.5       anton    8951: 
1.47      crook    8952: Three important things to remember about pictured numeric output:
1.5       anton    8953: 
1.26      crook    8954: @itemize @bullet
                   8955: @item
1.28      crook    8956: It always operates on double-precision numbers; to display a
1.49      anton    8957: single-precision number, convert it first (for ways of doing this
                   8958: @pxref{Double precision}).
1.26      crook    8959: @item
1.28      crook    8960: It always treats the double-precision number as though it were
                   8961: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    8962: @item
                   8963: The string is built up from right to left; least significant digit first.
                   8964: @end itemize
1.5       anton    8965: 
1.44      crook    8966: 
1.26      crook    8967: doc-<#
1.47      crook    8968: doc-<<#
1.26      crook    8969: doc-#
                   8970: doc-#s
                   8971: doc-hold
                   8972: doc-sign
                   8973: doc-#>
1.47      crook    8974: doc-#>>
1.5       anton    8975: 
1.26      crook    8976: doc-represent
1.111     anton    8977: doc-f>str-rdp
                   8978: doc-f>buf-rdp
1.5       anton    8979: 
1.44      crook    8980: 
                   8981: @noindent
1.26      crook    8982: Here are some examples of using pictured numeric output:
1.5       anton    8983: 
                   8984: @example
1.26      crook    8985: : my-u. ( u -- )
                   8986:   \ Simplest use of pns.. behaves like Standard u. 
                   8987:   0              \ convert to unsigned double
1.75      anton    8988:   <<#            \ start conversion
1.26      crook    8989:   #s             \ convert all digits
                   8990:   #>             \ complete conversion
1.75      anton    8991:   TYPE SPACE     \ display, with trailing space
                   8992:   #>> ;          \ release hold area
1.5       anton    8993: 
1.26      crook    8994: : cents-only ( u -- )
                   8995:   0              \ convert to unsigned double
1.75      anton    8996:   <<#            \ start conversion
1.26      crook    8997:   # #            \ convert two least-significant digits
                   8998:   #>             \ complete conversion, discard other digits
1.75      anton    8999:   TYPE SPACE     \ display, with trailing space
                   9000:   #>> ;          \ release hold area
1.5       anton    9001: 
1.26      crook    9002: : dollars-and-cents ( u -- )
                   9003:   0              \ convert to unsigned double
1.75      anton    9004:   <<#            \ start conversion
1.26      crook    9005:   # #            \ convert two least-significant digits
                   9006:   [char] . hold  \ insert decimal point
                   9007:   #s             \ convert remaining digits
                   9008:   [char] $ hold  \ append currency symbol
                   9009:   #>             \ complete conversion
1.75      anton    9010:   TYPE SPACE     \ display, with trailing space
                   9011:   #>> ;          \ release hold area
1.5       anton    9012: 
1.26      crook    9013: : my-. ( n -- )
                   9014:   \ handling negatives.. behaves like Standard .
                   9015:   s>d            \ convert to signed double
                   9016:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    9017:   <<#            \ start conversion
1.26      crook    9018:   #s             \ convert all digits
                   9019:   rot sign       \ get at sign byte, append "-" if needed
                   9020:   #>             \ complete conversion
1.75      anton    9021:   TYPE SPACE     \ display, with trailing space
                   9022:   #>> ;          \ release hold area
1.5       anton    9023: 
1.26      crook    9024: : account. ( n -- )
1.75      anton    9025:   \ accountants don't like minus signs, they use parentheses
1.26      crook    9026:   \ for negative numbers
                   9027:   s>d            \ convert to signed double
                   9028:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    9029:   <<#            \ start conversion
1.26      crook    9030:   2 pick         \ get copy of sign byte
                   9031:   0< IF [char] ) hold THEN \ right-most character of output
                   9032:   #s             \ convert all digits
                   9033:   rot            \ get at sign byte
                   9034:   0< IF [char] ( hold THEN
                   9035:   #>             \ complete conversion
1.75      anton    9036:   TYPE SPACE     \ display, with trailing space
                   9037:   #>> ;          \ release hold area
                   9038: 
1.5       anton    9039: @end example
                   9040: 
1.26      crook    9041: Here are some examples of using these words:
1.5       anton    9042: 
                   9043: @example
1.26      crook    9044: 1 my-u. 1
                   9045: hex -1 my-u. decimal FFFFFFFF
                   9046: 1 cents-only 01
                   9047: 1234 cents-only 34
                   9048: 2 dollars-and-cents $0.02
                   9049: 1234 dollars-and-cents $12.34
                   9050: 123 my-. 123
                   9051: -123 my. -123
                   9052: 123 account. 123
                   9053: -456 account. (456)
1.5       anton    9054: @end example
                   9055: 
                   9056: 
1.26      crook    9057: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   9058: @subsection String Formats
1.27      crook    9059: @cindex strings - see character strings
                   9060: @cindex character strings - formats
1.28      crook    9061: @cindex I/O - see character strings
1.75      anton    9062: @cindex counted strings
                   9063: 
                   9064: @c anton: this does not really belong here; maybe the memory section,
                   9065: @c  or the principles chapter
1.26      crook    9066: 
1.27      crook    9067: Forth commonly uses two different methods for representing character
                   9068: strings:
1.26      crook    9069: 
                   9070: @itemize @bullet
                   9071: @item
                   9072: @cindex address of counted string
1.45      crook    9073: @cindex counted string
1.29      crook    9074: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   9075: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   9076: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    9077: memory.
                   9078: @item
1.29      crook    9079: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   9080: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    9081: first byte of the string.
                   9082: @end itemize
                   9083: 
                   9084: ANS Forth encourages the use of the second format when representing
1.75      anton    9085: strings.
1.26      crook    9086: 
1.44      crook    9087: 
1.26      crook    9088: doc-count
                   9089: 
1.44      crook    9090: 
1.49      anton    9091: For words that move, copy and search for strings see @ref{Memory
                   9092: Blocks}. For words that display characters and strings see
                   9093: @ref{Displaying characters and strings}.
1.26      crook    9094: 
1.175     anton    9095: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
1.26      crook    9096: @subsection Displaying characters and strings
1.27      crook    9097: @cindex characters - compiling and displaying
                   9098: @cindex character strings - compiling and displaying
1.26      crook    9099: 
                   9100: This section starts with a glossary of Forth words and ends with a set
                   9101: of examples.
                   9102: 
                   9103: doc-bl
                   9104: doc-space
                   9105: doc-spaces
                   9106: doc-emit
                   9107: doc-toupper
                   9108: doc-."
                   9109: doc-.(
1.98      anton    9110: doc-.\"
1.26      crook    9111: doc-type
1.44      crook    9112: doc-typewhite
1.26      crook    9113: doc-cr
1.27      crook    9114: @cindex cursor control
1.26      crook    9115: doc-s"
1.98      anton    9116: doc-s\"
1.26      crook    9117: doc-c"
                   9118: doc-char
                   9119: doc-[char]
                   9120: 
1.44      crook    9121: 
                   9122: @noindent
1.26      crook    9123: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    9124: 
                   9125: @example
1.26      crook    9126: .( text-1)
                   9127: : my-word
                   9128:   ." text-2" cr
                   9129:   .( text-3)
                   9130: ;
                   9131: 
                   9132: ." text-4"
                   9133: 
                   9134: : my-char
                   9135:   [char] ALPHABET emit
                   9136:   char emit
                   9137: ;
1.5       anton    9138: @end example
                   9139: 
1.26      crook    9140: When you load this code into Gforth, the following output is generated:
1.5       anton    9141: 
1.26      crook    9142: @example
1.30      anton    9143: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    9144: @end example
1.5       anton    9145: 
1.26      crook    9146: @itemize @bullet
                   9147: @item
                   9148: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   9149: is an immediate word; it behaves in the same way whether it is used inside
                   9150: or outside a colon definition.
                   9151: @item
                   9152: Message @code{text-4} is displayed because of Gforth's added interpretation
                   9153: semantics for @code{."}.
                   9154: @item
1.29      crook    9155: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    9156: performs the compilation semantics for @code{."} within the definition of
                   9157: @code{my-word}.
                   9158: @end itemize
1.5       anton    9159: 
1.26      crook    9160: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    9161: 
1.26      crook    9162: @example
1.30      anton    9163: @kbd{my-word @key{RET}} text-2
1.26      crook    9164:  ok
1.30      anton    9165: @kbd{my-char fred @key{RET}} Af ok
                   9166: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    9167: @end example
1.5       anton    9168: 
                   9169: @itemize @bullet
                   9170: @item
1.26      crook    9171: Message @code{text-2} is displayed because of the run-time behaviour of
                   9172: @code{."}.
                   9173: @item
                   9174: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   9175: on the stack at run-time. @code{emit} always displays the character
                   9176: when @code{my-char} is executed.
                   9177: @item
                   9178: @code{char} parses a string at run-time and the second @code{emit} displays
                   9179: the first character of the string.
1.5       anton    9180: @item
1.26      crook    9181: If you type @code{see my-char} you can see that @code{[char]} discarded
                   9182: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   9183: definition of @code{my-char}.
1.5       anton    9184: @end itemize
                   9185: 
                   9186: 
1.181     anton    9187: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
1.175     anton    9188: @subsection Terminal output
                   9189: @cindex output to terminal
                   9190: @cindex terminal output
                   9191: 
                   9192: If you are outputting to a terminal, you may want to control the
                   9193: positioning of the cursor:
                   9194: @cindex cursor positioning
                   9195: 
                   9196: doc-at-xy
                   9197: 
                   9198: In order to know where to position the cursor, it is often helpful to
                   9199: know the size of the screen:
                   9200: @cindex terminal size 
                   9201: 
                   9202: doc-form
                   9203: 
                   9204: And sometimes you want to use:
                   9205: @cindex clear screen
                   9206: 
                   9207: doc-page
                   9208: 
                   9209: Note that on non-terminals you should use @code{12 emit}, not
                   9210: @code{page}, to get a form feed.
                   9211: 
1.5       anton    9212: 
1.181     anton    9213: @node Single-key input, Line input and conversion, Terminal output, Other I/O
                   9214: @subsection Single-key input
                   9215: @cindex single-key input
                   9216: @cindex input, single-key
                   9217: 
                   9218: If you want to get a single printable character, you can use
                   9219: @code{key}; to check whether a character is available for @code{key},
                   9220: you can use @code{key?}.
1.5       anton    9221: 
1.181     anton    9222: doc-key
                   9223: doc-key?
1.27      crook    9224: 
1.181     anton    9225: If you want to process a mix of printable and non-printable
                   9226: characters, you can do that with @code{ekey} and friends.  @code{Ekey}
                   9227: produces a keyboard event that you have to convert into a character
                   9228: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
                   9229: 
                   9230: Typical code for using EKEY looks like this:
                   9231: 
                   9232: @example
                   9233: ekey ekey>char if ( c )
                   9234:   ... \ do something with the character
                   9235: else ekey>fkey if ( key-id )
                   9236:   case
                   9237:     k-up                                  of ... endof
                   9238:     k-f1                                  of ... endof
                   9239:     k-left k-shift-mask or k-ctrl-mask or of ... endof
                   9240:     ...
                   9241:   endcase
                   9242: else ( keyboard-event )
                   9243:   drop \ just ignore an unknown keyboard event type
                   9244: then then
                   9245: @end example
1.44      crook    9246: 
1.45      crook    9247: doc-ekey
1.141     anton    9248: doc-ekey>char
1.181     anton    9249: doc-ekey>fkey
1.45      crook    9250: doc-ekey?
1.141     anton    9251: 
1.181     anton    9252: The key identifiers for cursor keys are:
1.141     anton    9253: 
                   9254: doc-k-left
                   9255: doc-k-right
1.185     anton    9256: doc-k-up
                   9257: doc-k-down
                   9258: doc-k-home
                   9259: doc-k-end
1.141     anton    9260: doc-k-prior
                   9261: doc-k-next
                   9262: doc-k-insert
                   9263: doc-k-delete
                   9264: 
1.181     anton    9265: The key identifiers for function keys (aka keypad keys) are:
1.141     anton    9266: 
1.181     anton    9267: doc-k-f1
                   9268: doc-k-f2
                   9269: doc-k-f3
                   9270: doc-k-f4
                   9271: doc-k-f5
                   9272: doc-k-f6
                   9273: doc-k-f7
                   9274: doc-k-f8
                   9275: doc-k-f9
                   9276: doc-k-f10
                   9277: doc-k-f11
                   9278: doc-k-f12
                   9279: 
                   9280: Note that @code{k-f11} and @code{k-f12} are not as widely available.
                   9281: 
                   9282: You can combine these key identifiers with masks for various shift keys:
                   9283: 
                   9284: doc-k-shift-mask
                   9285: doc-k-ctrl-mask
                   9286: doc-k-alt-mask
                   9287: 
                   9288: Note that, even if a Forth system has @code{ekey>fkey} and the key
                   9289: identifier words, the keys are not necessarily available or it may not
                   9290: necessarily be able to report all the keys and all the possible
                   9291: combinations with shift masks.  Therefore, write your programs in such
                   9292: a way that they are still useful even if the keys and key combinations
                   9293: cannot be pressed or are not recognized.
                   9294: 
                   9295: Examples: Older keyboards often do not have an F11 and F12 key.  If
                   9296: you run Gforth in an xterm, the xterm catches a number of combinations
                   9297: (e.g., @key{Shift-Up}), and never passes it to Gforth.  Finally,
                   9298: Gforth currently does not recognize and report combinations with
                   9299: multiple shift keys (so the @key{shift-ctrl-left} case in the example
                   9300: above would never be entered).
                   9301: 
                   9302: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
                   9303: you need the ANSI.SYS driver to get that behaviour); it works by
                   9304: recognizing the escape sequences that ANSI terminals send when such a
                   9305: key is pressed.  If you have a terminal that sends other escape
                   9306: sequences, you will not get useful results on Gforth.  Other Forth
                   9307: systems may work in a different way.
                   9308: 
1.200     anton    9309: Gforth also provides a few words for outputting names of function
                   9310: keys:
                   9311: 
                   9312: doc-fkey.
                   9313: doc-simple-fkey-string
                   9314: 
1.181     anton    9315: 
                   9316: @node  Line input and conversion, Pipes, Single-key input, Other I/O
                   9317: @subsection Line input and conversion
                   9318: @cindex line input from terminal
                   9319: @cindex input, linewise from terminal
                   9320: @cindex convertin strings to numbers
                   9321: @cindex I/O - see input
                   9322: 
                   9323: For ways of storing character strings in memory see @ref{String Formats}.
                   9324: 
                   9325: @comment TODO examples for >number >float accept key key? pad parse word refill
                   9326: @comment then index them
1.141     anton    9327: 
                   9328: Words for inputting one line from the keyboard:
                   9329: 
                   9330: doc-accept
                   9331: doc-edit-line
                   9332: 
                   9333: Conversion words:
                   9334: 
1.143     anton    9335: doc-s>number?
                   9336: doc-s>unumber?
1.26      crook    9337: doc->number
                   9338: doc->float
1.143     anton    9339: 
1.141     anton    9340: 
1.27      crook    9341: @comment obsolescent words..
1.141     anton    9342: Obsolescent input and conversion words:
                   9343: 
1.27      crook    9344: doc-convert
1.26      crook    9345: doc-expect
1.27      crook    9346: doc-span
1.5       anton    9347: 
                   9348: 
1.181     anton    9349: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
1.112     anton    9350: @subsection Pipes
                   9351: @cindex pipes, creating your own
                   9352: 
                   9353: In addition to using Gforth in pipes created by other processes
                   9354: (@pxref{Gforth in pipes}), you can create your own pipe with
                   9355: @code{open-pipe}, and read from or write to it.
                   9356: 
                   9357: doc-open-pipe
                   9358: doc-close-pipe
                   9359: 
                   9360: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
                   9361: you don't catch this exception, Gforth will catch it and exit, usually
                   9362: silently (@pxref{Gforth in pipes}).  Since you probably do not want
                   9363: this, you should wrap a @code{catch} or @code{try} block around the code
                   9364: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
                   9365: problem yourself, and then return to regular processing.
                   9366: 
                   9367: doc-broken-pipe-error
                   9368: 
1.155     anton    9369: @node Xchars and Unicode,  , Pipes, Other I/O
                   9370: @subsection Xchars and Unicode
1.149     pazsan   9371: 
1.188     pazsan   9372: ASCII is only appropriate for the English language. Most western
                   9373: languages however fit somewhat into the Forth frame, since a byte is
                   9374: sufficient to encode the few special characters in each (though not
                   9375: always the same encoding can be used; latin-1 is most widely used,
                   9376: though). For other languages, different char-sets have to be used,
                   9377: several of them variable-width. Most prominent representant is
                   9378: UTF-8. Let's call these extended characters xchars. The primitive
                   9379: fixed-size characters stored as bytes are called pchars in this
                   9380: section.
                   9381: 
                   9382: The xchar words add a few data types:
                   9383: 
                   9384: @itemize
                   9385: 
                   9386: @item
                   9387: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
                   9388: and is a subset of unsigned cell. Note: UTF-8 can not store more that
                   9389: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
                   9390: character set can be used.
                   9391: 
                   9392: @item
                   9393: @var{xc-addr} is the address of an xchar in memory. Alignment
                   9394: requirements are the same as @var{c-addr}. The memory representation of an
                   9395: xchar differs from the stack representation, and depends on the
                   9396: encoding used. An xchar may use a variable number of pchars in memory.
                   9397: 
                   9398: @item
                   9399: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
                   9400: @var{xc-addr}, @var{u} pchars long.
                   9401: 
                   9402: @end itemize
                   9403: 
                   9404: doc-xc-size
                   9405: doc-x-size
                   9406: doc-xc@+
                   9407: doc-xc!+?
                   9408: doc-xchar+
                   9409: doc-xchar-
                   9410: doc-+x/string
                   9411: doc-x\string-
                   9412: doc--trailing-garbage
                   9413: doc-x-width
                   9414: doc-xkey
                   9415: doc-xemit
                   9416: 
                   9417: There's a new environment query
                   9418: 
                   9419: doc-xchar-encoding
1.112     anton    9420: 
1.121     anton    9421: @node OS command line arguments, Locals, Other I/O, Words
                   9422: @section OS command line arguments
                   9423: @cindex OS command line arguments
                   9424: @cindex command line arguments, OS
                   9425: @cindex arguments, OS command line
                   9426: 
                   9427: The usual way to pass arguments to Gforth programs on the command line
                   9428: is via the @option{-e} option, e.g.
                   9429: 
                   9430: @example
                   9431: gforth -e "123 456" foo.fs -e bye
                   9432: @end example
                   9433: 
                   9434: However, you may want to interpret the command-line arguments directly.
                   9435: In that case, you can access the (image-specific) command-line arguments
1.123     anton    9436: through @code{next-arg}:
1.121     anton    9437: 
1.123     anton    9438: doc-next-arg
1.121     anton    9439: 
1.123     anton    9440: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121     anton    9441: 
                   9442: @example
                   9443: : echo ( -- )
1.122     anton    9444:     begin
1.123     anton    9445:        next-arg 2dup 0 0 d<> while
                   9446:            type space
                   9447:     repeat
                   9448:     2drop ;
1.121     anton    9449: 
                   9450: echo cr bye
                   9451: @end example
                   9452: 
                   9453: This can be invoked with
                   9454: 
                   9455: @example
                   9456: gforth echo.fs hello world
                   9457: @end example
1.123     anton    9458: 
                   9459: and it will print
                   9460: 
                   9461: @example
                   9462: hello world
                   9463: @end example
                   9464: 
                   9465: The next lower level of dealing with the OS command line are the
                   9466: following words:
                   9467: 
                   9468: doc-arg
                   9469: doc-shift-args
                   9470: 
                   9471: Finally, at the lowest level Gforth provides the following words:
                   9472: 
                   9473: doc-argc
                   9474: doc-argv
1.121     anton    9475: 
1.78      anton    9476: @c -------------------------------------------------------------
1.126     pazsan   9477: @node Locals, Structures, OS command line arguments, Words
1.78      anton    9478: @section Locals
                   9479: @cindex locals
                   9480: 
                   9481: Local variables can make Forth programming more enjoyable and Forth
                   9482: programs easier to read. Unfortunately, the locals of ANS Forth are
                   9483: laden with restrictions. Therefore, we provide not only the ANS Forth
                   9484: locals wordset, but also our own, more powerful locals wordset (we
                   9485: implemented the ANS Forth locals wordset through our locals wordset).
1.44      crook    9486: 
1.78      anton    9487: The ideas in this section have also been published in M. Anton Ertl,
                   9488: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
                   9489: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12      anton    9490: 
                   9491: @menu
1.78      anton    9492: * Gforth locals::               
                   9493: * ANS Forth locals::            
1.5       anton    9494: @end menu
                   9495: 
1.78      anton    9496: @node Gforth locals, ANS Forth locals, Locals, Locals
                   9497: @subsection Gforth locals
                   9498: @cindex Gforth locals
                   9499: @cindex locals, Gforth style
1.5       anton    9500: 
1.78      anton    9501: Locals can be defined with
1.44      crook    9502: 
1.78      anton    9503: @example
                   9504: @{ local1 local2 ... -- comment @}
                   9505: @end example
                   9506: or
                   9507: @example
                   9508: @{ local1 local2 ... @}
                   9509: @end example
1.5       anton    9510: 
1.78      anton    9511: E.g.,
                   9512: @example
                   9513: : max @{ n1 n2 -- n3 @}
                   9514:  n1 n2 > if
                   9515:    n1
                   9516:  else
                   9517:    n2
                   9518:  endif ;
                   9519: @end example
1.44      crook    9520: 
1.78      anton    9521: The similarity of locals definitions with stack comments is intended. A
                   9522: locals definition often replaces the stack comment of a word. The order
                   9523: of the locals corresponds to the order in a stack comment and everything
                   9524: after the @code{--} is really a comment.
1.77      anton    9525: 
1.78      anton    9526: This similarity has one disadvantage: It is too easy to confuse locals
                   9527: declarations with stack comments, causing bugs and making them hard to
                   9528: find. However, this problem can be avoided by appropriate coding
                   9529: conventions: Do not use both notations in the same program. If you do,
                   9530: they should be distinguished using additional means, e.g. by position.
1.77      anton    9531: 
1.78      anton    9532: @cindex types of locals
                   9533: @cindex locals types
                   9534: The name of the local may be preceded by a type specifier, e.g.,
                   9535: @code{F:} for a floating point value:
1.5       anton    9536: 
1.78      anton    9537: @example
                   9538: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   9539: \ complex multiplication
                   9540:  Ar Br f* Ai Bi f* f-
                   9541:  Ar Bi f* Ai Br f* f+ ;
                   9542: @end example
1.44      crook    9543: 
1.78      anton    9544: @cindex flavours of locals
                   9545: @cindex locals flavours
                   9546: @cindex value-flavoured locals
                   9547: @cindex variable-flavoured locals
                   9548: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   9549: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   9550: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   9551: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   9552: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   9553: produces its address (which becomes invalid when the variable's scope is
                   9554: left). E.g., the standard word @code{emit} can be defined in terms of
                   9555: @code{type} like this:
1.5       anton    9556: 
1.78      anton    9557: @example
                   9558: : emit @{ C^ char* -- @}
                   9559:     char* 1 type ;
                   9560: @end example
1.5       anton    9561: 
1.78      anton    9562: @cindex default type of locals
                   9563: @cindex locals, default type
                   9564: A local without type specifier is a @code{W:} local. Both flavours of
                   9565: locals are initialized with values from the data or FP stack.
1.44      crook    9566: 
1.78      anton    9567: Currently there is no way to define locals with user-defined data
                   9568: structures, but we are working on it.
1.5       anton    9569: 
1.78      anton    9570: Gforth allows defining locals everywhere in a colon definition. This
                   9571: poses the following questions:
1.5       anton    9572: 
1.78      anton    9573: @menu
                   9574: * Where are locals visible by name?::  
                   9575: * How long do locals live?::    
                   9576: * Locals programming style::    
                   9577: * Locals implementation::       
                   9578: @end menu
1.44      crook    9579: 
1.78      anton    9580: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   9581: @subsubsection Where are locals visible by name?
                   9582: @cindex locals visibility
                   9583: @cindex visibility of locals
                   9584: @cindex scope of locals
1.5       anton    9585: 
1.78      anton    9586: Basically, the answer is that locals are visible where you would expect
                   9587: it in block-structured languages, and sometimes a little longer. If you
                   9588: want to restrict the scope of a local, enclose its definition in
                   9589: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    9590: 
                   9591: 
1.78      anton    9592: doc-scope
                   9593: doc-endscope
1.5       anton    9594: 
                   9595: 
1.78      anton    9596: These words behave like control structure words, so you can use them
                   9597: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   9598: arbitrary ways.
1.77      anton    9599: 
1.78      anton    9600: If you want a more exact answer to the visibility question, here's the
                   9601: basic principle: A local is visible in all places that can only be
                   9602: reached through the definition of the local@footnote{In compiler
                   9603: construction terminology, all places dominated by the definition of the
                   9604: local.}. In other words, it is not visible in places that can be reached
                   9605: without going through the definition of the local. E.g., locals defined
                   9606: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   9607: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   9608: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77      anton    9609: 
1.78      anton    9610: The reasoning behind this solution is: We want to have the locals
                   9611: visible as long as it is meaningful. The user can always make the
                   9612: visibility shorter by using explicit scoping. In a place that can
                   9613: only be reached through the definition of a local, the meaning of a
                   9614: local name is clear. In other places it is not: How is the local
                   9615: initialized at the control flow path that does not contain the
                   9616: definition? Which local is meant, if the same name is defined twice in
                   9617: two independent control flow paths?
1.77      anton    9618: 
1.78      anton    9619: This should be enough detail for nearly all users, so you can skip the
                   9620: rest of this section. If you really must know all the gory details and
                   9621: options, read on.
1.77      anton    9622: 
1.78      anton    9623: In order to implement this rule, the compiler has to know which places
                   9624: are unreachable. It knows this automatically after @code{AHEAD},
                   9625: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   9626: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   9627: compiler that the control flow never reaches that place. If
                   9628: @code{UNREACHABLE} is not used where it could, the only consequence is
                   9629: that the visibility of some locals is more limited than the rule above
                   9630: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   9631: lie to the compiler), buggy code will be produced.
1.77      anton    9632: 
1.5       anton    9633: 
1.78      anton    9634: doc-unreachable
1.5       anton    9635: 
1.23      crook    9636: 
1.78      anton    9637: Another problem with this rule is that at @code{BEGIN}, the compiler
                   9638: does not know which locals will be visible on the incoming
                   9639: back-edge. All problems discussed in the following are due to this
                   9640: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   9641: loops as examples; the discussion also applies to @code{?DO} and other
                   9642: loops). Perhaps the most insidious example is:
1.26      crook    9643: @example
1.78      anton    9644: AHEAD
                   9645: BEGIN
                   9646:   x
                   9647: [ 1 CS-ROLL ] THEN
                   9648:   @{ x @}
                   9649:   ...
                   9650: UNTIL
1.26      crook    9651: @end example
1.23      crook    9652: 
1.78      anton    9653: This should be legal according to the visibility rule. The use of
                   9654: @code{x} can only be reached through the definition; but that appears
                   9655: textually below the use.
                   9656: 
                   9657: From this example it is clear that the visibility rules cannot be fully
                   9658: implemented without major headaches. Our implementation treats common
                   9659: cases as advertised and the exceptions are treated in a safe way: The
                   9660: compiler makes a reasonable guess about the locals visible after a
                   9661: @code{BEGIN}; if it is too pessimistic, the
                   9662: user will get a spurious error about the local not being defined; if the
                   9663: compiler is too optimistic, it will notice this later and issue a
                   9664: warning. In the case above the compiler would complain about @code{x}
                   9665: being undefined at its use. You can see from the obscure examples in
                   9666: this section that it takes quite unusual control structures to get the
                   9667: compiler into trouble, and even then it will often do fine.
1.23      crook    9668: 
1.78      anton    9669: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   9670: is that all locals visible before the @code{BEGIN} will also be
                   9671: visible after the @code{BEGIN}. This guess is valid for all loops that
                   9672: are entered only through the @code{BEGIN}, in particular, for normal
                   9673: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   9674: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   9675: compiler. When the branch to the @code{BEGIN} is finally generated by
                   9676: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   9677: warns the user if it was too optimistic:
1.26      crook    9678: @example
1.78      anton    9679: IF
                   9680:   @{ x @}
                   9681: BEGIN
                   9682:   \ x ? 
                   9683: [ 1 cs-roll ] THEN
                   9684:   ...
                   9685: UNTIL
1.26      crook    9686: @end example
1.23      crook    9687: 
1.78      anton    9688: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   9689: optimistically assumes that it lives until the @code{THEN}. It notices
                   9690: this difference when it compiles the @code{UNTIL} and issues a
                   9691: warning. The user can avoid the warning, and make sure that @code{x}
                   9692: is not used in the wrong area by using explicit scoping:
                   9693: @example
                   9694: IF
                   9695:   SCOPE
                   9696:   @{ x @}
                   9697:   ENDSCOPE
                   9698: BEGIN
                   9699: [ 1 cs-roll ] THEN
                   9700:   ...
                   9701: UNTIL
                   9702: @end example
1.23      crook    9703: 
1.78      anton    9704: Since the guess is optimistic, there will be no spurious error messages
                   9705: about undefined locals.
1.44      crook    9706: 
1.78      anton    9707: If the @code{BEGIN} is not reachable from above (e.g., after
                   9708: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   9709: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   9710: defined later. Therefore, the compiler assumes that no locals are
                   9711: visible after the @code{BEGIN}. However, the user can use
                   9712: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   9713: visible at the BEGIN as at the point where the top control-flow stack
                   9714: item was created.
1.23      crook    9715: 
1.44      crook    9716: 
1.78      anton    9717: doc-assume-live
1.26      crook    9718: 
1.23      crook    9719: 
1.78      anton    9720: @noindent
                   9721: E.g.,
                   9722: @example
                   9723: @{ x @}
                   9724: AHEAD
                   9725: ASSUME-LIVE
                   9726: BEGIN
                   9727:   x
                   9728: [ 1 CS-ROLL ] THEN
                   9729:   ...
                   9730: UNTIL
                   9731: @end example
1.44      crook    9732: 
1.78      anton    9733: Other cases where the locals are defined before the @code{BEGIN} can be
                   9734: handled by inserting an appropriate @code{CS-ROLL} before the
                   9735: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   9736: behind the @code{ASSUME-LIVE}).
1.23      crook    9737: 
1.78      anton    9738: Cases where locals are defined after the @code{BEGIN} (but should be
                   9739: visible immediately after the @code{BEGIN}) can only be handled by
                   9740: rearranging the loop. E.g., the ``most insidious'' example above can be
                   9741: arranged into:
                   9742: @example
                   9743: BEGIN
                   9744:   @{ x @}
                   9745:   ... 0=
                   9746: WHILE
                   9747:   x
                   9748: REPEAT
                   9749: @end example
1.44      crook    9750: 
1.78      anton    9751: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
                   9752: @subsubsection How long do locals live?
                   9753: @cindex locals lifetime
                   9754: @cindex lifetime of locals
1.23      crook    9755: 
1.78      anton    9756: The right answer for the lifetime question would be: A local lives at
                   9757: least as long as it can be accessed. For a value-flavoured local this
                   9758: means: until the end of its visibility. However, a variable-flavoured
                   9759: local could be accessed through its address far beyond its visibility
                   9760: scope. Ultimately, this would mean that such locals would have to be
                   9761: garbage collected. Since this entails un-Forth-like implementation
                   9762: complexities, I adopted the same cowardly solution as some other
                   9763: languages (e.g., C): The local lives only as long as it is visible;
                   9764: afterwards its address is invalid (and programs that access it
                   9765: afterwards are erroneous).
1.23      crook    9766: 
1.78      anton    9767: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
                   9768: @subsubsection Locals programming style
                   9769: @cindex locals programming style
                   9770: @cindex programming style, locals
1.23      crook    9771: 
1.78      anton    9772: The freedom to define locals anywhere has the potential to change
                   9773: programming styles dramatically. In particular, the need to use the
                   9774: return stack for intermediate storage vanishes. Moreover, all stack
                   9775: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   9776: determined arguments) can be eliminated: If the stack items are in the
                   9777: wrong order, just write a locals definition for all of them; then
                   9778: write the items in the order you want.
1.23      crook    9779: 
1.78      anton    9780: This seems a little far-fetched and eliminating stack manipulations is
                   9781: unlikely to become a conscious programming objective. Still, the number
                   9782: of stack manipulations will be reduced dramatically if local variables
                   9783: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
                   9784: a traditional implementation of @code{max}).
1.23      crook    9785: 
1.78      anton    9786: This shows one potential benefit of locals: making Forth programs more
                   9787: readable. Of course, this benefit will only be realized if the
                   9788: programmers continue to honour the principle of factoring instead of
                   9789: using the added latitude to make the words longer.
1.23      crook    9790: 
1.78      anton    9791: @cindex single-assignment style for locals
                   9792: Using @code{TO} can and should be avoided.  Without @code{TO},
                   9793: every value-flavoured local has only a single assignment and many
                   9794: advantages of functional languages apply to Forth. I.e., programs are
                   9795: easier to analyse, to optimize and to read: It is clear from the
                   9796: definition what the local stands for, it does not turn into something
                   9797: different later.
1.23      crook    9798: 
1.78      anton    9799: E.g., a definition using @code{TO} might look like this:
                   9800: @example
                   9801: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9802:  u1 u2 min 0
                   9803:  ?do
                   9804:    addr1 c@@ addr2 c@@ -
                   9805:    ?dup-if
                   9806:      unloop exit
                   9807:    then
                   9808:    addr1 char+ TO addr1
                   9809:    addr2 char+ TO addr2
                   9810:  loop
                   9811:  u1 u2 - ;
1.26      crook    9812: @end example
1.78      anton    9813: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   9814: every loop iteration. @code{strcmp} is a typical example of the
                   9815: readability problems of using @code{TO}. When you start reading
                   9816: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   9817: string. Only near the end of the loop you realize that it is something
                   9818: else.
1.23      crook    9819: 
1.78      anton    9820: This can be avoided by defining two locals at the start of the loop that
                   9821: are initialized with the right value for the current iteration.
                   9822: @example
                   9823: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9824:  addr1 addr2
                   9825:  u1 u2 min 0 
                   9826:  ?do @{ s1 s2 @}
                   9827:    s1 c@@ s2 c@@ -
                   9828:    ?dup-if
                   9829:      unloop exit
                   9830:    then
                   9831:    s1 char+ s2 char+
                   9832:  loop
                   9833:  2drop
                   9834:  u1 u2 - ;
                   9835: @end example
                   9836: Here it is clear from the start that @code{s1} has a different value
                   9837: in every loop iteration.
1.23      crook    9838: 
1.78      anton    9839: @node Locals implementation,  , Locals programming style, Gforth locals
                   9840: @subsubsection Locals implementation
                   9841: @cindex locals implementation
                   9842: @cindex implementation of locals
1.23      crook    9843: 
1.78      anton    9844: @cindex locals stack
                   9845: Gforth uses an extra locals stack. The most compelling reason for
                   9846: this is that the return stack is not float-aligned; using an extra stack
                   9847: also eliminates the problems and restrictions of using the return stack
                   9848: as locals stack. Like the other stacks, the locals stack grows toward
                   9849: lower addresses. A few primitives allow an efficient implementation:
                   9850: 
                   9851: 
                   9852: doc-@local#
                   9853: doc-f@local#
                   9854: doc-laddr#
                   9855: doc-lp+!#
                   9856: doc-lp!
                   9857: doc->l
                   9858: doc-f>l
                   9859: 
                   9860: 
                   9861: In addition to these primitives, some specializations of these
                   9862: primitives for commonly occurring inline arguments are provided for
                   9863: efficiency reasons, e.g., @code{@@local0} as specialization of
                   9864: @code{@@local#} for the inline argument 0. The following compiling words
                   9865: compile the right specialized version, or the general version, as
                   9866: appropriate:
1.23      crook    9867: 
1.5       anton    9868: 
1.107     dvdkhlng 9869: @c doc-compile-@local
                   9870: @c doc-compile-f@local
1.78      anton    9871: doc-compile-lp+!
1.5       anton    9872: 
                   9873: 
1.78      anton    9874: Combinations of conditional branches and @code{lp+!#} like
                   9875: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   9876: is taken) are provided for efficiency and correctness in loops.
1.5       anton    9877: 
1.78      anton    9878: A special area in the dictionary space is reserved for keeping the
                   9879: local variable names. @code{@{} switches the dictionary pointer to this
                   9880: area and @code{@}} switches it back and generates the locals
                   9881: initializing code. @code{W:} etc.@ are normal defining words. This
                   9882: special area is cleared at the start of every colon definition.
1.5       anton    9883: 
1.78      anton    9884: @cindex word list for defining locals
                   9885: A special feature of Gforth's dictionary is used to implement the
                   9886: definition of locals without type specifiers: every word list (aka
                   9887: vocabulary) has its own methods for searching
                   9888: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   9889: with a special search method: When it is searched for a word, it
                   9890: actually creates that word using @code{W:}. @code{@{} changes the search
                   9891: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   9892: and then the word list for defining locals without type specifiers.
1.5       anton    9893: 
1.78      anton    9894: The lifetime rules support a stack discipline within a colon
                   9895: definition: The lifetime of a local is either nested with other locals
                   9896: lifetimes or it does not overlap them.
1.23      crook    9897: 
1.78      anton    9898: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   9899: pointer manipulation is generated. Between control structure words
                   9900: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   9901: is the simplest of the other three control flow words. It has to
                   9902: restore the locals stack depth of the corresponding @code{BEGIN}
                   9903: before branching. The code looks like this:
                   9904: @format
                   9905: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   9906: @code{branch} <begin>
                   9907: @end format
1.26      crook    9908: 
1.78      anton    9909: @code{UNTIL} is a little more complicated: If it branches back, it
                   9910: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   9911: the locals stack must not be changed. The compiler generates the
                   9912: following code:
                   9913: @format
                   9914: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   9915: @end format
                   9916: The locals stack pointer is only adjusted if the branch is taken.
1.44      crook    9917: 
1.78      anton    9918: @code{THEN} can produce somewhat inefficient code:
                   9919: @format
                   9920: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   9921: <orig target>:
                   9922: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   9923: @end format
                   9924: The second @code{lp+!#} adjusts the locals stack pointer from the
                   9925: level at the @i{orig} point to the level after the @code{THEN}. The
                   9926: first @code{lp+!#} adjusts the locals stack pointer from the current
                   9927: level to the level at the orig point, so the complete effect is an
                   9928: adjustment from the current level to the right level after the
                   9929: @code{THEN}.
1.26      crook    9930: 
1.78      anton    9931: @cindex locals information on the control-flow stack
                   9932: @cindex control-flow stack items, locals information
                   9933: In a conventional Forth implementation a dest control-flow stack entry
                   9934: is just the target address and an orig entry is just the address to be
                   9935: patched. Our locals implementation adds a word list to every orig or dest
                   9936: item. It is the list of locals visible (or assumed visible) at the point
                   9937: described by the entry. Our implementation also adds a tag to identify
                   9938: the kind of entry, in particular to differentiate between live and dead
                   9939: (reachable and unreachable) orig entries.
1.26      crook    9940: 
1.78      anton    9941: A few unusual operations have to be performed on locals word lists:
1.44      crook    9942: 
1.5       anton    9943: 
1.78      anton    9944: doc-common-list
                   9945: doc-sub-list?
                   9946: doc-list-size
1.52      anton    9947: 
                   9948: 
1.78      anton    9949: Several features of our locals word list implementation make these
                   9950: operations easy to implement: The locals word lists are organised as
                   9951: linked lists; the tails of these lists are shared, if the lists
                   9952: contain some of the same locals; and the address of a name is greater
                   9953: than the address of the names behind it in the list.
1.5       anton    9954: 
1.78      anton    9955: Another important implementation detail is the variable
                   9956: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   9957: determine if they can be reached directly or only through the branch
                   9958: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   9959: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   9960: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5       anton    9961: 
1.78      anton    9962: Counted loops are similar to other loops in most respects, but
                   9963: @code{LEAVE} requires special attention: It performs basically the same
                   9964: service as @code{AHEAD}, but it does not create a control-flow stack
                   9965: entry. Therefore the information has to be stored elsewhere;
                   9966: traditionally, the information was stored in the target fields of the
                   9967: branches created by the @code{LEAVE}s, by organizing these fields into a
                   9968: linked list. Unfortunately, this clever trick does not provide enough
                   9969: space for storing our extended control flow information. Therefore, we
                   9970: introduce another stack, the leave stack. It contains the control-flow
                   9971: stack entries for all unresolved @code{LEAVE}s.
1.44      crook    9972: 
1.78      anton    9973: Local names are kept until the end of the colon definition, even if
                   9974: they are no longer visible in any control-flow path. In a few cases
                   9975: this may lead to increased space needs for the locals name area, but
                   9976: usually less than reclaiming this space would cost in code size.
1.5       anton    9977: 
1.44      crook    9978: 
1.78      anton    9979: @node ANS Forth locals,  , Gforth locals, Locals
                   9980: @subsection ANS Forth locals
                   9981: @cindex locals, ANS Forth style
1.5       anton    9982: 
1.78      anton    9983: The ANS Forth locals wordset does not define a syntax for locals, but
                   9984: words that make it possible to define various syntaxes. One of the
                   9985: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   9986: wordset, i.e.:
1.29      crook    9987: 
                   9988: @example
1.78      anton    9989: @{ local1 local2 ... -- comment @}
                   9990: @end example
                   9991: @noindent
                   9992: or
                   9993: @example
                   9994: @{ local1 local2 ... @}
1.29      crook    9995: @end example
                   9996: 
1.78      anton    9997: The order of the locals corresponds to the order in a stack comment. The
                   9998: restrictions are:
1.5       anton    9999: 
1.78      anton    10000: @itemize @bullet
                   10001: @item
                   10002: Locals can only be cell-sized values (no type specifiers are allowed).
                   10003: @item
                   10004: Locals can be defined only outside control structures.
                   10005: @item
                   10006: Locals can interfere with explicit usage of the return stack. For the
                   10007: exact (and long) rules, see the standard. If you don't use return stack
                   10008: accessing words in a definition using locals, you will be all right. The
                   10009: purpose of this rule is to make locals implementation on the return
                   10010: stack easier.
                   10011: @item
                   10012: The whole definition must be in one line.
                   10013: @end itemize
1.5       anton    10014: 
1.78      anton    10015: Locals defined in ANS Forth behave like @code{VALUE}s
                   10016: (@pxref{Values}). I.e., they are initialized from the stack. Using their
                   10017: name produces their value. Their value can be changed using @code{TO}.
1.77      anton    10018: 
1.78      anton    10019: Since the syntax above is supported by Gforth directly, you need not do
                   10020: anything to use it. If you want to port a program using this syntax to
                   10021: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   10022: syntax on the other system.
1.5       anton    10023: 
1.78      anton    10024: Note that a syntax shown in the standard, section A.13 looks
                   10025: similar, but is quite different in having the order of locals
                   10026: reversed. Beware!
1.5       anton    10027: 
1.78      anton    10028: The ANS Forth locals wordset itself consists of one word:
1.5       anton    10029: 
1.78      anton    10030: doc-(local)
1.5       anton    10031: 
1.78      anton    10032: The ANS Forth locals extension wordset defines a syntax using
                   10033: @code{locals|}, but it is so awful that we strongly recommend not to use
                   10034: it. We have implemented this syntax to make porting to Gforth easy, but
                   10035: do not document it here. The problem with this syntax is that the locals
                   10036: are defined in an order reversed with respect to the standard stack
                   10037: comment notation, making programs harder to read, and easier to misread
                   10038: and miswrite. The only merit of this syntax is that it is easy to
                   10039: implement using the ANS Forth locals wordset.
1.53      anton    10040: 
                   10041: 
1.78      anton    10042: @c ----------------------------------------------------------
                   10043: @node Structures, Object-oriented Forth, Locals, Words
                   10044: @section  Structures
                   10045: @cindex structures
                   10046: @cindex records
1.53      anton    10047: 
1.78      anton    10048: This section presents the structure package that comes with Gforth. A
                   10049: version of the package implemented in ANS Forth is available in
                   10050: @file{compat/struct.fs}. This package was inspired by a posting on
                   10051: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   10052: possibly John Hayes). A version of this section has been published in
                   10053: M. Anton Ertl,
                   10054: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
                   10055: Another Forth Structures Package}, Forth Dimensions 19(3), pages
                   10056: 13--16. Marcel Hendrix provided helpful comments.
1.53      anton    10057: 
1.78      anton    10058: @menu
                   10059: * Why explicit structure support?::  
                   10060: * Structure Usage::             
                   10061: * Structure Naming Convention::  
                   10062: * Structure Implementation::    
                   10063: * Structure Glossary::          
1.183     anton    10064: * Forth200x Structures::        
1.78      anton    10065: @end menu
1.55      anton    10066: 
1.78      anton    10067: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   10068: @subsection Why explicit structure support?
1.53      anton    10069: 
1.78      anton    10070: @cindex address arithmetic for structures
                   10071: @cindex structures using address arithmetic
                   10072: If we want to use a structure containing several fields, we could simply
                   10073: reserve memory for it, and access the fields using address arithmetic
                   10074: (@pxref{Address arithmetic}). As an example, consider a structure with
                   10075: the following fields
1.57      anton    10076: 
1.78      anton    10077: @table @code
                   10078: @item a
                   10079: is a float
                   10080: @item b
                   10081: is a cell
                   10082: @item c
                   10083: is a float
                   10084: @end table
1.57      anton    10085: 
1.78      anton    10086: Given the (float-aligned) base address of the structure we get the
                   10087: address of the field
1.52      anton    10088: 
1.78      anton    10089: @table @code
                   10090: @item a
                   10091: without doing anything further.
                   10092: @item b
                   10093: with @code{float+}
                   10094: @item c
                   10095: with @code{float+ cell+ faligned}
                   10096: @end table
1.52      anton    10097: 
1.78      anton    10098: It is easy to see that this can become quite tiring. 
1.52      anton    10099: 
1.78      anton    10100: Moreover, it is not very readable, because seeing a
                   10101: @code{cell+} tells us neither which kind of structure is
                   10102: accessed nor what field is accessed; we have to somehow infer the kind
                   10103: of structure, and then look up in the documentation, which field of
                   10104: that structure corresponds to that offset.
1.53      anton    10105: 
1.78      anton    10106: Finally, this kind of address arithmetic also causes maintenance
                   10107: troubles: If you add or delete a field somewhere in the middle of the
                   10108: structure, you have to find and change all computations for the fields
                   10109: afterwards.
1.52      anton    10110: 
1.78      anton    10111: So, instead of using @code{cell+} and friends directly, how
                   10112: about storing the offsets in constants:
1.52      anton    10113: 
1.78      anton    10114: @example
                   10115: 0 constant a-offset
                   10116: 0 float+ constant b-offset
                   10117: 0 float+ cell+ faligned c-offset
                   10118: @end example
1.64      pazsan   10119: 
1.78      anton    10120: Now we can get the address of field @code{x} with @code{x-offset
                   10121: +}. This is much better in all respects. Of course, you still
                   10122: have to change all later offset definitions if you add a field. You can
                   10123: fix this by declaring the offsets in the following way:
1.57      anton    10124: 
1.78      anton    10125: @example
                   10126: 0 constant a-offset
                   10127: a-offset float+ constant b-offset
                   10128: b-offset cell+ faligned constant c-offset
                   10129: @end example
1.57      anton    10130: 
1.78      anton    10131: Since we always use the offsets with @code{+}, we could use a defining
                   10132: word @code{cfield} that includes the @code{+} in the action of the
                   10133: defined word:
1.64      pazsan   10134: 
1.78      anton    10135: @example
                   10136: : cfield ( n "name" -- )
                   10137:     create ,
                   10138: does> ( name execution: addr1 -- addr2 )
                   10139:     @@ + ;
1.64      pazsan   10140: 
1.78      anton    10141: 0 cfield a
                   10142: 0 a float+ cfield b
                   10143: 0 b cell+ faligned cfield c
                   10144: @end example
1.64      pazsan   10145: 
1.78      anton    10146: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64      pazsan   10147: 
1.78      anton    10148: The structure field words now can be used quite nicely. However,
                   10149: their definition is still a bit cumbersome: We have to repeat the
                   10150: name, the information about size and alignment is distributed before
                   10151: and after the field definitions etc.  The structure package presented
                   10152: here addresses these problems.
1.64      pazsan   10153: 
1.78      anton    10154: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   10155: @subsection Structure Usage
                   10156: @cindex structure usage
1.57      anton    10157: 
1.78      anton    10158: @cindex @code{field} usage
                   10159: @cindex @code{struct} usage
                   10160: @cindex @code{end-struct} usage
                   10161: You can define a structure for a (data-less) linked list with:
1.57      anton    10162: @example
1.78      anton    10163: struct
                   10164:     cell% field list-next
                   10165: end-struct list%
1.57      anton    10166: @end example
                   10167: 
1.78      anton    10168: With the address of the list node on the stack, you can compute the
                   10169: address of the field that contains the address of the next node with
                   10170: @code{list-next}. E.g., you can determine the length of a list
                   10171: with:
1.57      anton    10172: 
                   10173: @example
1.78      anton    10174: : list-length ( list -- n )
                   10175: \ "list" is a pointer to the first element of a linked list
                   10176: \ "n" is the length of the list
                   10177:     0 BEGIN ( list1 n1 )
                   10178:         over
                   10179:     WHILE ( list1 n1 )
                   10180:         1+ swap list-next @@ swap
                   10181:     REPEAT
                   10182:     nip ;
1.57      anton    10183: @end example
                   10184: 
1.78      anton    10185: You can reserve memory for a list node in the dictionary with
                   10186: @code{list% %allot}, which leaves the address of the list node on the
                   10187: stack. For the equivalent allocation on the heap you can use @code{list%
                   10188: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   10189: use @code{list% %allocate}). You can get the the size of a list
                   10190: node with @code{list% %size} and its alignment with @code{list%
                   10191: %alignment}.
                   10192: 
                   10193: Note that in ANS Forth the body of a @code{create}d word is
                   10194: @code{aligned} but not necessarily @code{faligned};
                   10195: therefore, if you do a:
1.57      anton    10196: 
                   10197: @example
1.78      anton    10198: create @emph{name} foo% %allot drop
1.57      anton    10199: @end example
                   10200: 
1.78      anton    10201: @noindent
                   10202: then the memory alloted for @code{foo%} is guaranteed to start at the
                   10203: body of @code{@emph{name}} only if @code{foo%} contains only character,
                   10204: cell and double fields.  Therefore, if your structure contains floats,
                   10205: better use
1.57      anton    10206: 
                   10207: @example
1.78      anton    10208: foo% %allot constant @emph{name}
1.57      anton    10209: @end example
                   10210: 
1.78      anton    10211: @cindex structures containing structures
                   10212: You can include a structure @code{foo%} as a field of
                   10213: another structure, like this:
1.65      anton    10214: @example
1.78      anton    10215: struct
                   10216: ...
                   10217:     foo% field ...
                   10218: ...
                   10219: end-struct ...
1.65      anton    10220: @end example
1.52      anton    10221: 
1.78      anton    10222: @cindex structure extension
                   10223: @cindex extended records
                   10224: Instead of starting with an empty structure, you can extend an
                   10225: existing structure. E.g., a plain linked list without data, as defined
                   10226: above, is hardly useful; You can extend it to a linked list of integers,
                   10227: like this:@footnote{This feature is also known as @emph{extended
                   10228: records}. It is the main innovation in the Oberon language; in other
                   10229: words, adding this feature to Modula-2 led Wirth to create a new
                   10230: language, write a new compiler etc.  Adding this feature to Forth just
                   10231: required a few lines of code.}
1.52      anton    10232: 
1.78      anton    10233: @example
                   10234: list%
                   10235:     cell% field intlist-int
                   10236: end-struct intlist%
                   10237: @end example
1.55      anton    10238: 
1.78      anton    10239: @code{intlist%} is a structure with two fields:
                   10240: @code{list-next} and @code{intlist-int}.
1.55      anton    10241: 
1.78      anton    10242: @cindex structures containing arrays
                   10243: You can specify an array type containing @emph{n} elements of
                   10244: type @code{foo%} like this:
1.55      anton    10245: 
                   10246: @example
1.78      anton    10247: foo% @emph{n} *
1.56      anton    10248: @end example
1.55      anton    10249: 
1.78      anton    10250: You can use this array type in any place where you can use a normal
                   10251: type, e.g., when defining a @code{field}, or with
                   10252: @code{%allot}.
                   10253: 
                   10254: @cindex first field optimization
                   10255: The first field is at the base address of a structure and the word for
                   10256: this field (e.g., @code{list-next}) actually does not change the address
                   10257: on the stack. You may be tempted to leave it away in the interest of
                   10258: run-time and space efficiency. This is not necessary, because the
                   10259: structure package optimizes this case: If you compile a first-field
                   10260: words, no code is generated. So, in the interest of readability and
                   10261: maintainability you should include the word for the field when accessing
                   10262: the field.
1.52      anton    10263: 
                   10264: 
1.78      anton    10265: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   10266: @subsection Structure Naming Convention
                   10267: @cindex structure naming convention
1.52      anton    10268: 
1.78      anton    10269: The field names that come to (my) mind are often quite generic, and,
                   10270: if used, would cause frequent name clashes. E.g., many structures
                   10271: probably contain a @code{counter} field. The structure names
                   10272: that come to (my) mind are often also the logical choice for the names
                   10273: of words that create such a structure.
1.52      anton    10274: 
1.78      anton    10275: Therefore, I have adopted the following naming conventions: 
1.52      anton    10276: 
1.78      anton    10277: @itemize @bullet
                   10278: @cindex field naming convention
                   10279: @item
                   10280: The names of fields are of the form
                   10281: @code{@emph{struct}-@emph{field}}, where
                   10282: @code{@emph{struct}} is the basic name of the structure, and
                   10283: @code{@emph{field}} is the basic name of the field. You can
                   10284: think of field words as converting the (address of the)
                   10285: structure into the (address of the) field.
1.52      anton    10286: 
1.78      anton    10287: @cindex structure naming convention
                   10288: @item
                   10289: The names of structures are of the form
                   10290: @code{@emph{struct}%}, where
                   10291: @code{@emph{struct}} is the basic name of the structure.
                   10292: @end itemize
1.52      anton    10293: 
1.78      anton    10294: This naming convention does not work that well for fields of extended
                   10295: structures; e.g., the integer list structure has a field
                   10296: @code{intlist-int}, but has @code{list-next}, not
                   10297: @code{intlist-next}.
1.53      anton    10298: 
1.78      anton    10299: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   10300: @subsection Structure Implementation
                   10301: @cindex structure implementation
                   10302: @cindex implementation of structures
1.52      anton    10303: 
1.78      anton    10304: The central idea in the implementation is to pass the data about the
                   10305: structure being built on the stack, not in some global
                   10306: variable. Everything else falls into place naturally once this design
                   10307: decision is made.
1.53      anton    10308: 
1.78      anton    10309: The type description on the stack is of the form @emph{align
                   10310: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   10311: very simple.
1.53      anton    10312: 
1.78      anton    10313: @code{field} is a defining word that uses @code{Create}
                   10314: and @code{DOES>}. The body of the field contains the offset
                   10315: of the field, and the normal @code{DOES>} action is simply:
1.53      anton    10316: 
                   10317: @example
1.78      anton    10318: @@ +
1.53      anton    10319: @end example
                   10320: 
1.78      anton    10321: @noindent
                   10322: i.e., add the offset to the address, giving the stack effect
                   10323: @i{addr1 -- addr2} for a field.
                   10324: 
                   10325: @cindex first field optimization, implementation
                   10326: This simple structure is slightly complicated by the optimization
                   10327: for fields with offset 0, which requires a different
                   10328: @code{DOES>}-part (because we cannot rely on there being
                   10329: something on the stack if such a field is invoked during
                   10330: compilation). Therefore, we put the different @code{DOES>}-parts
                   10331: in separate words, and decide which one to invoke based on the
                   10332: offset. For a zero offset, the field is basically a noop; it is
                   10333: immediate, and therefore no code is generated when it is compiled.
1.53      anton    10334: 
1.183     anton    10335: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
1.78      anton    10336: @subsection Structure Glossary
                   10337: @cindex structure glossary
1.53      anton    10338: 
1.5       anton    10339: 
1.78      anton    10340: doc-%align
                   10341: doc-%alignment
                   10342: doc-%alloc
                   10343: doc-%allocate
                   10344: doc-%allot
                   10345: doc-cell%
                   10346: doc-char%
                   10347: doc-dfloat%
                   10348: doc-double%
                   10349: doc-end-struct
                   10350: doc-field
                   10351: doc-float%
                   10352: doc-naligned
                   10353: doc-sfloat%
                   10354: doc-%size
                   10355: doc-struct
1.54      anton    10356: 
                   10357: 
1.183     anton    10358: @node Forth200x Structures,  , Structure Glossary, Structures
                   10359: @subsection Forth200x Structures
                   10360: @cindex Structures in Forth200x
                   10361: 
                   10362: The Forth 200x standard defines a slightly less convenient form of
                   10363: structures.  In general (when using @code{field+}, you have to perform
                   10364: the alignment yourself, but there are a number of convenience words
                   10365: (e.g., @code{field:} that perform the alignment for you.
                   10366: 
                   10367: A typical usage example is:
                   10368: 
                   10369: @example
                   10370: 0
                   10371:   field:                   s-a
                   10372:   faligned 2 floats +field s-b
                   10373: constant s-struct
                   10374: @end example
                   10375: 
                   10376: An alternative way of writing this structure is:
                   10377: 
                   10378: @example
                   10379: begin-structure s-struct
                   10380:   field:                   s-a
                   10381:   faligned 2 floats +field s-b
                   10382: end-structure
                   10383: @end example
                   10384: 
                   10385: doc-begin-structure
                   10386: doc-end-structure
                   10387: doc-+field
                   10388: doc-cfield:
                   10389: doc-field:
                   10390: doc-2field:
                   10391: doc-ffield:
                   10392: doc-sffield:
                   10393: doc-dffield:
                   10394: 
1.26      crook    10395: @c -------------------------------------------------------------
1.78      anton    10396: @node Object-oriented Forth, Programming Tools, Structures, Words
                   10397: @section Object-oriented Forth
                   10398: 
                   10399: Gforth comes with three packages for object-oriented programming:
                   10400: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   10401: is preloaded, so you have to @code{include} them before use. The most
                   10402: important differences between these packages (and others) are discussed
                   10403: in @ref{Comparison with other object models}. All packages are written
                   10404: in ANS Forth and can be used with any other ANS Forth.
1.5       anton    10405: 
1.78      anton    10406: @menu
                   10407: * Why object-oriented programming?::  
                   10408: * Object-Oriented Terminology::  
                   10409: * Objects::                     
                   10410: * OOF::                         
                   10411: * Mini-OOF::                    
                   10412: * Comparison with other object models::  
                   10413: @end menu
1.5       anton    10414: 
1.78      anton    10415: @c ----------------------------------------------------------------
                   10416: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
                   10417: @subsection Why object-oriented programming?
                   10418: @cindex object-oriented programming motivation
                   10419: @cindex motivation for object-oriented programming
1.44      crook    10420: 
1.78      anton    10421: Often we have to deal with several data structures (@emph{objects}),
                   10422: that have to be treated similarly in some respects, but differently in
                   10423: others. Graphical objects are the textbook example: circles, triangles,
                   10424: dinosaurs, icons, and others, and we may want to add more during program
                   10425: development. We want to apply some operations to any graphical object,
                   10426: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   10427: has to do something different for every kind of object.
                   10428: @comment TODO add some other operations eg perimeter, area
                   10429: @comment and tie in to concrete examples later..
1.5       anton    10430: 
1.78      anton    10431: We could implement @code{draw} as a big @code{CASE}
                   10432: control structure that executes the appropriate code depending on the
                   10433: kind of object to be drawn. This would be not be very elegant, and,
                   10434: moreover, we would have to change @code{draw} every time we add
                   10435: a new kind of graphical object (say, a spaceship).
1.44      crook    10436: 
1.78      anton    10437: What we would rather do is: When defining spaceships, we would tell
                   10438: the system: ``Here's how you @code{draw} a spaceship; you figure
                   10439: out the rest''.
1.5       anton    10440: 
1.78      anton    10441: This is the problem that all systems solve that (rightfully) call
                   10442: themselves object-oriented; the object-oriented packages presented here
                   10443: solve this problem (and not much else).
                   10444: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44      crook    10445: 
1.78      anton    10446: @c ------------------------------------------------------------------------
                   10447: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
                   10448: @subsection Object-Oriented Terminology
                   10449: @cindex object-oriented terminology
                   10450: @cindex terminology for object-oriented programming
1.5       anton    10451: 
1.78      anton    10452: This section is mainly for reference, so you don't have to understand
                   10453: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   10454: short:
1.44      crook    10455: 
1.78      anton    10456: @table @emph
                   10457: @cindex class
                   10458: @item class
                   10459: a data structure definition with some extras.
1.5       anton    10460: 
1.78      anton    10461: @cindex object
                   10462: @item object
                   10463: an instance of the data structure described by the class definition.
1.5       anton    10464: 
1.78      anton    10465: @cindex instance variables
                   10466: @item instance variables
                   10467: fields of the data structure.
1.5       anton    10468: 
1.78      anton    10469: @cindex selector
                   10470: @cindex method selector
                   10471: @cindex virtual function
                   10472: @item selector
                   10473: (or @emph{method selector}) a word (e.g.,
                   10474: @code{draw}) that performs an operation on a variety of data
                   10475: structures (classes). A selector describes @emph{what} operation to
                   10476: perform. In C++ terminology: a (pure) virtual function.
1.5       anton    10477: 
1.78      anton    10478: @cindex method
                   10479: @item method
                   10480: the concrete definition that performs the operation
                   10481: described by the selector for a specific class. A method specifies
                   10482: @emph{how} the operation is performed for a specific class.
1.5       anton    10483: 
1.78      anton    10484: @cindex selector invocation
                   10485: @cindex message send
                   10486: @cindex invoking a selector
                   10487: @item selector invocation
                   10488: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   10489: is used for determining which method is used. In Smalltalk terminology:
                   10490: a message (consisting of the selector and the other arguments) is sent
                   10491: to the object.
1.5       anton    10492: 
1.78      anton    10493: @cindex receiving object
                   10494: @item receiving object
                   10495: the object used for determining the method executed by a selector
                   10496: invocation. In the @file{objects.fs} model, it is the object that is on
                   10497: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   10498: the Smalltalk @emph{message} terminology.)
1.5       anton    10499: 
1.78      anton    10500: @cindex child class
                   10501: @cindex parent class
                   10502: @cindex inheritance
                   10503: @item child class
                   10504: a class that has (@emph{inherits}) all properties (instance variables,
                   10505: selectors, methods) from a @emph{parent class}. In Smalltalk
                   10506: terminology: The subclass inherits from the superclass. In C++
                   10507: terminology: The derived class inherits from the base class.
1.5       anton    10508: 
1.78      anton    10509: @end table
1.5       anton    10510: 
1.78      anton    10511: @c If you wonder about the message sending terminology, it comes from
                   10512: @c a time when each object had it's own task and objects communicated via
                   10513: @c message passing; eventually the Smalltalk developers realized that
                   10514: @c they can do most things through simple (indirect) calls. They kept the
                   10515: @c terminology.
1.5       anton    10516: 
1.78      anton    10517: @c --------------------------------------------------------------
                   10518: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   10519: @subsection The @file{objects.fs} model
                   10520: @cindex objects
                   10521: @cindex object-oriented programming
1.26      crook    10522: 
1.78      anton    10523: @cindex @file{objects.fs}
                   10524: @cindex @file{oof.fs}
1.26      crook    10525: 
1.78      anton    10526: This section describes the @file{objects.fs} package. This material also
                   10527: has been published in M. Anton Ertl,
                   10528: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
                   10529: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
                   10530: 37--43.
                   10531: @c McKewan's and Zsoter's packages
1.26      crook    10532: 
1.78      anton    10533: This section assumes that you have read @ref{Structures}.
1.5       anton    10534: 
1.78      anton    10535: The techniques on which this model is based have been used to implement
                   10536: the parser generator, Gray, and have also been used in Gforth for
                   10537: implementing the various flavours of word lists (hashed or not,
                   10538: case-sensitive or not, special-purpose word lists for locals etc.).
1.5       anton    10539: 
                   10540: 
1.26      crook    10541: @menu
1.78      anton    10542: * Properties of the Objects model::  
                   10543: * Basic Objects Usage::         
                   10544: * The Objects base class::      
                   10545: * Creating objects::            
                   10546: * Object-Oriented Programming Style::  
                   10547: * Class Binding::               
                   10548: * Method conveniences::         
                   10549: * Classes and Scoping::         
                   10550: * Dividing classes::            
                   10551: * Object Interfaces::           
                   10552: * Objects Implementation::      
                   10553: * Objects Glossary::            
1.26      crook    10554: @end menu
1.5       anton    10555: 
1.78      anton    10556: Marcel Hendrix provided helpful comments on this section.
1.5       anton    10557: 
1.78      anton    10558: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   10559: @subsubsection Properties of the @file{objects.fs} model
                   10560: @cindex @file{objects.fs} properties
1.5       anton    10561: 
1.78      anton    10562: @itemize @bullet
                   10563: @item
                   10564: It is straightforward to pass objects on the stack. Passing
                   10565: selectors on the stack is a little less convenient, but possible.
1.44      crook    10566: 
1.78      anton    10567: @item
                   10568: Objects are just data structures in memory, and are referenced by their
                   10569: address. You can create words for objects with normal defining words
                   10570: like @code{constant}. Likewise, there is no difference between instance
                   10571: variables that contain objects and those that contain other data.
1.5       anton    10572: 
1.78      anton    10573: @item
                   10574: Late binding is efficient and easy to use.
1.44      crook    10575: 
1.78      anton    10576: @item
                   10577: It avoids parsing, and thus avoids problems with state-smartness
                   10578: and reduced extensibility; for convenience there are a few parsing
                   10579: words, but they have non-parsing counterparts. There are also a few
                   10580: defining words that parse. This is hard to avoid, because all standard
                   10581: defining words parse (except @code{:noname}); however, such
                   10582: words are not as bad as many other parsing words, because they are not
                   10583: state-smart.
1.5       anton    10584: 
1.78      anton    10585: @item
                   10586: It does not try to incorporate everything. It does a few things and does
                   10587: them well (IMO). In particular, this model was not designed to support
                   10588: information hiding (although it has features that may help); you can use
                   10589: a separate package for achieving this.
1.5       anton    10590: 
1.78      anton    10591: @item
                   10592: It is layered; you don't have to learn and use all features to use this
                   10593: model. Only a few features are necessary (@pxref{Basic Objects Usage},
                   10594: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
                   10595: are optional and independent of each other.
1.5       anton    10596: 
1.78      anton    10597: @item
                   10598: An implementation in ANS Forth is available.
1.5       anton    10599: 
1.78      anton    10600: @end itemize
1.5       anton    10601: 
1.44      crook    10602: 
1.78      anton    10603: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   10604: @subsubsection Basic @file{objects.fs} Usage
                   10605: @cindex basic objects usage
                   10606: @cindex objects, basic usage
1.5       anton    10607: 
1.78      anton    10608: You can define a class for graphical objects like this:
1.44      crook    10609: 
1.78      anton    10610: @cindex @code{class} usage
                   10611: @cindex @code{end-class} usage
                   10612: @cindex @code{selector} usage
1.5       anton    10613: @example
1.78      anton    10614: object class \ "object" is the parent class
                   10615:   selector draw ( x y graphical -- )
                   10616: end-class graphical
                   10617: @end example
                   10618: 
                   10619: This code defines a class @code{graphical} with an
                   10620: operation @code{draw}.  We can perform the operation
                   10621: @code{draw} on any @code{graphical} object, e.g.:
                   10622: 
                   10623: @example
                   10624: 100 100 t-rex draw
1.26      crook    10625: @end example
1.5       anton    10626: 
1.78      anton    10627: @noindent
                   10628: where @code{t-rex} is a word (say, a constant) that produces a
                   10629: graphical object.
                   10630: 
                   10631: @comment TODO add a 2nd operation eg perimeter.. and use for
                   10632: @comment a concrete example
1.5       anton    10633: 
1.78      anton    10634: @cindex abstract class
                   10635: How do we create a graphical object? With the present definitions,
                   10636: we cannot create a useful graphical object. The class
                   10637: @code{graphical} describes graphical objects in general, but not
                   10638: any concrete graphical object type (C++ users would call it an
                   10639: @emph{abstract class}); e.g., there is no method for the selector
                   10640: @code{draw} in the class @code{graphical}.
1.5       anton    10641: 
1.78      anton    10642: For concrete graphical objects, we define child classes of the
                   10643: class @code{graphical}, e.g.:
1.5       anton    10644: 
1.78      anton    10645: @cindex @code{overrides} usage
                   10646: @cindex @code{field} usage in class definition
1.26      crook    10647: @example
1.78      anton    10648: graphical class \ "graphical" is the parent class
                   10649:   cell% field circle-radius
1.5       anton    10650: 
1.78      anton    10651: :noname ( x y circle -- )
                   10652:   circle-radius @@ draw-circle ;
                   10653: overrides draw
1.5       anton    10654: 
1.78      anton    10655: :noname ( n-radius circle -- )
                   10656:   circle-radius ! ;
                   10657: overrides construct
1.5       anton    10658: 
1.78      anton    10659: end-class circle
                   10660: @end example
1.44      crook    10661: 
1.78      anton    10662: Here we define a class @code{circle} as a child of @code{graphical},
                   10663: with field @code{circle-radius} (which behaves just like a field
                   10664: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   10665: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   10666: defined in @code{object}, the parent class of @code{graphical}).
1.5       anton    10667: 
1.78      anton    10668: Now we can create a circle on the heap (i.e.,
                   10669: @code{allocate}d memory) with:
1.44      crook    10670: 
1.78      anton    10671: @cindex @code{heap-new} usage
1.5       anton    10672: @example
1.78      anton    10673: 50 circle heap-new constant my-circle
1.5       anton    10674: @end example
                   10675: 
1.78      anton    10676: @noindent
                   10677: @code{heap-new} invokes @code{construct}, thus
                   10678: initializing the field @code{circle-radius} with 50. We can draw
                   10679: this new circle at (100,100) with:
1.5       anton    10680: 
                   10681: @example
1.78      anton    10682: 100 100 my-circle draw
1.5       anton    10683: @end example
                   10684: 
1.78      anton    10685: @cindex selector invocation, restrictions
                   10686: @cindex class definition, restrictions
                   10687: Note: You can only invoke a selector if the object on the TOS
                   10688: (the receiving object) belongs to the class where the selector was
                   10689: defined or one of its descendents; e.g., you can invoke
                   10690: @code{draw} only for objects belonging to @code{graphical}
                   10691: or its descendents (e.g., @code{circle}).  Immediately before
                   10692: @code{end-class}, the search order has to be the same as
                   10693: immediately after @code{class}.
                   10694: 
                   10695: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   10696: @subsubsection The @file{object.fs} base class
                   10697: @cindex @code{object} class
                   10698: 
                   10699: When you define a class, you have to specify a parent class.  So how do
                   10700: you start defining classes? There is one class available from the start:
                   10701: @code{object}. It is ancestor for all classes and so is the
                   10702: only class that has no parent. It has two selectors: @code{construct}
                   10703: and @code{print}.
                   10704: 
                   10705: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   10706: @subsubsection Creating objects
                   10707: @cindex creating objects
                   10708: @cindex object creation
                   10709: @cindex object allocation options
                   10710: 
                   10711: @cindex @code{heap-new} discussion
                   10712: @cindex @code{dict-new} discussion
                   10713: @cindex @code{construct} discussion
                   10714: You can create and initialize an object of a class on the heap with
                   10715: @code{heap-new} ( ... class -- object ) and in the dictionary
                   10716: (allocation with @code{allot}) with @code{dict-new} (
                   10717: ... class -- object ). Both words invoke @code{construct}, which
                   10718: consumes the stack items indicated by "..." above.
                   10719: 
                   10720: @cindex @code{init-object} discussion
                   10721: @cindex @code{class-inst-size} discussion
                   10722: If you want to allocate memory for an object yourself, you can get its
                   10723: alignment and size with @code{class-inst-size 2@@} ( class --
                   10724: align size ). Once you have memory for an object, you can initialize
                   10725: it with @code{init-object} ( ... class object -- );
                   10726: @code{construct} does only a part of the necessary work.
                   10727: 
                   10728: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   10729: @subsubsection Object-Oriented Programming Style
                   10730: @cindex object-oriented programming style
                   10731: @cindex programming style, object-oriented
1.5       anton    10732: 
1.78      anton    10733: This section is not exhaustive.
1.5       anton    10734: 
1.78      anton    10735: @cindex stack effects of selectors
                   10736: @cindex selectors and stack effects
                   10737: In general, it is a good idea to ensure that all methods for the
                   10738: same selector have the same stack effect: when you invoke a selector,
                   10739: you often have no idea which method will be invoked, so, unless all
                   10740: methods have the same stack effect, you will not know the stack effect
                   10741: of the selector invocation.
1.5       anton    10742: 
1.78      anton    10743: One exception to this rule is methods for the selector
                   10744: @code{construct}. We know which method is invoked, because we
                   10745: specify the class to be constructed at the same place. Actually, I
                   10746: defined @code{construct} as a selector only to give the users a
                   10747: convenient way to specify initialization. The way it is used, a
                   10748: mechanism different from selector invocation would be more natural
                   10749: (but probably would take more code and more space to explain).
1.5       anton    10750: 
1.78      anton    10751: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   10752: @subsubsection Class Binding
                   10753: @cindex class binding
                   10754: @cindex early binding
1.5       anton    10755: 
1.78      anton    10756: @cindex late binding
                   10757: Normal selector invocations determine the method at run-time depending
                   10758: on the class of the receiving object. This run-time selection is called
                   10759: @i{late binding}.
1.5       anton    10760: 
1.78      anton    10761: Sometimes it's preferable to invoke a different method. For example,
                   10762: you might want to use the simple method for @code{print}ing
                   10763: @code{object}s instead of the possibly long-winded @code{print} method
                   10764: of the receiver class. You can achieve this by replacing the invocation
                   10765: of @code{print} with:
1.5       anton    10766: 
1.78      anton    10767: @cindex @code{[bind]} usage
1.5       anton    10768: @example
1.78      anton    10769: [bind] object print
1.5       anton    10770: @end example
                   10771: 
1.78      anton    10772: @noindent
                   10773: in compiled code or:
                   10774: 
                   10775: @cindex @code{bind} usage
1.5       anton    10776: @example
1.78      anton    10777: bind object print
1.5       anton    10778: @end example
                   10779: 
1.78      anton    10780: @cindex class binding, alternative to
                   10781: @noindent
                   10782: in interpreted code. Alternatively, you can define the method with a
                   10783: name (e.g., @code{print-object}), and then invoke it through the
                   10784: name. Class binding is just a (often more convenient) way to achieve
                   10785: the same effect; it avoids name clutter and allows you to invoke
                   10786: methods directly without naming them first.
1.5       anton    10787: 
1.78      anton    10788: @cindex superclass binding
                   10789: @cindex parent class binding
                   10790: A frequent use of class binding is this: When we define a method
                   10791: for a selector, we often want the method to do what the selector does
                   10792: in the parent class, and a little more. There is a special word for
                   10793: this purpose: @code{[parent]}; @code{[parent]
                   10794: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   10795: selector}}, where @code{@emph{parent}} is the parent
                   10796: class of the current class. E.g., a method definition might look like:
1.44      crook    10797: 
1.78      anton    10798: @cindex @code{[parent]} usage
                   10799: @example
                   10800: :noname
                   10801:   dup [parent] foo \ do parent's foo on the receiving object
                   10802:   ... \ do some more
                   10803: ; overrides foo
                   10804: @end example
1.6       pazsan   10805: 
1.78      anton    10806: @cindex class binding as optimization
                   10807: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   10808: March 1997), Andrew McKewan presents class binding as an optimization
                   10809: technique. I recommend not using it for this purpose unless you are in
                   10810: an emergency. Late binding is pretty fast with this model anyway, so the
                   10811: benefit of using class binding is small; the cost of using class binding
                   10812: where it is not appropriate is reduced maintainability.
1.44      crook    10813: 
1.78      anton    10814: While we are at programming style questions: You should bind
                   10815: selectors only to ancestor classes of the receiving object. E.g., say,
                   10816: you know that the receiving object is of class @code{foo} or its
                   10817: descendents; then you should bind only to @code{foo} and its
                   10818: ancestors.
1.12      anton    10819: 
1.78      anton    10820: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   10821: @subsubsection Method conveniences
                   10822: @cindex method conveniences
1.44      crook    10823: 
1.78      anton    10824: In a method you usually access the receiving object pretty often.  If
                   10825: you define the method as a plain colon definition (e.g., with
                   10826: @code{:noname}), you may have to do a lot of stack
                   10827: gymnastics. To avoid this, you can define the method with @code{m:
                   10828: ... ;m}. E.g., you could define the method for
                   10829: @code{draw}ing a @code{circle} with
1.6       pazsan   10830: 
1.78      anton    10831: @cindex @code{this} usage
                   10832: @cindex @code{m:} usage
                   10833: @cindex @code{;m} usage
                   10834: @example
                   10835: m: ( x y circle -- )
                   10836:   ( x y ) this circle-radius @@ draw-circle ;m
                   10837: @end example
1.6       pazsan   10838: 
1.78      anton    10839: @cindex @code{exit} in @code{m: ... ;m}
                   10840: @cindex @code{exitm} discussion
                   10841: @cindex @code{catch} in @code{m: ... ;m}
                   10842: When this method is executed, the receiver object is removed from the
                   10843: stack; you can access it with @code{this} (admittedly, in this
                   10844: example the use of @code{m: ... ;m} offers no advantage). Note
                   10845: that I specify the stack effect for the whole method (i.e. including
                   10846: the receiver object), not just for the code between @code{m:}
                   10847: and @code{;m}. You cannot use @code{exit} in
                   10848: @code{m:...;m}; instead, use
                   10849: @code{exitm}.@footnote{Moreover, for any word that calls
                   10850: @code{catch} and was defined before loading
                   10851: @code{objects.fs}, you have to redefine it like I redefined
                   10852: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12      anton    10853: 
1.78      anton    10854: @cindex @code{inst-var} usage
                   10855: You will frequently use sequences of the form @code{this
                   10856: @emph{field}} (in the example above: @code{this
                   10857: circle-radius}). If you use the field only in this way, you can
                   10858: define it with @code{inst-var} and eliminate the
                   10859: @code{this} before the field name. E.g., the @code{circle}
                   10860: class above could also be defined with:
1.6       pazsan   10861: 
1.78      anton    10862: @example
                   10863: graphical class
                   10864:   cell% inst-var radius
1.6       pazsan   10865: 
1.78      anton    10866: m: ( x y circle -- )
                   10867:   radius @@ draw-circle ;m
                   10868: overrides draw
1.6       pazsan   10869: 
1.78      anton    10870: m: ( n-radius circle -- )
                   10871:   radius ! ;m
                   10872: overrides construct
1.6       pazsan   10873: 
1.78      anton    10874: end-class circle
                   10875: @end example
1.6       pazsan   10876: 
1.78      anton    10877: @code{radius} can only be used in @code{circle} and its
                   10878: descendent classes and inside @code{m:...;m}.
1.6       pazsan   10879: 
1.78      anton    10880: @cindex @code{inst-value} usage
                   10881: You can also define fields with @code{inst-value}, which is
                   10882: to @code{inst-var} what @code{value} is to
                   10883: @code{variable}.  You can change the value of such a field with
                   10884: @code{[to-inst]}.  E.g., we could also define the class
                   10885: @code{circle} like this:
1.44      crook    10886: 
1.78      anton    10887: @example
                   10888: graphical class
                   10889:   inst-value radius
1.6       pazsan   10890: 
1.78      anton    10891: m: ( x y circle -- )
                   10892:   radius draw-circle ;m
                   10893: overrides draw
1.44      crook    10894: 
1.78      anton    10895: m: ( n-radius circle -- )
                   10896:   [to-inst] radius ;m
                   10897: overrides construct
1.6       pazsan   10898: 
1.78      anton    10899: end-class circle
                   10900: @end example
1.6       pazsan   10901: 
1.78      anton    10902: @c !! :m is easy to confuse with m:.  Another name would be better.
1.6       pazsan   10903: 
1.78      anton    10904: @c Finally, you can define named methods with @code{:m}.  One use of this
                   10905: @c feature is the definition of words that occur only in one class and are
                   10906: @c not intended to be overridden, but which still need method context
                   10907: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
                   10908: @c would be bound frequently, if defined anonymously.
1.6       pazsan   10909: 
                   10910: 
1.78      anton    10911: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
                   10912: @subsubsection Classes and Scoping
                   10913: @cindex classes and scoping
                   10914: @cindex scoping and classes
1.6       pazsan   10915: 
1.78      anton    10916: Inheritance is frequent, unlike structure extension. This exacerbates
                   10917: the problem with the field name convention (@pxref{Structure Naming
                   10918: Convention}): One always has to remember in which class the field was
                   10919: originally defined; changing a part of the class structure would require
                   10920: changes for renaming in otherwise unaffected code.
1.6       pazsan   10921: 
1.78      anton    10922: @cindex @code{inst-var} visibility
                   10923: @cindex @code{inst-value} visibility
                   10924: To solve this problem, I added a scoping mechanism (which was not in my
                   10925: original charter): A field defined with @code{inst-var} (or
                   10926: @code{inst-value}) is visible only in the class where it is defined and in
                   10927: the descendent classes of this class.  Using such fields only makes
                   10928: sense in @code{m:}-defined methods in these classes anyway.
1.6       pazsan   10929: 
1.78      anton    10930: This scoping mechanism allows us to use the unadorned field name,
                   10931: because name clashes with unrelated words become much less likely.
1.6       pazsan   10932: 
1.78      anton    10933: @cindex @code{protected} discussion
                   10934: @cindex @code{private} discussion
                   10935: Once we have this mechanism, we can also use it for controlling the
                   10936: visibility of other words: All words defined after
                   10937: @code{protected} are visible only in the current class and its
                   10938: descendents. @code{public} restores the compilation
                   10939: (i.e. @code{current}) word list that was in effect before. If you
                   10940: have several @code{protected}s without an intervening
                   10941: @code{public} or @code{set-current}, @code{public}
                   10942: will restore the compilation word list in effect before the first of
                   10943: these @code{protected}s.
1.6       pazsan   10944: 
1.78      anton    10945: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
                   10946: @subsubsection Dividing classes
                   10947: @cindex Dividing classes
                   10948: @cindex @code{methods}...@code{end-methods}
1.6       pazsan   10949: 
1.78      anton    10950: You may want to do the definition of methods separate from the
                   10951: definition of the class, its selectors, fields, and instance variables,
                   10952: i.e., separate the implementation from the definition.  You can do this
                   10953: in the following way:
1.6       pazsan   10954: 
1.78      anton    10955: @example
                   10956: graphical class
                   10957:   inst-value radius
                   10958: end-class circle
1.6       pazsan   10959: 
1.78      anton    10960: ... \ do some other stuff
1.6       pazsan   10961: 
1.78      anton    10962: circle methods \ now we are ready
1.44      crook    10963: 
1.78      anton    10964: m: ( x y circle -- )
                   10965:   radius draw-circle ;m
                   10966: overrides draw
1.6       pazsan   10967: 
1.78      anton    10968: m: ( n-radius circle -- )
                   10969:   [to-inst] radius ;m
                   10970: overrides construct
1.44      crook    10971: 
1.78      anton    10972: end-methods
                   10973: @end example
1.7       pazsan   10974: 
1.78      anton    10975: You can use several @code{methods}...@code{end-methods} sections.  The
                   10976: only things you can do to the class in these sections are: defining
                   10977: methods, and overriding the class's selectors.  You must not define new
                   10978: selectors or fields.
1.7       pazsan   10979: 
1.78      anton    10980: Note that you often have to override a selector before using it.  In
                   10981: particular, you usually have to override @code{construct} with a new
                   10982: method before you can invoke @code{heap-new} and friends.  E.g., you
                   10983: must not create a circle before the @code{overrides construct} sequence
                   10984: in the example above.
1.7       pazsan   10985: 
1.78      anton    10986: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
                   10987: @subsubsection Object Interfaces
                   10988: @cindex object interfaces
                   10989: @cindex interfaces for objects
1.7       pazsan   10990: 
1.78      anton    10991: In this model you can only call selectors defined in the class of the
                   10992: receiving objects or in one of its ancestors. If you call a selector
                   10993: with a receiving object that is not in one of these classes, the
                   10994: result is undefined; if you are lucky, the program crashes
                   10995: immediately.
1.7       pazsan   10996: 
1.78      anton    10997: @cindex selectors common to hardly-related classes
                   10998: Now consider the case when you want to have a selector (or several)
                   10999: available in two classes: You would have to add the selector to a
                   11000: common ancestor class, in the worst case to @code{object}. You
                   11001: may not want to do this, e.g., because someone else is responsible for
                   11002: this ancestor class.
1.7       pazsan   11003: 
1.78      anton    11004: The solution for this problem is interfaces. An interface is a
                   11005: collection of selectors. If a class implements an interface, the
                   11006: selectors become available to the class and its descendents. A class
                   11007: can implement an unlimited number of interfaces. For the problem
                   11008: discussed above, we would define an interface for the selector(s), and
                   11009: both classes would implement the interface.
1.7       pazsan   11010: 
1.78      anton    11011: As an example, consider an interface @code{storage} for
                   11012: writing objects to disk and getting them back, and a class
                   11013: @code{foo} that implements it. The code would look like this:
1.7       pazsan   11014: 
1.78      anton    11015: @cindex @code{interface} usage
                   11016: @cindex @code{end-interface} usage
                   11017: @cindex @code{implementation} usage
                   11018: @example
                   11019: interface
                   11020:   selector write ( file object -- )
                   11021:   selector read1 ( file object -- )
                   11022: end-interface storage
1.13      pazsan   11023: 
1.78      anton    11024: bar class
                   11025:   storage implementation
1.13      pazsan   11026: 
1.78      anton    11027: ... overrides write
                   11028: ... overrides read1
                   11029: ...
                   11030: end-class foo
                   11031: @end example
1.13      pazsan   11032: 
1.78      anton    11033: @noindent
                   11034: (I would add a word @code{read} @i{( file -- object )} that uses
                   11035: @code{read1} internally, but that's beyond the point illustrated
                   11036: here.)
1.13      pazsan   11037: 
1.78      anton    11038: Note that you cannot use @code{protected} in an interface; and
                   11039: of course you cannot define fields.
1.13      pazsan   11040: 
1.78      anton    11041: In the Neon model, all selectors are available for all classes;
                   11042: therefore it does not need interfaces. The price you pay in this model
                   11043: is slower late binding, and therefore, added complexity to avoid late
                   11044: binding.
1.13      pazsan   11045: 
1.78      anton    11046: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   11047: @subsubsection @file{objects.fs} Implementation
                   11048: @cindex @file{objects.fs} implementation
1.13      pazsan   11049: 
1.78      anton    11050: @cindex @code{object-map} discussion
                   11051: An object is a piece of memory, like one of the data structures
                   11052: described with @code{struct...end-struct}. It has a field
                   11053: @code{object-map} that points to the method map for the object's
                   11054: class.
1.13      pazsan   11055: 
1.78      anton    11056: @cindex method map
                   11057: @cindex virtual function table
                   11058: The @emph{method map}@footnote{This is Self terminology; in C++
                   11059: terminology: virtual function table.} is an array that contains the
                   11060: execution tokens (@i{xt}s) of the methods for the object's class. Each
                   11061: selector contains an offset into a method map.
1.13      pazsan   11062: 
1.78      anton    11063: @cindex @code{selector} implementation, class
                   11064: @code{selector} is a defining word that uses
                   11065: @code{CREATE} and @code{DOES>}. The body of the
                   11066: selector contains the offset; the @code{DOES>} action for a
                   11067: class selector is, basically:
1.8       pazsan   11068: 
                   11069: @example
1.78      anton    11070: ( object addr ) @@ over object-map @@ + @@ execute
1.13      pazsan   11071: @end example
                   11072: 
1.78      anton    11073: Since @code{object-map} is the first field of the object, it
                   11074: does not generate any code. As you can see, calling a selector has a
                   11075: small, constant cost.
1.26      crook    11076: 
1.78      anton    11077: @cindex @code{current-interface} discussion
                   11078: @cindex class implementation and representation
                   11079: A class is basically a @code{struct} combined with a method
                   11080: map. During the class definition the alignment and size of the class
                   11081: are passed on the stack, just as with @code{struct}s, so
                   11082: @code{field} can also be used for defining class
                   11083: fields. However, passing more items on the stack would be
                   11084: inconvenient, so @code{class} builds a data structure in memory,
                   11085: which is accessed through the variable
                   11086: @code{current-interface}. After its definition is complete, the
                   11087: class is represented on the stack by a pointer (e.g., as parameter for
                   11088: a child class definition).
1.26      crook    11089: 
1.78      anton    11090: A new class starts off with the alignment and size of its parent,
                   11091: and a copy of the parent's method map. Defining new fields extends the
                   11092: size and alignment; likewise, defining new selectors extends the
                   11093: method map. @code{overrides} just stores a new @i{xt} in the method
                   11094: map at the offset given by the selector.
1.13      pazsan   11095: 
1.78      anton    11096: @cindex class binding, implementation
                   11097: Class binding just gets the @i{xt} at the offset given by the selector
                   11098: from the class's method map and @code{compile,}s (in the case of
                   11099: @code{[bind]}) it.
1.13      pazsan   11100: 
1.78      anton    11101: @cindex @code{this} implementation
                   11102: @cindex @code{catch} and @code{this}
                   11103: @cindex @code{this} and @code{catch}
                   11104: I implemented @code{this} as a @code{value}. At the
                   11105: start of an @code{m:...;m} method the old @code{this} is
                   11106: stored to the return stack and restored at the end; and the object on
                   11107: the TOS is stored @code{TO this}. This technique has one
                   11108: disadvantage: If the user does not leave the method via
                   11109: @code{;m}, but via @code{throw} or @code{exit},
                   11110: @code{this} is not restored (and @code{exit} may
                   11111: crash). To deal with the @code{throw} problem, I have redefined
                   11112: @code{catch} to save and restore @code{this}; the same
                   11113: should be done with any word that can catch an exception. As for
                   11114: @code{exit}, I simply forbid it (as a replacement, there is
                   11115: @code{exitm}).
1.13      pazsan   11116: 
1.78      anton    11117: @cindex @code{inst-var} implementation
                   11118: @code{inst-var} is just the same as @code{field}, with
                   11119: a different @code{DOES>} action:
1.13      pazsan   11120: @example
1.78      anton    11121: @@ this +
1.8       pazsan   11122: @end example
1.78      anton    11123: Similar for @code{inst-value}.
1.8       pazsan   11124: 
1.78      anton    11125: @cindex class scoping implementation
                   11126: Each class also has a word list that contains the words defined with
                   11127: @code{inst-var} and @code{inst-value}, and its protected
                   11128: words. It also has a pointer to its parent. @code{class} pushes
                   11129: the word lists of the class and all its ancestors onto the search order stack,
                   11130: and @code{end-class} drops them.
1.20      pazsan   11131: 
1.78      anton    11132: @cindex interface implementation
                   11133: An interface is like a class without fields, parent and protected
                   11134: words; i.e., it just has a method map. If a class implements an
                   11135: interface, its method map contains a pointer to the method map of the
                   11136: interface. The positive offsets in the map are reserved for class
                   11137: methods, therefore interface map pointers have negative
                   11138: offsets. Interfaces have offsets that are unique throughout the
                   11139: system, unlike class selectors, whose offsets are only unique for the
                   11140: classes where the selector is available (invokable).
1.20      pazsan   11141: 
1.78      anton    11142: This structure means that interface selectors have to perform one
                   11143: indirection more than class selectors to find their method. Their body
                   11144: contains the interface map pointer offset in the class method map, and
                   11145: the method offset in the interface method map. The
                   11146: @code{does>} action for an interface selector is, basically:
1.20      pazsan   11147: 
                   11148: @example
1.78      anton    11149: ( object selector-body )
                   11150: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   11151: swap object-map @@ + @@ ( object selector-body map )
                   11152: swap selector-offset @@ + @@ execute
1.20      pazsan   11153: @end example
                   11154: 
1.78      anton    11155: where @code{object-map} and @code{selector-offset} are
                   11156: first fields and generate no code.
1.20      pazsan   11157: 
1.78      anton    11158: As a concrete example, consider the following code:
1.20      pazsan   11159: 
                   11160: @example
1.78      anton    11161: interface
                   11162:   selector if1sel1
                   11163:   selector if1sel2
                   11164: end-interface if1
1.20      pazsan   11165: 
1.78      anton    11166: object class
                   11167:   if1 implementation
                   11168:   selector cl1sel1
                   11169:   cell% inst-var cl1iv1
1.20      pazsan   11170: 
1.78      anton    11171: ' m1 overrides construct
                   11172: ' m2 overrides if1sel1
                   11173: ' m3 overrides if1sel2
                   11174: ' m4 overrides cl1sel2
                   11175: end-class cl1
1.20      pazsan   11176: 
1.78      anton    11177: create obj1 object dict-new drop
                   11178: create obj2 cl1    dict-new drop
                   11179: @end example
1.20      pazsan   11180: 
1.78      anton    11181: The data structure created by this code (including the data structure
                   11182: for @code{object}) is shown in the
                   11183: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
                   11184: @comment TODO add this diagram..
1.20      pazsan   11185: 
1.78      anton    11186: @node Objects Glossary,  , Objects Implementation, Objects
                   11187: @subsubsection @file{objects.fs} Glossary
                   11188: @cindex @file{objects.fs} Glossary
1.20      pazsan   11189: 
                   11190: 
1.78      anton    11191: doc---objects-bind
                   11192: doc---objects-<bind>
                   11193: doc---objects-bind'
                   11194: doc---objects-[bind]
                   11195: doc---objects-class
                   11196: doc---objects-class->map
                   11197: doc---objects-class-inst-size
                   11198: doc---objects-class-override!
1.79      anton    11199: doc---objects-class-previous
                   11200: doc---objects-class>order
1.78      anton    11201: doc---objects-construct
                   11202: doc---objects-current'
                   11203: doc---objects-[current]
                   11204: doc---objects-current-interface
                   11205: doc---objects-dict-new
                   11206: doc---objects-end-class
                   11207: doc---objects-end-class-noname
                   11208: doc---objects-end-interface
                   11209: doc---objects-end-interface-noname
                   11210: doc---objects-end-methods
                   11211: doc---objects-exitm
                   11212: doc---objects-heap-new
                   11213: doc---objects-implementation
                   11214: doc---objects-init-object
                   11215: doc---objects-inst-value
                   11216: doc---objects-inst-var
                   11217: doc---objects-interface
                   11218: doc---objects-m:
                   11219: doc---objects-:m
                   11220: doc---objects-;m
                   11221: doc---objects-method
                   11222: doc---objects-methods
                   11223: doc---objects-object
                   11224: doc---objects-overrides
                   11225: doc---objects-[parent]
                   11226: doc---objects-print
                   11227: doc---objects-protected
                   11228: doc---objects-public
                   11229: doc---objects-selector
                   11230: doc---objects-this
                   11231: doc---objects-<to-inst>
                   11232: doc---objects-[to-inst]
                   11233: doc---objects-to-this
                   11234: doc---objects-xt-new
1.20      pazsan   11235: 
                   11236: 
1.78      anton    11237: @c -------------------------------------------------------------
                   11238: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   11239: @subsection The @file{oof.fs} model
                   11240: @cindex oof
                   11241: @cindex object-oriented programming
1.20      pazsan   11242: 
1.78      anton    11243: @cindex @file{objects.fs}
                   11244: @cindex @file{oof.fs}
1.20      pazsan   11245: 
1.78      anton    11246: This section describes the @file{oof.fs} package.
1.20      pazsan   11247: 
1.78      anton    11248: The package described in this section has been used in bigFORTH since 1991, and
                   11249: used for two large applications: a chromatographic system used to
                   11250: create new medicaments, and a graphic user interface library (MINOS).
1.20      pazsan   11251: 
1.78      anton    11252: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   11253: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   11254: 10(2), 1994.
1.20      pazsan   11255: 
1.78      anton    11256: @menu
                   11257: * Properties of the OOF model::  
                   11258: * Basic OOF Usage::             
                   11259: * The OOF base class::          
                   11260: * Class Declaration::           
                   11261: * Class Implementation::        
                   11262: @end menu
1.20      pazsan   11263: 
1.78      anton    11264: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   11265: @subsubsection Properties of the @file{oof.fs} model
                   11266: @cindex @file{oof.fs} properties
1.20      pazsan   11267: 
1.78      anton    11268: @itemize @bullet
                   11269: @item
                   11270: This model combines object oriented programming with information
                   11271: hiding. It helps you writing large application, where scoping is
                   11272: necessary, because it provides class-oriented scoping.
1.20      pazsan   11273: 
1.78      anton    11274: @item
                   11275: Named objects, object pointers, and object arrays can be created,
                   11276: selector invocation uses the ``object selector'' syntax. Selector invocation
                   11277: to objects and/or selectors on the stack is a bit less convenient, but
                   11278: possible.
1.44      crook    11279: 
1.78      anton    11280: @item
                   11281: Selector invocation and instance variable usage of the active object is
                   11282: straightforward, since both make use of the active object.
1.44      crook    11283: 
1.78      anton    11284: @item
                   11285: Late binding is efficient and easy to use.
1.20      pazsan   11286: 
1.78      anton    11287: @item
                   11288: State-smart objects parse selectors. However, extensibility is provided
                   11289: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20      pazsan   11290: 
1.78      anton    11291: @item
                   11292: An implementation in ANS Forth is available.
1.20      pazsan   11293: 
1.78      anton    11294: @end itemize
1.23      crook    11295: 
                   11296: 
1.78      anton    11297: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   11298: @subsubsection Basic @file{oof.fs} Usage
                   11299: @cindex @file{oof.fs} usage
1.23      crook    11300: 
1.78      anton    11301: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23      crook    11302: 
1.78      anton    11303: You can define a class for graphical objects like this:
1.23      crook    11304: 
1.78      anton    11305: @cindex @code{class} usage
                   11306: @cindex @code{class;} usage
                   11307: @cindex @code{method} usage
                   11308: @example
                   11309: object class graphical \ "object" is the parent class
1.139     pazsan   11310:   method draw ( x y -- )
1.78      anton    11311: class;
                   11312: @end example
1.23      crook    11313: 
1.78      anton    11314: This code defines a class @code{graphical} with an
                   11315: operation @code{draw}.  We can perform the operation
                   11316: @code{draw} on any @code{graphical} object, e.g.:
1.23      crook    11317: 
1.78      anton    11318: @example
                   11319: 100 100 t-rex draw
                   11320: @end example
1.23      crook    11321: 
1.78      anton    11322: @noindent
                   11323: where @code{t-rex} is an object or object pointer, created with e.g.
                   11324: @code{graphical : t-rex}.
1.23      crook    11325: 
1.78      anton    11326: @cindex abstract class
                   11327: How do we create a graphical object? With the present definitions,
                   11328: we cannot create a useful graphical object. The class
                   11329: @code{graphical} describes graphical objects in general, but not
                   11330: any concrete graphical object type (C++ users would call it an
                   11331: @emph{abstract class}); e.g., there is no method for the selector
                   11332: @code{draw} in the class @code{graphical}.
1.23      crook    11333: 
1.78      anton    11334: For concrete graphical objects, we define child classes of the
                   11335: class @code{graphical}, e.g.:
1.23      crook    11336: 
1.78      anton    11337: @example
                   11338: graphical class circle \ "graphical" is the parent class
                   11339:   cell var circle-radius
                   11340: how:
                   11341:   : draw ( x y -- )
                   11342:     circle-radius @@ draw-circle ;
1.23      crook    11343: 
1.139     pazsan   11344:   : init ( n-radius -- )
1.78      anton    11345:     circle-radius ! ;
                   11346: class;
                   11347: @end example
1.1       anton    11348: 
1.78      anton    11349: Here we define a class @code{circle} as a child of @code{graphical},
                   11350: with a field @code{circle-radius}; it defines new methods for the
                   11351: selectors @code{draw} and @code{init} (@code{init} is defined in
                   11352: @code{object}, the parent class of @code{graphical}).
1.1       anton    11353: 
1.78      anton    11354: Now we can create a circle in the dictionary with:
1.1       anton    11355: 
1.78      anton    11356: @example
                   11357: 50 circle : my-circle
                   11358: @end example
1.21      crook    11359: 
1.78      anton    11360: @noindent
                   11361: @code{:} invokes @code{init}, thus initializing the field
                   11362: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   11363: with:
1.1       anton    11364: 
1.78      anton    11365: @example
                   11366: 100 100 my-circle draw
                   11367: @end example
1.1       anton    11368: 
1.78      anton    11369: @cindex selector invocation, restrictions
                   11370: @cindex class definition, restrictions
                   11371: Note: You can only invoke a selector if the receiving object belongs to
                   11372: the class where the selector was defined or one of its descendents;
                   11373: e.g., you can invoke @code{draw} only for objects belonging to
                   11374: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   11375: mechanism will check if you try to invoke a selector that is not
                   11376: defined in this class hierarchy, so you'll get an error at compilation
                   11377: time.
1.1       anton    11378: 
                   11379: 
1.78      anton    11380: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   11381: @subsubsection The @file{oof.fs} base class
                   11382: @cindex @file{oof.fs} base class
1.1       anton    11383: 
1.78      anton    11384: When you define a class, you have to specify a parent class.  So how do
                   11385: you start defining classes? There is one class available from the start:
                   11386: @code{object}. You have to use it as ancestor for all classes. It is the
                   11387: only class that has no parent. Classes are also objects, except that
                   11388: they don't have instance variables; class manipulation such as
                   11389: inheritance or changing definitions of a class is handled through
                   11390: selectors of the class @code{object}.
1.1       anton    11391: 
1.78      anton    11392: @code{object} provides a number of selectors:
1.1       anton    11393: 
1.78      anton    11394: @itemize @bullet
                   11395: @item
                   11396: @code{class} for subclassing, @code{definitions} to add definitions
                   11397: later on, and @code{class?} to get type informations (is the class a
                   11398: subclass of the class passed on the stack?).
1.1       anton    11399: 
1.78      anton    11400: doc---object-class
                   11401: doc---object-definitions
                   11402: doc---object-class?
1.1       anton    11403: 
                   11404: 
1.26      crook    11405: @item
1.78      anton    11406: @code{init} and @code{dispose} as constructor and destructor of the
                   11407: object. @code{init} is invocated after the object's memory is allocated,
                   11408: while @code{dispose} also handles deallocation. Thus if you redefine
                   11409: @code{dispose}, you have to call the parent's dispose with @code{super
                   11410: dispose}, too.
                   11411: 
                   11412: doc---object-init
                   11413: doc---object-dispose
                   11414: 
1.1       anton    11415: 
1.26      crook    11416: @item
1.78      anton    11417: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   11418: @code{[]} to create named and unnamed objects and object arrays or
                   11419: object pointers.
                   11420: 
                   11421: doc---object-new
                   11422: doc---object-new[]
                   11423: doc---object-:
                   11424: doc---object-ptr
                   11425: doc---object-asptr
                   11426: doc---object-[]
                   11427: 
1.1       anton    11428: 
1.26      crook    11429: @item
1.78      anton    11430: @code{::} and @code{super} for explicit scoping. You should use explicit
                   11431: scoping only for super classes or classes with the same set of instance
                   11432: variables. Explicitly-scoped selectors use early binding.
1.21      crook    11433: 
1.78      anton    11434: doc---object-::
                   11435: doc---object-super
1.21      crook    11436: 
                   11437: 
1.26      crook    11438: @item
1.78      anton    11439: @code{self} to get the address of the object
1.21      crook    11440: 
1.78      anton    11441: doc---object-self
1.21      crook    11442: 
                   11443: 
1.78      anton    11444: @item
                   11445: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   11446: pointers and instance defers.
1.21      crook    11447: 
1.78      anton    11448: doc---object-bind
                   11449: doc---object-bound
                   11450: doc---object-link
                   11451: doc---object-is
1.21      crook    11452: 
                   11453: 
1.78      anton    11454: @item
                   11455: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   11456: form the stack, and @code{postpone} to generate selector invocation code.
1.21      crook    11457: 
1.78      anton    11458: doc---object-'
                   11459: doc---object-postpone
1.21      crook    11460: 
                   11461: 
1.78      anton    11462: @item
                   11463: @code{with} and @code{endwith} to select the active object from the
                   11464: stack, and enable its scope. Using @code{with} and @code{endwith}
                   11465: also allows you to create code using selector @code{postpone} without being
                   11466: trapped by the state-smart objects.
1.21      crook    11467: 
1.78      anton    11468: doc---object-with
                   11469: doc---object-endwith
1.21      crook    11470: 
                   11471: 
1.78      anton    11472: @end itemize
1.21      crook    11473: 
1.78      anton    11474: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   11475: @subsubsection Class Declaration
                   11476: @cindex class declaration
1.21      crook    11477: 
1.78      anton    11478: @itemize @bullet
                   11479: @item
                   11480: Instance variables
1.21      crook    11481: 
1.78      anton    11482: doc---oof-var
1.21      crook    11483: 
                   11484: 
1.78      anton    11485: @item
                   11486: Object pointers
1.21      crook    11487: 
1.78      anton    11488: doc---oof-ptr
                   11489: doc---oof-asptr
1.21      crook    11490: 
                   11491: 
1.78      anton    11492: @item
                   11493: Instance defers
1.21      crook    11494: 
1.78      anton    11495: doc---oof-defer
1.21      crook    11496: 
                   11497: 
1.78      anton    11498: @item
                   11499: Method selectors
1.21      crook    11500: 
1.78      anton    11501: doc---oof-early
                   11502: doc---oof-method
1.21      crook    11503: 
                   11504: 
1.78      anton    11505: @item
                   11506: Class-wide variables
1.21      crook    11507: 
1.78      anton    11508: doc---oof-static
1.21      crook    11509: 
                   11510: 
1.78      anton    11511: @item
                   11512: End declaration
1.1       anton    11513: 
1.78      anton    11514: doc---oof-how:
                   11515: doc---oof-class;
1.21      crook    11516: 
                   11517: 
1.78      anton    11518: @end itemize
1.21      crook    11519: 
1.78      anton    11520: @c -------------------------------------------------------------
                   11521: @node Class Implementation,  , Class Declaration, OOF
                   11522: @subsubsection Class Implementation
                   11523: @cindex class implementation
1.21      crook    11524: 
1.78      anton    11525: @c -------------------------------------------------------------
                   11526: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   11527: @subsection The @file{mini-oof.fs} model
                   11528: @cindex mini-oof
1.21      crook    11529: 
1.78      anton    11530: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79      anton    11531: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78      anton    11532: and reduces to the bare minimum of features. This is based on a posting
                   11533: of Bernd Paysan in comp.lang.forth.
1.21      crook    11534: 
1.78      anton    11535: @menu
                   11536: * Basic Mini-OOF Usage::        
                   11537: * Mini-OOF Example::            
                   11538: * Mini-OOF Implementation::     
                   11539: @end menu
1.21      crook    11540: 
1.78      anton    11541: @c -------------------------------------------------------------
                   11542: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
                   11543: @subsubsection Basic @file{mini-oof.fs} Usage
                   11544: @cindex mini-oof usage
1.21      crook    11545: 
1.78      anton    11546: There is a base class (@code{class}, which allocates one cell for the
                   11547: object pointer) plus seven other words: to define a method, a variable,
                   11548: a class; to end a class, to resolve binding, to allocate an object and
                   11549: to compile a class method.
                   11550: @comment TODO better description of the last one
1.26      crook    11551: 
1.21      crook    11552: 
1.78      anton    11553: doc-object
                   11554: doc-method
                   11555: doc-var
                   11556: doc-class
                   11557: doc-end-class
                   11558: doc-defines
                   11559: doc-new
                   11560: doc-::
1.21      crook    11561: 
                   11562: 
                   11563: 
1.78      anton    11564: @c -------------------------------------------------------------
                   11565: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   11566: @subsubsection Mini-OOF Example
                   11567: @cindex mini-oof example
1.1       anton    11568: 
1.78      anton    11569: A short example shows how to use this package. This example, in slightly
                   11570: extended form, is supplied as @file{moof-exm.fs}
                   11571: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20      pazsan   11572: 
1.26      crook    11573: @example
1.78      anton    11574: object class
                   11575:   method init
                   11576:   method draw
                   11577: end-class graphical
1.26      crook    11578: @end example
1.20      pazsan   11579: 
1.78      anton    11580: This code defines a class @code{graphical} with an
                   11581: operation @code{draw}.  We can perform the operation
                   11582: @code{draw} on any @code{graphical} object, e.g.:
1.20      pazsan   11583: 
1.26      crook    11584: @example
1.78      anton    11585: 100 100 t-rex draw
1.26      crook    11586: @end example
1.12      anton    11587: 
1.78      anton    11588: where @code{t-rex} is an object or object pointer, created with e.g.
                   11589: @code{graphical new Constant t-rex}.
1.12      anton    11590: 
1.78      anton    11591: For concrete graphical objects, we define child classes of the
                   11592: class @code{graphical}, e.g.:
1.12      anton    11593: 
1.26      crook    11594: @example
                   11595: graphical class
1.78      anton    11596:   cell var circle-radius
                   11597: end-class circle \ "graphical" is the parent class
1.12      anton    11598: 
1.78      anton    11599: :noname ( x y -- )
                   11600:   circle-radius @@ draw-circle ; circle defines draw
                   11601: :noname ( r -- )
                   11602:   circle-radius ! ; circle defines init
                   11603: @end example
1.12      anton    11604: 
1.78      anton    11605: There is no implicit init method, so we have to define one. The creation
                   11606: code of the object now has to call init explicitely.
1.21      crook    11607: 
1.78      anton    11608: @example
                   11609: circle new Constant my-circle
                   11610: 50 my-circle init
1.12      anton    11611: @end example
                   11612: 
1.78      anton    11613: It is also possible to add a function to create named objects with
                   11614: automatic call of @code{init}, given that all objects have @code{init}
                   11615: on the same place:
1.38      anton    11616: 
1.78      anton    11617: @example
                   11618: : new: ( .. o "name" -- )
                   11619:     new dup Constant init ;
                   11620: 80 circle new: large-circle
                   11621: @end example
1.12      anton    11622: 
1.78      anton    11623: We can draw this new circle at (100,100) with:
1.12      anton    11624: 
1.78      anton    11625: @example
                   11626: 100 100 my-circle draw
                   11627: @end example
1.12      anton    11628: 
1.78      anton    11629: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
                   11630: @subsubsection @file{mini-oof.fs} Implementation
1.12      anton    11631: 
1.78      anton    11632: Object-oriented systems with late binding typically use a
                   11633: ``vtable''-approach: the first variable in each object is a pointer to a
                   11634: table, which contains the methods as function pointers. The vtable
                   11635: may also contain other information.
1.12      anton    11636: 
1.79      anton    11637: So first, let's declare selectors:
1.37      anton    11638: 
                   11639: @example
1.79      anton    11640: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
1.78      anton    11641:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
                   11642: @end example
1.37      anton    11643: 
1.79      anton    11644: During selector declaration, the number of selectors and instance
                   11645: variables is on the stack (in address units). @code{method} creates one
                   11646: selector and increments the selector number. To execute a selector, it
1.78      anton    11647: takes the object, fetches the vtable pointer, adds the offset, and
1.79      anton    11648: executes the method @i{xt} stored there. Each selector takes the object
                   11649: it is invoked with as top of stack parameter; it passes the parameters
                   11650: (including the object) unchanged to the appropriate method which should
1.78      anton    11651: consume that object.
1.37      anton    11652: 
1.78      anton    11653: Now, we also have to declare instance variables
1.37      anton    11654: 
1.78      anton    11655: @example
1.79      anton    11656: : var ( m v size "name" -- m v' ) Create  over , +
1.78      anton    11657:   DOES> ( o -- addr ) @@ + ;
1.37      anton    11658: @end example
                   11659: 
1.78      anton    11660: As before, a word is created with the current offset. Instance
                   11661: variables can have different sizes (cells, floats, doubles, chars), so
                   11662: all we do is take the size and add it to the offset. If your machine
                   11663: has alignment restrictions, put the proper @code{aligned} or
                   11664: @code{faligned} before the variable, to adjust the variable
                   11665: offset. That's why it is on the top of stack.
1.37      anton    11666: 
1.78      anton    11667: We need a starting point (the base object) and some syntactic sugar:
1.37      anton    11668: 
1.78      anton    11669: @example
                   11670: Create object  1 cells , 2 cells ,
1.79      anton    11671: : class ( class -- class selectors vars ) dup 2@@ ;
1.78      anton    11672: @end example
1.12      anton    11673: 
1.78      anton    11674: For inheritance, the vtable of the parent object has to be
                   11675: copied when a new, derived class is declared. This gives all the
                   11676: methods of the parent class, which can be overridden, though.
1.12      anton    11677: 
1.78      anton    11678: @example
1.79      anton    11679: : end-class  ( class selectors vars "name" -- )
1.78      anton    11680:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   11681:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
                   11682: @end example
1.12      anton    11683: 
1.78      anton    11684: The first line creates the vtable, initialized with
                   11685: @code{noop}s. The second line is the inheritance mechanism, it
                   11686: copies the xts from the parent vtable.
1.12      anton    11687: 
1.78      anton    11688: We still have no way to define new methods, let's do that now:
1.12      anton    11689: 
1.26      crook    11690: @example
1.79      anton    11691: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78      anton    11692: @end example
1.12      anton    11693: 
1.78      anton    11694: To allocate a new object, we need a word, too:
1.12      anton    11695: 
1.78      anton    11696: @example
                   11697: : new ( class -- o )  here over @@ allot swap over ! ;
1.12      anton    11698: @end example
                   11699: 
1.78      anton    11700: Sometimes derived classes want to access the method of the
                   11701: parent object. There are two ways to achieve this with Mini-OOF:
                   11702: first, you could use named words, and second, you could look up the
                   11703: vtable of the parent object.
1.12      anton    11704: 
1.78      anton    11705: @example
                   11706: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
                   11707: @end example
1.12      anton    11708: 
                   11709: 
1.78      anton    11710: Nothing can be more confusing than a good example, so here is
                   11711: one. First let's declare a text object (called
                   11712: @code{button}), that stores text and position:
1.12      anton    11713: 
1.78      anton    11714: @example
                   11715: object class
                   11716:   cell var text
                   11717:   cell var len
                   11718:   cell var x
                   11719:   cell var y
                   11720:   method init
                   11721:   method draw
                   11722: end-class button
                   11723: @end example
1.12      anton    11724: 
1.78      anton    11725: @noindent
                   11726: Now, implement the two methods, @code{draw} and @code{init}:
1.21      crook    11727: 
1.26      crook    11728: @example
1.78      anton    11729: :noname ( o -- )
                   11730:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
                   11731:  button defines draw
                   11732: :noname ( addr u o -- )
                   11733:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
                   11734:  button defines init
1.26      crook    11735: @end example
1.12      anton    11736: 
1.78      anton    11737: @noindent
                   11738: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79      anton    11739: new data and no new selectors:
1.78      anton    11740: 
                   11741: @example
                   11742: button class
                   11743: end-class bold-button
1.12      anton    11744: 
1.78      anton    11745: : bold   27 emit ." [1m" ;
                   11746: : normal 27 emit ." [0m" ;
                   11747: @end example
1.1       anton    11748: 
1.78      anton    11749: @noindent
                   11750: The class @code{bold-button} has a different draw method to
                   11751: @code{button}, but the new method is defined in terms of the draw method
                   11752: for @code{button}:
1.20      pazsan   11753: 
1.78      anton    11754: @example
                   11755: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   11756: @end example
1.21      crook    11757: 
1.78      anton    11758: @noindent
1.79      anton    11759: Finally, create two objects and apply selectors:
1.21      crook    11760: 
1.26      crook    11761: @example
1.78      anton    11762: button new Constant foo
                   11763: s" thin foo" foo init
                   11764: page
                   11765: foo draw
                   11766: bold-button new Constant bar
                   11767: s" fat bar" bar init
                   11768: 1 bar y !
                   11769: bar draw
1.26      crook    11770: @end example
1.21      crook    11771: 
                   11772: 
1.78      anton    11773: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
                   11774: @subsection Comparison with other object models
                   11775: @cindex comparison of object models
                   11776: @cindex object models, comparison
                   11777: 
                   11778: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   11779: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   11780: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   11781: relation of the object models described here to two well-known and two
                   11782: closely-related (by the use of method maps) models.  Andras Zsoter
                   11783: helped us with this section.
                   11784: 
                   11785: @cindex Neon model
                   11786: The most popular model currently seems to be the Neon model (see
                   11787: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   11788: 1997) by Andrew McKewan) but this model has a number of limitations
                   11789: @footnote{A longer version of this critique can be
                   11790: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   11791: Dimensions, May 1997) by Anton Ertl.}:
                   11792: 
                   11793: @itemize @bullet
                   11794: @item
                   11795: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
                   11796: to pass objects on the stack.
1.21      crook    11797: 
1.78      anton    11798: @item
                   11799: It requires that the selector parses the input stream (at
1.79      anton    11800: compile time); this leads to reduced extensibility and to bugs that are
1.78      anton    11801: hard to find.
1.21      crook    11802: 
1.78      anton    11803: @item
1.79      anton    11804: It allows using every selector on every object; this eliminates the
                   11805: need for interfaces, but makes it harder to create efficient
                   11806: implementations.
1.78      anton    11807: @end itemize
1.21      crook    11808: 
1.78      anton    11809: @cindex Pountain's object-oriented model
                   11810: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   11811: Press, London, 1987) by Dick Pountain. However, it is not really about
                   11812: object-oriented programming, because it hardly deals with late
                   11813: binding. Instead, it focuses on features like information hiding and
                   11814: overloading that are characteristic of modular languages like Ada (83).
1.26      crook    11815: 
1.78      anton    11816: @cindex Zsoter's object-oriented model
1.79      anton    11817: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
                   11818: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
                   11819: describes a model that makes heavy use of an active object (like
                   11820: @code{this} in @file{objects.fs}): The active object is not only used
                   11821: for accessing all fields, but also specifies the receiving object of
                   11822: every selector invocation; you have to change the active object
                   11823: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
                   11824: changes more or less implicitly at @code{m: ... ;m}. Such a change at
                   11825: the method entry point is unnecessary with Zsoter's model, because the
                   11826: receiving object is the active object already. On the other hand, the
                   11827: explicit change is absolutely necessary in that model, because otherwise
                   11828: no one could ever change the active object. An ANS Forth implementation
                   11829: of this model is available through
                   11830: @uref{http://www.forth.org/oopf.html}.
1.21      crook    11831: 
1.78      anton    11832: @cindex @file{oof.fs}, differences to other models
                   11833: The @file{oof.fs} model combines information hiding and overloading
                   11834: resolution (by keeping names in various word lists) with object-oriented
                   11835: programming. It sets the active object implicitly on method entry, but
                   11836: also allows explicit changing (with @code{>o...o>} or with
                   11837: @code{with...endwith}). It uses parsing and state-smart objects and
                   11838: classes for resolving overloading and for early binding: the object or
                   11839: class parses the selector and determines the method from this. If the
                   11840: selector is not parsed by an object or class, it performs a call to the
                   11841: selector for the active object (late binding), like Zsoter's model.
                   11842: Fields are always accessed through the active object. The big
                   11843: disadvantage of this model is the parsing and the state-smartness, which
                   11844: reduces extensibility and increases the opportunities for subtle bugs;
                   11845: essentially, you are only safe if you never tick or @code{postpone} an
                   11846: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21      crook    11847: 
1.78      anton    11848: @cindex @file{mini-oof.fs}, differences to other models
                   11849: The @file{mini-oof.fs} model is quite similar to a very stripped-down
                   11850: version of the @file{objects.fs} model, but syntactically it is a
                   11851: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21      crook    11852: 
                   11853: 
1.78      anton    11854: @c -------------------------------------------------------------
1.150     anton    11855: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78      anton    11856: @section Programming Tools
                   11857: @cindex programming tools
1.21      crook    11858: 
1.78      anton    11859: @c !! move this and assembler down below OO stuff.
1.21      crook    11860: 
1.78      anton    11861: @menu
1.150     anton    11862: * Examining::                   Data and Code.
                   11863: * Forgetting words::            Usually before reloading.
1.78      anton    11864: * Debugging::                   Simple and quick.
                   11865: * Assertions::                  Making your programs self-checking.
                   11866: * Singlestep Debugger::         Executing your program word by word.
                   11867: @end menu
1.21      crook    11868: 
1.78      anton    11869: @node Examining, Forgetting words, Programming Tools, Programming Tools
                   11870: @subsection Examining data and code
                   11871: @cindex examining data and code
                   11872: @cindex data examination
                   11873: @cindex code examination
1.44      crook    11874: 
1.78      anton    11875: The following words inspect the stack non-destructively:
1.21      crook    11876: 
1.78      anton    11877: doc-.s
                   11878: doc-f.s
1.158     anton    11879: doc-maxdepth-.s
1.44      crook    11880: 
1.78      anton    11881: There is a word @code{.r} but it does @i{not} display the return stack!
                   11882: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21      crook    11883: 
1.78      anton    11884: doc-depth
                   11885: doc-fdepth
                   11886: doc-clearstack
1.124     anton    11887: doc-clearstacks
1.21      crook    11888: 
1.78      anton    11889: The following words inspect memory.
1.21      crook    11890: 
1.78      anton    11891: doc-?
                   11892: doc-dump
1.21      crook    11893: 
1.78      anton    11894: And finally, @code{see} allows to inspect code:
1.21      crook    11895: 
1.78      anton    11896: doc-see
                   11897: doc-xt-see
1.111     anton    11898: doc-simple-see
                   11899: doc-simple-see-range
1.182     anton    11900: doc-see-code
                   11901: doc-see-code-range
1.21      crook    11902: 
1.78      anton    11903: @node Forgetting words, Debugging, Examining, Programming Tools
                   11904: @subsection Forgetting words
                   11905: @cindex words, forgetting
                   11906: @cindex forgeting words
1.21      crook    11907: 
1.78      anton    11908: @c  anton: other, maybe better places for this subsection: Defining Words;
                   11909: @c  Dictionary allocation.  At least a reference should be there.
1.21      crook    11910: 
1.78      anton    11911: Forth allows you to forget words (and everything that was alloted in the
                   11912: dictonary after them) in a LIFO manner.
1.21      crook    11913: 
1.78      anton    11914: doc-marker
1.21      crook    11915: 
1.78      anton    11916: The most common use of this feature is during progam development: when
                   11917: you change a source file, forget all the words it defined and load it
                   11918: again (since you also forget everything defined after the source file
                   11919: was loaded, you have to reload that, too).  Note that effects like
                   11920: storing to variables and destroyed system words are not undone when you
                   11921: forget words.  With a system like Gforth, that is fast enough at
                   11922: starting up and compiling, I find it more convenient to exit and restart
                   11923: Gforth, as this gives me a clean slate.
1.21      crook    11924: 
1.78      anton    11925: Here's an example of using @code{marker} at the start of a source file
                   11926: that you are debugging; it ensures that you only ever have one copy of
                   11927: the file's definitions compiled at any time:
1.21      crook    11928: 
1.78      anton    11929: @example
                   11930: [IFDEF] my-code
                   11931:     my-code
                   11932: [ENDIF]
1.26      crook    11933: 
1.78      anton    11934: marker my-code
                   11935: init-included-files
1.21      crook    11936: 
1.78      anton    11937: \ .. definitions start here
                   11938: \ .
                   11939: \ .
                   11940: \ end
                   11941: @end example
1.21      crook    11942: 
1.26      crook    11943: 
1.78      anton    11944: @node Debugging, Assertions, Forgetting words, Programming Tools
                   11945: @subsection Debugging
                   11946: @cindex debugging
1.21      crook    11947: 
1.78      anton    11948: Languages with a slow edit/compile/link/test development loop tend to
                   11949: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21      crook    11950: 
1.78      anton    11951: A much better (faster) way in fast-compiling languages is to add
                   11952: printing code at well-selected places, let the program run, look at
                   11953: the output, see where things went wrong, add more printing code, etc.,
                   11954: until the bug is found.
1.21      crook    11955: 
1.78      anton    11956: The simple debugging aids provided in @file{debugs.fs}
                   11957: are meant to support this style of debugging.
1.21      crook    11958: 
1.78      anton    11959: The word @code{~~} prints debugging information (by default the source
                   11960: location and the stack contents). It is easy to insert. If you use Emacs
                   11961: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   11962: query-replace them with nothing). The deferred words
1.101     anton    11963: @code{printdebugdata} and @code{.debugline} control the output of
1.78      anton    11964: @code{~~}. The default source location output format works well with
                   11965: Emacs' compilation mode, so you can step through the program at the
                   11966: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   11967: is that you can step in any direction and you know where the crash has
                   11968: happened or where the strange data has occurred).
1.21      crook    11969: 
1.78      anton    11970: doc-~~
                   11971: doc-printdebugdata
1.101     anton    11972: doc-.debugline
1.203     anton    11973: doc-debug-fid
1.21      crook    11974: 
1.106     anton    11975: @cindex filenames in @code{~~} output
                   11976: @code{~~} (and assertions) will usually print the wrong file name if a
                   11977: marker is executed in the same file after their occurance.  They will
                   11978: print @samp{*somewhere*} as file name if a marker is executed in the
                   11979: same file before their occurance.
                   11980: 
                   11981: 
1.78      anton    11982: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   11983: @subsection Assertions
                   11984: @cindex assertions
1.21      crook    11985: 
1.78      anton    11986: It is a good idea to make your programs self-checking, especially if you
                   11987: make an assumption that may become invalid during maintenance (for
                   11988: example, that a certain field of a data structure is never zero). Gforth
                   11989: supports @dfn{assertions} for this purpose. They are used like this:
1.21      crook    11990: 
                   11991: @example
1.78      anton    11992: assert( @i{flag} )
1.26      crook    11993: @end example
                   11994: 
1.78      anton    11995: The code between @code{assert(} and @code{)} should compute a flag, that
                   11996: should be true if everything is alright and false otherwise. It should
                   11997: not change anything else on the stack. The overall stack effect of the
                   11998: assertion is @code{( -- )}. E.g.
1.21      crook    11999: 
1.26      crook    12000: @example
1.78      anton    12001: assert( 1 1 + 2 = ) \ what we learn in school
                   12002: assert( dup 0<> ) \ assert that the top of stack is not zero
                   12003: assert( false ) \ this code should not be reached
1.21      crook    12004: @end example
                   12005: 
1.78      anton    12006: The need for assertions is different at different times. During
                   12007: debugging, we want more checking, in production we sometimes care more
                   12008: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   12009: becomes a comment. Depending on the importance of an assertion and the
                   12010: time it takes to check it, you may want to turn off some assertions and
                   12011: keep others turned on. Gforth provides several levels of assertions for
                   12012: this purpose:
                   12013: 
                   12014: 
                   12015: doc-assert0(
                   12016: doc-assert1(
                   12017: doc-assert2(
                   12018: doc-assert3(
                   12019: doc-assert(
                   12020: doc-)
1.21      crook    12021: 
                   12022: 
1.78      anton    12023: The variable @code{assert-level} specifies the highest assertions that
                   12024: are turned on. I.e., at the default @code{assert-level} of one,
                   12025: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   12026: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26      crook    12027: 
1.78      anton    12028: The value of @code{assert-level} is evaluated at compile-time, not at
                   12029: run-time. Therefore you cannot turn assertions on or off at run-time;
                   12030: you have to set the @code{assert-level} appropriately before compiling a
                   12031: piece of code. You can compile different pieces of code at different
                   12032: @code{assert-level}s (e.g., a trusted library at level 1 and
                   12033: newly-written code at level 3).
1.26      crook    12034: 
                   12035: 
1.78      anton    12036: doc-assert-level
1.26      crook    12037: 
                   12038: 
1.78      anton    12039: If an assertion fails, a message compatible with Emacs' compilation mode
                   12040: is produced and the execution is aborted (currently with @code{ABORT"}.
                   12041: If there is interest, we will introduce a special throw code. But if you
                   12042: intend to @code{catch} a specific condition, using @code{throw} is
                   12043: probably more appropriate than an assertion).
1.106     anton    12044: 
                   12045: @cindex filenames in assertion output
                   12046: Assertions (and @code{~~}) will usually print the wrong file name if a
                   12047: marker is executed in the same file after their occurance.  They will
                   12048: print @samp{*somewhere*} as file name if a marker is executed in the
                   12049: same file before their occurance.
1.44      crook    12050: 
1.78      anton    12051: Definitions in ANS Forth for these assertion words are provided
                   12052: in @file{compat/assert.fs}.
1.26      crook    12053: 
1.44      crook    12054: 
1.78      anton    12055: @node Singlestep Debugger,  , Assertions, Programming Tools
                   12056: @subsection Singlestep Debugger
                   12057: @cindex singlestep Debugger
                   12058: @cindex debugging Singlestep
1.44      crook    12059: 
1.189     anton    12060: The singlestep debugger works only with the engine @code{gforth-itc}.
1.112     anton    12061: 
1.78      anton    12062: When you create a new word there's often the need to check whether it
                   12063: behaves correctly or not. You can do this by typing @code{dbg
                   12064: badword}. A debug session might look like this:
1.26      crook    12065: 
1.78      anton    12066: @example
                   12067: : badword 0 DO i . LOOP ;  ok
                   12068: 2 dbg badword 
                   12069: : badword  
                   12070: Scanning code...
1.44      crook    12071: 
1.78      anton    12072: Nesting debugger ready!
1.44      crook    12073: 
1.78      anton    12074: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   12075: 400D4740  8049F68 DO             -> [ 0 ] 
                   12076: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   12077: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   12078: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   12079: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   12080: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   12081: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   12082: 400D4758  804B384 ;              ->  ok
                   12083: @end example
1.21      crook    12084: 
1.78      anton    12085: Each line displayed is one step. You always have to hit return to
                   12086: execute the next word that is displayed. If you don't want to execute
                   12087: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   12088: an overview what keys are available:
1.44      crook    12089: 
1.78      anton    12090: @table @i
1.44      crook    12091: 
1.78      anton    12092: @item @key{RET}
                   12093: Next; Execute the next word.
1.21      crook    12094: 
1.78      anton    12095: @item n
                   12096: Nest; Single step through next word.
1.44      crook    12097: 
1.78      anton    12098: @item u
                   12099: Unnest; Stop debugging and execute rest of word. If we got to this word
                   12100: with nest, continue debugging with the calling word.
1.44      crook    12101: 
1.78      anton    12102: @item d
                   12103: Done; Stop debugging and execute rest.
1.21      crook    12104: 
1.78      anton    12105: @item s
                   12106: Stop; Abort immediately.
1.44      crook    12107: 
1.78      anton    12108: @end table
1.44      crook    12109: 
1.78      anton    12110: Debugging large application with this mechanism is very difficult, because
                   12111: you have to nest very deeply into the program before the interesting part
                   12112: begins. This takes a lot of time. 
1.26      crook    12113: 
1.78      anton    12114: To do it more directly put a @code{BREAK:} command into your source code.
                   12115: When program execution reaches @code{BREAK:} the single step debugger is
                   12116: invoked and you have all the features described above.
1.44      crook    12117: 
1.78      anton    12118: If you have more than one part to debug it is useful to know where the
                   12119: program has stopped at the moment. You can do this by the 
                   12120: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   12121: string is typed out when the ``breakpoint'' is reached.
1.44      crook    12122: 
1.26      crook    12123: 
1.78      anton    12124: doc-dbg
                   12125: doc-break:
                   12126: doc-break"
1.44      crook    12127: 
1.150     anton    12128: @c ------------------------------------------------------------
                   12129: @node C Interface, Assembler and Code Words, Programming Tools, Words
                   12130: @section C Interface
                   12131: @cindex C interface
                   12132: @cindex foreign language interface
                   12133: @cindex interface to C functions
                   12134: 
1.178     anton    12135: Note that the C interface is not yet complete; callbacks are missing,
                   12136: as well as a way of declaring structs, unions, and their fields.
1.150     anton    12137: 
                   12138: @menu
                   12139: * Calling C Functions::         
                   12140: * Declaring C Functions::       
1.180     anton    12141: * Calling C function pointers::  
1.196     anton    12142: * Defining library interfaces::  
                   12143: * Declaring OS-level libraries::  
1.150     anton    12144: * Callbacks::                   
1.178     anton    12145: * C interface internals::       
1.155     anton    12146: * Low-Level C Interface Words::  
1.150     anton    12147: @end menu
                   12148: 
1.151     pazsan   12149: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150     anton    12150: @subsection Calling C functions
1.155     anton    12151: @cindex C functions, calls to
                   12152: @cindex calling C functions
1.150     anton    12153: 
1.151     pazsan   12154: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150     anton    12155: can call it as follows: You push the arguments on the stack(s), and
                   12156: then call the word for the C function.  The arguments have to be
                   12157: pushed in the same order as the arguments appear in the C
                   12158: documentation (i.e., the first argument is deepest on the stack).
                   12159: Integer and pointer arguments have to be pushed on the data stack,
                   12160: floating-point arguments on the FP stack; these arguments are consumed
1.155     anton    12161: by the called C function.
1.150     anton    12162: 
1.155     anton    12163: On returning from the C function, the return value, if any, resides on
                   12164: the appropriate stack: an integer return value is pushed on the data
                   12165: stack, an FP return value on the FP stack, and a void return value
                   12166: results in not pushing anything.  Note that most C functions have a
                   12167: return value, even if that is often not used in C; in Forth, you have
                   12168: to @code{drop} this return value explicitly if you do not use it.
1.150     anton    12169: 
1.177     anton    12170: The C interface automatically converts between the C type and the
                   12171: Forth type as necessary, on a best-effort basis (in some cases, there
                   12172: may be some loss).
1.150     anton    12173: 
                   12174: As an example, consider the POSIX function @code{lseek()}:
                   12175: 
                   12176: @example
                   12177: off_t lseek(int fd, off_t offset, int whence);
                   12178: @end example
                   12179: 
                   12180: This function takes three integer arguments, and returns an integer
                   12181: argument, so a Forth call for setting the current file offset to the
                   12182: start of the file could look like this:
                   12183: 
                   12184: @example
                   12185: fd @@ 0 SEEK_SET lseek -1 = if
                   12186:   ... \ error handling
                   12187: then
                   12188: @end example
                   12189: 
                   12190: You might be worried that an @code{off_t} does not fit into a cell, so
                   12191: you could not pass larger offsets to lseek, and might get only a part
1.155     anton    12192: of the return values.  In that case, in your declaration of the
                   12193: function (@pxref{Declaring C Functions}) you should declare it to use
                   12194: double-cells for the off_t argument and return value, and maybe give
                   12195: the resulting Forth word a different name, like @code{dlseek}; the
                   12196: result could be called like this:
1.150     anton    12197: 
                   12198: @example
                   12199: fd @@ 0. SEEK_SET dlseek -1. d= if
                   12200:   ... \ error handling
                   12201: then
                   12202: @end example
                   12203: 
                   12204: Passing and returning structs or unions is currently not supported by
                   12205: our interface@footnote{If you know the calling convention of your C
                   12206: compiler, you usually can call such functions in some way, but that
                   12207: way is usually not portable between platforms, and sometimes not even
                   12208: between C compilers.}.
                   12209: 
1.177     anton    12210: Calling functions with a variable number of arguments (@emph{variadic}
                   12211: functions, e.g., @code{printf()}) is only supported by having you
                   12212: declare one function-calling word for each argument pattern, and
                   12213: calling the appropriate word for the desired pattern.
                   12214: 
1.150     anton    12215: 
1.155     anton    12216: 
1.180     anton    12217: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
1.150     anton    12218: @subsection Declaring C Functions
1.155     anton    12219: @cindex C functions, declarations
                   12220: @cindex declaring C functions
1.150     anton    12221: 
                   12222: Before you can call @code{lseek} or @code{dlseek}, you have to declare
1.177     anton    12223: it.  The declaration consists of two parts: 
                   12224: 
                   12225: @table @b
                   12226: 
                   12227: @item The C part
1.179     anton    12228: is the C declaration of the function, or more typically and portably,
                   12229: a C-style @code{#include} of a file that contains the declaration of
                   12230: the C function.
1.177     anton    12231: 
                   12232: @item The Forth part
                   12233: declares the Forth types of the parameters and the Forth word name
                   12234: corresponding to the C function.
                   12235: 
                   12236: @end table
                   12237: 
                   12238: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
                   12239: declarations are:
                   12240: 
                   12241: @example
                   12242: \c #define _FILE_OFFSET_BITS 64
                   12243: \c #include <sys/types.h>
                   12244: \c #include <unistd.h>
                   12245: c-function lseek lseek n n n -- n
                   12246: c-function dlseek lseek n d n -- d
                   12247: @end example
                   12248: 
1.178     anton    12249: The C part of the declarations is prefixed by @code{\c}, and the rest
1.177     anton    12250: of the line is ordinary C code.  You can use as many lines of C
                   12251: declarations as you like, and they are visible for all further
                   12252: function declarations.
                   12253: 
                   12254: The Forth part declares each interface word with @code{c-function},
                   12255: followed by the Forth name of the word, the C name of the called
                   12256: function, and the stack effect of the word.  The stack effect contains
1.178     anton    12257: an arbitrary number of types of parameters, then @code{--}, and then
1.177     anton    12258: exactly one type for the return value.  The possible types are:
                   12259: 
                   12260: @table @code
                   12261: 
                   12262: @item n
                   12263: single-cell integer
                   12264: 
                   12265: @item a
                   12266: address (single-cell)
                   12267: 
                   12268: @item d
                   12269: double-cell integer
                   12270: 
                   12271: @item r
                   12272: floating-point value
                   12273: 
                   12274: @item func
                   12275: C function pointer
                   12276: 
                   12277: @item void
                   12278: no value (used as return type for void functions)
                   12279: 
                   12280: @end table
                   12281: 
                   12282: @cindex variadic C functions
                   12283: 
                   12284: To deal with variadic C functions, you can declare one Forth word for
                   12285: every pattern you want to use, e.g.:
                   12286: 
                   12287: @example
                   12288: \c #include <stdio.h>
                   12289: c-function printf-nr printf a n r -- n
                   12290: c-function printf-rn printf a r n -- n
                   12291: @end example
                   12292: 
                   12293: Note that with C functions declared as variadic (or if you don't
                   12294: provide a prototype), the C interface has no C type to convert to, so
                   12295: no automatic conversion happens, which may lead to portability
                   12296: problems in some cases.  In such cases you can perform the conversion
                   12297: explicitly on the C level, e.g., as follows:
                   12298: 
                   12299: @example
1.178     anton    12300: \c #define printfll(s,ll) printf(s,(long long)ll)
                   12301: c-function printfll printfll a n -- n
1.177     anton    12302: @end example
                   12303: 
                   12304: Here, instead of calling @code{printf()} directly, we define a macro
1.178     anton    12305: that casts (converts) the Forth single-cell integer into a
                   12306: C @code{long long} before calling @code{printf()}.
1.177     anton    12307: 
                   12308: doc-\c
                   12309: doc-c-function
1.207   ! pazsan   12310: doc-c-value
        !          12311: doc-c-variable
1.177     anton    12312: 
                   12313: In order to work, this C interface invokes GCC at run-time and uses
1.178     anton    12314: dynamic linking.  If these features are not available, there are
                   12315: other, less convenient and less portable C interfaces in @file{lib.fs}
                   12316: and @file{oldlib.fs}.  These interfaces are mostly undocumented and
                   12317: mostly incompatible with each other and with the documented C
                   12318: interface; you can find some examples for the @file{lib.fs} interface
                   12319: in @file{lib.fs}.
1.177     anton    12320: 
                   12321: 
1.196     anton    12322: @node Calling C function pointers, Defining library interfaces, Declaring C Functions, C Interface
1.180     anton    12323: @subsection Calling C function pointers from Forth
                   12324: @cindex C function pointers, calling from Forth
1.177     anton    12325: 
1.180     anton    12326: If you come across a C function pointer (e.g., in some C-constructed
                   12327: structure) and want to call it from your Forth program, you can also
                   12328: use the features explained until now to achieve that, as follows:
1.150     anton    12329: 
1.180     anton    12330: Let us assume that there is a C function pointer type @code{func1}
                   12331: defined in some header file @file{func1.h}, and you know that these
                   12332: functions take one integer argument and return an integer result; and
                   12333: you want to call functions through such pointers.  Just define
1.155     anton    12334: 
1.180     anton    12335: @example
                   12336: \c #include <func1.h>
                   12337: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
                   12338: c-function call-func1 call_func1 n func -- n
                   12339: @end example
                   12340: 
                   12341: and then you can call a function pointed to by, say @code{func1a} as
                   12342: follows:
                   12343: 
                   12344: @example
                   12345: -5 func1a call-func1 .
                   12346: @end example
                   12347: 
                   12348: In the C part, @code{call_func} is defined as a macro to avoid having
                   12349: to declare the exact parameter and return types, so the C compiler
                   12350: knows them from the declaration of @code{func1}.
                   12351: 
                   12352: The Forth word @code{call-func1} is similar to @code{execute}, except
                   12353: that it takes a C @code{func1} pointer instead of a Forth execution
                   12354: token, and it is specific to @code{func1} pointers.  For each type of
                   12355: function pointer you want to call from Forth, you have to define
                   12356: a separate calling word.
                   12357: 
                   12358: 
1.196     anton    12359: @node Defining library interfaces, Declaring OS-level libraries, Calling C function pointers, C Interface
                   12360: @subsection Defining library interfaces
                   12361: @cindex giving a name to a library interface
                   12362: @cindex library interface names
                   12363: 
                   12364: You can give a name to a bunch of C function declarations (a library
                   12365: interface), as follows:
                   12366: 
                   12367: @example
                   12368: c-library lseek-lib
                   12369: \c #define _FILE_OFFSET_BITS 64
                   12370: ...
                   12371: end-c-library
                   12372: @end example
                   12373: 
1.202     anton    12374: The effect of giving such a name to the interface is that the names of
                   12375: the generated files will contain that name, and when you use the
                   12376: interface a second time, it will use the existing files instead of
                   12377: generating and compiling them again, saving you time.  Note that even
                   12378: if you change the declarations, the old (stale) files will be used,
                   12379: probably leading to errors.  So, during development of the
                   12380: declarations we recommend not using @code{c-library}.  Normally these
                   12381: files are cached in @file{$HOME/.gforth/libcc-named}, so by deleting
                   12382: that directory you can get rid of stale files.
                   12383: 
                   12384: Note that you should use @code{c-library} before everything else
                   12385: having anything to do with that library, as it resets some setup
                   12386: stuff.  The idea is that the typical use is to put each
                   12387: @code{c-library}...@code{end-library} unit in its own file, and to be
                   12388: able to include these files in any order.
1.196     anton    12389: 
                   12390: Note that the library name is not allocated in the dictionary and
                   12391: therefore does not shadow dictionary names.  It is used in the file
                   12392: system, so you have to use naming conventions appropriate for file
                   12393: systems.  Also, you must not call a function you declare after
                   12394: @code{c-library} before you perform @code{end-c-library}.
                   12395: 
                   12396: A major benefit of these named library interfaces is that, once they
                   12397: are generated, the tools used to generated them (in particular, the C
                   12398: compiler and libtool) are no longer needed, so the interface can be
                   12399: used even on machines that do not have the tools installed.
                   12400: 
                   12401: doc-c-library-name
                   12402: doc-c-library
                   12403: doc-end-c-library
                   12404: 
                   12405: 
                   12406: @node Declaring OS-level libraries, Callbacks, Defining library interfaces, C Interface
                   12407: @subsection Declaring OS-level libraries
1.195     anton    12408: @cindex Shared libraries in C interface
                   12409: @cindex Dynamically linked libraries in C interface
                   12410: @cindex Libraries in C interface
                   12411: 
1.196     anton    12412: For calling some C functions, you need to link with a specific
                   12413: OS-level library that contains that function.  E.g., the @code{sin}
                   12414: function requires linking a special library by using the command line
                   12415: switch @code{-lm}.  In our C iterface you do the equivalent thing by
                   12416: calling @code{add-lib} as follows:
1.195     anton    12417: 
                   12418: @example
                   12419: clear-libs
                   12420: s" m" add-lib
                   12421: \c #include <math.h>
                   12422: c-function sin sin r -- r
                   12423: @end example
                   12424: 
                   12425: First, you clear any libraries that may have been declared earlier
                   12426: (you don't need them for @code{sin}); then you add the @code{m}
                   12427: library (actually @code{libm.so} or somesuch) to the currently
                   12428: declared libraries; you can add as many as you need.  Finally you
                   12429: declare the function as shown above.  Typically you will use the same
                   12430: set of library declarations for many function declarations; you need
                   12431: to write only one set for that, right at the beginning.
                   12432: 
1.196     anton    12433: Note that you must not call @code{clear-libs} inside
                   12434: @code{c-library...end-c-library}; however, @code{c-library} performs
                   12435: the function of @code{clear-libs}, so @code{clear-libs} is not
                   12436: necessary, and you usually want to put @code{add-lib} calls inside
                   12437: @code{c-library...end-c-library}.
                   12438: 
1.195     anton    12439: doc-clear-libs
                   12440: doc-add-lib
                   12441: 
                   12442: 
1.196     anton    12443: @node Callbacks, C interface internals, Declaring OS-level libraries, C Interface
1.150     anton    12444: @subsection Callbacks
1.155     anton    12445: @cindex Callback functions written in Forth
                   12446: @cindex C function pointers to Forth words
                   12447: 
1.177     anton    12448: Callbacks are not yet supported by the documented C interface.  You
                   12449: can use the undocumented @file{lib.fs} interface for callbacks.
                   12450: 
1.155     anton    12451: In some cases you have to pass a function pointer to a C function,
                   12452: i.e., the library wants to call back to your application (and the
                   12453: pointed-to function is called a callback function).  You can pass the
                   12454: address of an existing C function (that you get with @code{lib-sym},
                   12455: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
                   12456: function, you probably want to define the function as a Forth word.
                   12457: 
                   12458: @c I don't understand the existing callback interface from the example - anton
                   12459: 
1.165     anton    12460: 
                   12461: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
                   12462: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
                   12463: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
                   12464: @c > > C-Funktionsadresse auf dem TOS).
                   12465: @c >
                   12466: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
                   12467: @c > gesehen habe, wozu das gut ist.
                   12468: @c 
                   12469: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch 
                   12470: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen 
                   12471: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit 
                   12472: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte 
                   12473: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit 
                   12474: @c demselben Prototyp.
                   12475: 
                   12476: 
1.178     anton    12477: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
1.177     anton    12478: @subsection How the C interface works
                   12479: 
                   12480: The documented C interface works by generating a C code out of the
                   12481: declarations.
                   12482: 
                   12483: In particular, for every Forth word declared with @code{c-function},
                   12484: it generates a wrapper function in C that takes the Forth data from
                   12485: the Forth stacks, and calls the target C function with these data as
                   12486: arguments.  The C compiler then performs an implicit conversion
                   12487: between the Forth type from the stack, and the C type for the
                   12488: parameter, which is given by the C function prototype.  After the C
                   12489: function returns, the return value is likewise implicitly converted to
                   12490: a Forth type and written back on the stack.
                   12491: 
                   12492: The @code{\c} lines are literally included in the C code (but without
                   12493: the @code{\c}), and provide the necessary declarations so that the C
                   12494: compiler knows the C types and has enough information to perform the
                   12495: conversion.
                   12496: 
                   12497: These wrapper functions are eventually compiled and dynamically linked
                   12498: into Gforth, and then they can be called.
                   12499: 
1.195     anton    12500: The libraries added with @code{add-lib} are used in the compile
                   12501: command line to specify dependent libraries with @code{-l@var{lib}},
                   12502: causing these libraries to be dynamically linked when the wrapper
                   12503: function is linked.
                   12504: 
1.177     anton    12505: 
1.178     anton    12506: @node Low-Level C Interface Words,  , C interface internals, C Interface
1.155     anton    12507: @subsection Low-Level C Interface Words
1.44      crook    12508: 
1.155     anton    12509: doc-open-lib
                   12510: doc-lib-sym
1.196     anton    12511: doc-lib-error
1.177     anton    12512: doc-call-c
1.26      crook    12513: 
1.78      anton    12514: @c -------------------------------------------------------------
1.150     anton    12515: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78      anton    12516: @section Assembler and Code Words
                   12517: @cindex assembler
                   12518: @cindex code words
1.44      crook    12519: 
1.78      anton    12520: @menu
                   12521: * Code and ;code::              
                   12522: * Common Assembler::            Assembler Syntax
                   12523: * Common Disassembler::         
                   12524: * 386 Assembler::               Deviations and special cases
                   12525: * Alpha Assembler::             Deviations and special cases
                   12526: * MIPS assembler::              Deviations and special cases
1.161     anton    12527: * PowerPC assembler::           Deviations and special cases
1.193     dvdkhlng 12528: * ARM Assembler::               Deviations and special cases
1.78      anton    12529: * Other assemblers::            How to write them
                   12530: @end menu
1.21      crook    12531: 
1.78      anton    12532: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
                   12533: @subsection @code{Code} and @code{;code}
1.26      crook    12534: 
1.78      anton    12535: Gforth provides some words for defining primitives (words written in
                   12536: machine code), and for defining the machine-code equivalent of
                   12537: @code{DOES>}-based defining words. However, the machine-independent
                   12538: nature of Gforth poses a few problems: First of all, Gforth runs on
                   12539: several architectures, so it can provide no standard assembler. What's
                   12540: worse is that the register allocation not only depends on the processor,
                   12541: but also on the @code{gcc} version and options used.
1.44      crook    12542: 
1.78      anton    12543: The words that Gforth offers encapsulate some system dependences (e.g.,
                   12544: the header structure), so a system-independent assembler may be used in
                   12545: Gforth. If you do not have an assembler, you can compile machine code
                   12546: directly with @code{,} and @code{c,}@footnote{This isn't portable,
                   12547: because these words emit stuff in @i{data} space; it works because
                   12548: Gforth has unified code/data spaces. Assembler isn't likely to be
                   12549: portable anyway.}.
1.21      crook    12550: 
1.44      crook    12551: 
1.78      anton    12552: doc-assembler
                   12553: doc-init-asm
                   12554: doc-code
                   12555: doc-end-code
                   12556: doc-;code
                   12557: doc-flush-icache
1.44      crook    12558: 
1.21      crook    12559: 
1.78      anton    12560: If @code{flush-icache} does not work correctly, @code{code} words
                   12561: etc. will not work (reliably), either.
1.44      crook    12562: 
1.78      anton    12563: The typical usage of these @code{code} words can be shown most easily by
                   12564: analogy to the equivalent high-level defining words:
1.44      crook    12565: 
1.78      anton    12566: @example
                   12567: : foo                              code foo
                   12568:    <high-level Forth words>              <assembler>
                   12569: ;                                  end-code
                   12570:                                 
                   12571: : bar                              : bar
                   12572:    <high-level Forth words>           <high-level Forth words>
                   12573:    CREATE                             CREATE
                   12574:       <high-level Forth words>           <high-level Forth words>
                   12575:    DOES>                              ;code
                   12576:       <high-level Forth words>           <assembler>
                   12577: ;                                  end-code
                   12578: @end example
1.21      crook    12579: 
1.78      anton    12580: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44      crook    12581: 
1.78      anton    12582: @cindex registers of the inner interpreter
                   12583: In the assembly code you will want to refer to the inner interpreter's
                   12584: registers (e.g., the data stack pointer) and you may want to use other
                   12585: registers for temporary storage. Unfortunately, the register allocation
                   12586: is installation-dependent.
1.44      crook    12587: 
1.78      anton    12588: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100     anton    12589: (return stack pointer) may be in different places in @code{gforth} and
                   12590: @code{gforth-fast}, or different installations.  This means that you
                   12591: cannot write a @code{NEXT} routine that works reliably on both versions
                   12592: or different installations; so for doing @code{NEXT}, I recommend
                   12593: jumping to @code{' noop >code-address}, which contains nothing but a
                   12594: @code{NEXT}.
1.21      crook    12595: 
1.78      anton    12596: For general accesses to the inner interpreter's registers, the easiest
                   12597: solution is to use explicit register declarations (@pxref{Explicit Reg
                   12598: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
                   12599: all of the inner interpreter's registers: You have to compile Gforth
                   12600: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
                   12601: the appropriate declarations must be present in the @code{machine.h}
                   12602: file (see @code{mips.h} for an example; you can find a full list of all
                   12603: declarable register symbols with @code{grep register engine.c}). If you
                   12604: give explicit registers to all variables that are declared at the
                   12605: beginning of @code{engine()}, you should be able to use the other
                   12606: caller-saved registers for temporary storage. Alternatively, you can use
                   12607: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
                   12608: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
                   12609: reserve a register (however, this restriction on register allocation may
                   12610: slow Gforth significantly).
1.44      crook    12611: 
1.78      anton    12612: If this solution is not viable (e.g., because @code{gcc} does not allow
                   12613: you to explicitly declare all the registers you need), you have to find
                   12614: out by looking at the code where the inner interpreter's registers
                   12615: reside and which registers can be used for temporary storage. You can
                   12616: get an assembly listing of the engine's code with @code{make engine.s}.
1.44      crook    12617: 
1.78      anton    12618: In any case, it is good practice to abstract your assembly code from the
                   12619: actual register allocation. E.g., if the data stack pointer resides in
                   12620: register @code{$17}, create an alias for this register called @code{sp},
                   12621: and use that in your assembly code.
1.21      crook    12622: 
1.78      anton    12623: @cindex code words, portable
                   12624: Another option for implementing normal and defining words efficiently
                   12625: is to add the desired functionality to the source of Gforth. For normal
                   12626: words you just have to edit @file{primitives} (@pxref{Automatic
                   12627: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
                   12628: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
                   12629: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44      crook    12630: 
1.78      anton    12631: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
                   12632: @subsection Common Assembler
1.44      crook    12633: 
1.78      anton    12634: The assemblers in Gforth generally use a postfix syntax, i.e., the
                   12635: instruction name follows the operands.
1.21      crook    12636: 
1.78      anton    12637: The operands are passed in the usual order (the same that is used in the
                   12638: manual of the architecture).  Since they all are Forth words, they have
                   12639: to be separated by spaces; you can also use Forth words to compute the
                   12640: operands.
1.44      crook    12641: 
1.78      anton    12642: The instruction names usually end with a @code{,}.  This makes it easier
                   12643: to visually separate instructions if you put several of them on one
                   12644: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21      crook    12645: 
1.78      anton    12646: Registers are usually specified by number; e.g., (decimal) @code{11}
                   12647: specifies registers R11 and F11 on the Alpha architecture (which one,
                   12648: depends on the instruction).  The usual names are also available, e.g.,
                   12649: @code{s2} for R11 on Alpha.
1.21      crook    12650: 
1.78      anton    12651: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
                   12652: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
                   12653: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
                   12654: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
                   12655: conditions are specified in a way specific to each assembler.
1.1       anton    12656: 
1.78      anton    12657: Note that the register assignments of the Gforth engine can change
                   12658: between Gforth versions, or even between different compilations of the
                   12659: same Gforth version (e.g., if you use a different GCC version).  So if
                   12660: you want to refer to Gforth's registers (e.g., the stack pointer or
                   12661: TOS), I recommend defining your own words for refering to these
                   12662: registers, and using them later on; then you can easily adapt to a
                   12663: changed register assignment.  The stability of the register assignment
                   12664: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1       anton    12665: 
1.100     anton    12666: The most common use of these registers is to dispatch to the next word
                   12667: (the @code{next} routine).  A portable way to do this is to jump to
                   12668: @code{' noop >code-address} (of course, this is less efficient than
                   12669: integrating the @code{next} code and scheduling it well).
1.1       anton    12670: 
1.96      anton    12671: Another difference between Gforth version is that the top of stack is
                   12672: kept in memory in @code{gforth} and, on most platforms, in a register in
                   12673: @code{gforth-fast}.
                   12674: 
1.78      anton    12675: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
                   12676: @subsection Common Disassembler
1.127     anton    12677: @cindex disassembler, general
                   12678: @cindex gdb disassembler
1.1       anton    12679: 
1.78      anton    12680: You can disassemble a @code{code} word with @code{see}
                   12681: (@pxref{Debugging}).  You can disassemble a section of memory with
1.1       anton    12682: 
1.127     anton    12683: doc-discode
1.44      crook    12684: 
1.127     anton    12685: There are two kinds of disassembler for Gforth: The Forth disassembler
                   12686: (available on some CPUs) and the gdb disassembler (available on
                   12687: platforms with @command{gdb} and @command{mktemp}).  If both are
                   12688: available, the Forth disassembler is used by default.  If you prefer
                   12689: the gdb disassembler, say
                   12690: 
                   12691: @example
                   12692: ' disasm-gdb is discode
                   12693: @end example
                   12694: 
                   12695: If neither is available, @code{discode} performs @code{dump}.
                   12696: 
                   12697: The Forth disassembler generally produces output that can be fed into the
1.78      anton    12698: assembler (i.e., same syntax, etc.).  It also includes additional
                   12699: information in comments.  In particular, the address of the instruction
                   12700: is given in a comment before the instruction.
1.1       anton    12701: 
1.127     anton    12702: The gdb disassembler produces output in the same format as the gdb
                   12703: @code{disassemble} command (@pxref{Machine Code,,Source and machine
                   12704: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
                   12705: the 386 and AMD64 architectures).
                   12706: 
1.78      anton    12707: @code{See} may display more or less than the actual code of the word,
                   12708: because the recognition of the end of the code is unreliable.  You can
1.127     anton    12709: use @code{discode} if it did not display enough.  It may display more, if
1.78      anton    12710: the code word is not immediately followed by a named word.  If you have
1.116     anton    12711: something else there, you can follow the word with @code{align latest ,}
1.78      anton    12712: to ensure that the end is recognized.
1.21      crook    12713: 
1.78      anton    12714: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
                   12715: @subsection 386 Assembler
1.44      crook    12716: 
1.78      anton    12717: The 386 assembler included in Gforth was written by Bernd Paysan, it's
                   12718: available under GPL, and originally part of bigFORTH.
1.21      crook    12719: 
1.78      anton    12720: The 386 disassembler included in Gforth was written by Andrew McKewan
                   12721: and is in the public domain.
1.21      crook    12722: 
1.91      anton    12723: The disassembler displays code in an Intel-like prefix syntax.
1.21      crook    12724: 
1.78      anton    12725: The assembler uses a postfix syntax with reversed parameters.
1.1       anton    12726: 
1.78      anton    12727: The assembler includes all instruction of the Athlon, i.e. 486 core
                   12728: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
                   12729: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
                   12730: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1       anton    12731: 
1.78      anton    12732: There are several prefixes to switch between different operation sizes,
                   12733: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
                   12734: double-word accesses. Addressing modes can be switched with @code{.wa}
                   12735: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
                   12736: need a prefix for byte register names (@code{AL} et al).
1.1       anton    12737: 
1.78      anton    12738: For floating point operations, the prefixes are @code{.fs} (IEEE
                   12739: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
                   12740: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21      crook    12741: 
1.78      anton    12742: The MMX opcodes don't have size prefixes, they are spelled out like in
                   12743: the Intel assembler. Instead of move from and to memory, there are
                   12744: PLDQ/PLDD and PSTQ/PSTD.
1.21      crook    12745: 
1.78      anton    12746: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
                   12747: ax.  Immediate values are indicated by postfixing them with @code{#},
1.91      anton    12748: e.g., @code{3 #}.  Here are some examples of addressing modes in various
                   12749: syntaxes:
1.21      crook    12750: 
1.26      crook    12751: @example
1.91      anton    12752: Gforth          Intel (NASM)   AT&T (gas)      Name
                   12753: .w ax           ax             %ax             register (16 bit)
                   12754: ax              eax            %eax            register (32 bit)
                   12755: 3 #             offset 3       $3              immediate
                   12756: 1000 #)         byte ptr 1000  1000            displacement
                   12757: bx )            [ebx]          (%ebx)          base
                   12758: 100 di d)       100[edi]       100(%edi)       base+displacement
                   12759: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
                   12760: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
                   12761: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
                   12762: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
                   12763: @end example
                   12764: 
                   12765: You can use @code{L)} and @code{LI)} instead of @code{D)} and
                   12766: @code{DI)} to enforce 32-bit displacement fields (useful for
                   12767: later patching).
1.21      crook    12768: 
1.78      anton    12769: Some example of instructions are:
1.1       anton    12770: 
                   12771: @example
1.78      anton    12772: ax bx mov             \ move ebx,eax
                   12773: 3 # ax mov            \ mov eax,3
1.137     pazsan   12774: 100 di d) ax mov      \ mov eax,100[edi]
1.78      anton    12775: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
                   12776: .w ax bx mov          \ mov bx,ax
1.1       anton    12777: @end example
                   12778: 
1.78      anton    12779: The following forms are supported for binary instructions:
1.1       anton    12780: 
                   12781: @example
1.78      anton    12782: <reg> <reg> <inst>
                   12783: <n> # <reg> <inst>
                   12784: <mem> <reg> <inst>
                   12785: <reg> <mem> <inst>
1.136     pazsan   12786: <n> # <mem> <inst>
1.1       anton    12787: @end example
                   12788: 
1.136     pazsan   12789: The shift/rotate syntax is:
1.1       anton    12790: 
1.26      crook    12791: @example
1.78      anton    12792: <reg/mem> 1 # shl \ shortens to shift without immediate
                   12793: <reg/mem> 4 # shl
                   12794: <reg/mem> cl shl
1.26      crook    12795: @end example
1.1       anton    12796: 
1.78      anton    12797: Precede string instructions (@code{movs} etc.) with @code{.b} to get
                   12798: the byte version.
1.1       anton    12799: 
1.78      anton    12800: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
                   12801: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
                   12802: pc < >= <= >}. (Note that most of these words shadow some Forth words
                   12803: when @code{assembler} is in front of @code{forth} in the search path,
                   12804: e.g., in @code{code} words).  Currently the control structure words use
                   12805: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
                   12806: to shuffle them (you can also use @code{swap} etc.).
1.21      crook    12807: 
1.78      anton    12808: Here is an example of a @code{code} word (assumes that the stack pointer
                   12809: is in esi and the TOS is in ebx):
1.21      crook    12810: 
1.26      crook    12811: @example
1.78      anton    12812: code my+ ( n1 n2 -- n )
                   12813:     4 si D) bx add
                   12814:     4 # si add
                   12815:     Next
                   12816: end-code
1.26      crook    12817: @end example
1.21      crook    12818: 
1.161     anton    12819: 
1.78      anton    12820: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
                   12821: @subsection Alpha Assembler
1.21      crook    12822: 
1.78      anton    12823: The Alpha assembler and disassembler were originally written by Bernd
                   12824: Thallner.
1.26      crook    12825: 
1.78      anton    12826: The register names @code{a0}--@code{a5} are not available to avoid
                   12827: shadowing hex numbers.
1.2       jwilke   12828: 
1.78      anton    12829: Immediate forms of arithmetic instructions are distinguished by a
                   12830: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
                   12831: does not count as arithmetic instruction).
1.2       jwilke   12832: 
1.78      anton    12833: You have to specify all operands to an instruction, even those that
                   12834: other assemblers consider optional, e.g., the destination register for
                   12835: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2       jwilke   12836: 
1.78      anton    12837: You can specify conditions for @code{if,} by removing the first @code{b}
                   12838: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2       jwilke   12839: 
1.26      crook    12840: @example
1.78      anton    12841: 11 fgt if, \ if F11>0e
                   12842:   ...
                   12843: endif,
1.26      crook    12844: @end example
1.2       jwilke   12845: 
1.78      anton    12846: @code{fbgt,} gives @code{fgt}.  
                   12847: 
1.161     anton    12848: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78      anton    12849: @subsection MIPS assembler
1.2       jwilke   12850: 
1.78      anton    12851: The MIPS assembler was originally written by Christian Pirker.
1.2       jwilke   12852: 
1.78      anton    12853: Currently the assembler and disassembler only cover the MIPS-I
                   12854: architecture (R3000), and don't support FP instructions.
1.2       jwilke   12855: 
1.78      anton    12856: The register names @code{$a0}--@code{$a3} are not available to avoid
                   12857: shadowing hex numbers.
1.2       jwilke   12858: 
1.78      anton    12859: Because there is no way to distinguish registers from immediate values,
                   12860: you have to explicitly use the immediate forms of instructions, i.e.,
                   12861: @code{addiu,}, not just @code{addu,} (@command{as} does this
                   12862: implicitly).
1.2       jwilke   12863: 
1.78      anton    12864: If the architecture manual specifies several formats for the instruction
                   12865: (e.g., for @code{jalr,}), you usually have to use the one with more
                   12866: arguments (i.e., two for @code{jalr,}).  When in doubt, see
                   12867: @code{arch/mips/testasm.fs} for an example of correct use.
1.2       jwilke   12868: 
1.78      anton    12869: Branches and jumps in the MIPS architecture have a delay slot.  You have
                   12870: to fill it yourself (the simplest way is to use @code{nop,}), the
                   12871: assembler does not do it for you (unlike @command{as}).  Even
                   12872: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
                   12873: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
                   12874: and @code{then,} just specify branch targets, they are not affected.
1.2       jwilke   12875: 
1.78      anton    12876: Note that you must not put branches, jumps, or @code{li,} into the delay
                   12877: slot: @code{li,} may expand to several instructions, and control flow
                   12878: instructions may not be put into the branch delay slot in any case.
1.2       jwilke   12879: 
1.78      anton    12880: For branches the argument specifying the target is a relative address;
                   12881: You have to add the address of the delay slot to get the absolute
                   12882: address.
1.1       anton    12883: 
1.78      anton    12884: The MIPS architecture also has load delay slots and restrictions on
                   12885: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
                   12886: yourself to satisfy these restrictions, the assembler does not do it for
                   12887: you.
1.1       anton    12888: 
1.78      anton    12889: You can specify the conditions for @code{if,} etc. by taking a
                   12890: conditional branch and leaving away the @code{b} at the start and the
                   12891: @code{,} at the end.  E.g.,
1.1       anton    12892: 
1.26      crook    12893: @example
1.78      anton    12894: 4 5 eq if,
                   12895:   ... \ do something if $4 equals $5
                   12896: then,
1.26      crook    12897: @end example
1.1       anton    12898: 
1.161     anton    12899: 
1.193     dvdkhlng 12900: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
1.161     anton    12901: @subsection PowerPC assembler
                   12902: 
1.162     anton    12903: The PowerPC assembler and disassembler were contributed by Michal
1.161     anton    12904: Revucky.
                   12905: 
1.162     anton    12906: This assembler does not follow the convention of ending mnemonic names
                   12907: with a ``,'', so some mnemonic names shadow regular Forth words (in
                   12908: particular: @code{and or xor fabs}); so if you want to use the Forth
                   12909: words, you have to make them visible first, e.g., with @code{also
                   12910: forth}.
                   12911: 
1.161     anton    12912: Registers are referred to by their number, e.g., @code{9} means the
                   12913: integer register 9 or the FP register 9 (depending on the
                   12914: instruction).
                   12915: 
                   12916: Because there is no way to distinguish registers from immediate values,
                   12917: you have to explicitly use the immediate forms of instructions, i.e.,
1.162     anton    12918: @code{addi,}, not just @code{add,}.
1.161     anton    12919: 
1.162     anton    12920: The assembler and disassembler usually support the most general form
1.161     anton    12921: of an instruction, but usually not the shorter forms (especially for
                   12922: branches).
                   12923: 
                   12924: 
1.193     dvdkhlng 12925: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
                   12926: @subsection ARM Assembler
1.161     anton    12927: 
1.193     dvdkhlng 12928: The ARM assembler included in Gforth was written from scratch by David
                   12929: Kuehling.
                   12930: 
                   12931: The assembler includes all instruction of ARM architecture version 4,
                   12932: but does not (yet) have support for Thumb instructions.  It also lacks
                   12933: support for any co-processors.
                   12934: 
                   12935: The assembler uses a postfix syntax with the target operand specified
                   12936: last.  For load/store instructions the last operand will be the
                   12937: register(s) to be loaded from/stored to.
                   12938: 
                   12939: Registers are specified by their names @code{r0} through @code{r15},
                   12940: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
                   12941: @code{fp} provided for convenience.  Note that @code{ip} means intra
                   12942: procedure call scratch register (@code{r12}) and does not refer to the
                   12943: instruction pointer.
                   12944: 
                   12945: Condition codes can be specified anywhere in the instruction, but will
                   12946: be most readable if specified just in front of the mnemonic.  The 'S'
                   12947: flag is not a separate word, but encoded into instruction mnemonics,
                   12948: ie. just use @code{adds,} instead of @code{add,} if you want the
                   12949: status register to be updated.
                   12950: 
                   12951: The following table lists the syntax of operands for general
                   12952: instructions:
                   12953: 
                   12954: @example
                   12955: Gforth          normal assembler      description
                   12956: 123 #           #123                  immediate
                   12957: r12             r12                   register
                   12958: r12 4 #LSL      r12, LSL #4           shift left by immediate
                   12959: r12 r1 #LSL     r12, LSL r1           shift left by register
                   12960: r12 4 #LSR      r12, LSR #4           shift right by immediate
                   12961: r12 r1 #LSR     r12, LSR r1           shift right by register
                   12962: r12 4 #ASR      r12, ASR #4           arithmetic shift right
                   12963: r12 r1 #ASR     r12, ASR r1           ... by register
                   12964: r12 4 #ROR      r12, ROR #4           rotate right by immediate
                   12965: r12 r1 #ROR     r12, ROR r1           ... by register
                   12966: r12 RRX         r12, RRX              rotate right with extend by 1
                   12967: @end example
                   12968: 
                   12969: Memory operand syntax is listed in this table:
                   12970: 
                   12971: @example
                   12972: Gforth            normal assembler      description
                   12973: r4 ]              [r4]                  register
                   12974: r4 4 #]           [r4, #+4]             register with immediate offset
                   12975: r4 -4 #]          [r4, #-4]             with negative offset
                   12976: r4 r1 +]          [r4, +r1]             register with register offset
                   12977: r4 r1 -]          [r4, -r1]             with negated register offset
                   12978: r4 r1 2 #LSL -]   [r4, -r1, LSL #2]     with negated and shifted offset
                   12979: r4 4 #]!          [r4, #+4]!            immediate preincrement
                   12980: r4 r1 +]!         [r4, +r1]!            register preincrement
                   12981: r4 r1 -]!         [r4, +r1]!            register predecrement
                   12982: r4 r1 2 #LSL +]!  [r4, +r1, LSL #2]!    shifted preincrement
                   12983: r4 -4 ]#          [r4], #-4             immediate postdecrement
                   12984: r4 r1 ]+          [r4], r1              register postincrement
                   12985: r4 r1 ]-          [r4], -r1             register postdecrement
                   12986: r4 r1 2 #LSL ]-   [r4], -r1, LSL #2     shifted postdecrement
                   12987: ' xyz >body [#]   xyz                   PC-relative addressing
                   12988: @end example
                   12989: 
                   12990: Register lists for load/store multiple instructions are started and
                   12991: terminated by using the words @code{@{} and @code{@}}
                   12992: respectivly.  Between braces, register names can be listed one by one,
                   12993: or register ranges can be formed by using the postfix operator
                   12994: @code{r-r}.  The @code{^} flag is not encoded in the register list
                   12995: operand, but instead directly encoded into the instruction mnemonic,
                   12996: ie. use @code{^ldm,} and @code{^stm,}.
                   12997: 
                   12998: Addressing modes for load/store multiple are not encoded as
                   12999: instruction suffixes, but instead specified after the register that
                   13000: supplies the address.  Use one of @code{DA}, @code{IA}, @code{DB},
                   13001: @code{IB}, @code{DA!}, @code{IA!}, @code{DB!} or @code{IB!}.
                   13002: 
                   13003: The following table gives some examples:
                   13004: 
                   13005: @example
                   13006: Gforth                           normal assembler
                   13007: @{ r0 r7 r8 @}  r4 ia  stm,        stmia    @{r0,r7,r8@}, r4
                   13008: @{ r0 r7 r8 @}  r4 db!  ldm,       ldmdb    @{r0,r7,r8@}, r4!
                   13009: @{ r0 r15 r-r @}  sp ia!  ^ldm,    ldmfd    @{r0-r15@}^, sp!
                   13010: @end example
                   13011: 
                   13012: Conditions for control structure words are specified in front of a
                   13013: word:
                   13014: 
                   13015: @example
                   13016: r1 r2 cmp,    \ compare r1 and r2
                   13017: eq if,        \ equal?
                   13018:    ...          \ code executed if r1 == r2
                   13019: then,
                   13020: @end example
                   13021: 
                   13022: Here is an example of a @code{code} word (assumes that the stack
                   13023: pointer is in @code{r9}, and that @code{r2} and @code{r3} can be
                   13024: clobbered):
                   13025: 
                   13026: @example
                   13027: code my+ ( n1 n2 --  n3 )
                   13028:    r9 IA!       @{ r2 r3 @} ldm,  \ pop r2 = n2, r3 = n1
                   13029:    r2   r3      r3        add,  \ r3 = n2+n1
                   13030:    r9 -4 #]!    r3        str,  \ push r3
                   13031:    next,
                   13032: end-code
                   13033: @end example
                   13034: 
                   13035: Look at @file{arch/arm/asm-example.fs} for more examples.
                   13036: 
                   13037: @node Other assemblers,  , ARM Assembler, Assembler and Code Words
1.78      anton    13038: @subsection Other assemblers
                   13039: 
                   13040: If you want to contribute another assembler/disassembler, please contact
1.103     anton    13041: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
                   13042: an assembler already.  If you are writing them from scratch, please use
                   13043: a similar syntax style as the one we use (i.e., postfix, commas at the
                   13044: end of the instruction names, @pxref{Common Assembler}); make the output
                   13045: of the disassembler be valid input for the assembler, and keep the style
1.78      anton    13046: similar to the style we used.
                   13047: 
                   13048: Hints on implementation: The most important part is to have a good test
                   13049: suite that contains all instructions.  Once you have that, the rest is
                   13050: easy.  For actual coding you can take a look at
                   13051: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
                   13052: the assembler and disassembler, avoiding redundancy and some potential
                   13053: bugs.  You can also look at that file (and @pxref{Advanced does> usage
                   13054: example}) to get ideas how to factor a disassembler.
                   13055: 
                   13056: Start with the disassembler, because it's easier to reuse data from the
                   13057: disassembler for the assembler than the other way round.
1.1       anton    13058: 
1.78      anton    13059: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
                   13060: how simple it can be.
1.1       anton    13061: 
1.161     anton    13062: 
                   13063: 
                   13064: 
1.78      anton    13065: @c -------------------------------------------------------------
                   13066: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
                   13067: @section Threading Words
                   13068: @cindex threading words
1.1       anton    13069: 
1.78      anton    13070: @cindex code address
                   13071: These words provide access to code addresses and other threading stuff
                   13072: in Gforth (and, possibly, other interpretive Forths). It more or less
                   13073: abstracts away the differences between direct and indirect threading
                   13074: (and, for direct threading, the machine dependences). However, at
                   13075: present this wordset is still incomplete. It is also pretty low-level;
                   13076: some day it will hopefully be made unnecessary by an internals wordset
                   13077: that abstracts implementation details away completely.
1.1       anton    13078: 
1.78      anton    13079: The terminology used here stems from indirect threaded Forth systems; in
                   13080: such a system, the XT of a word is represented by the CFA (code field
                   13081: address) of a word; the CFA points to a cell that contains the code
                   13082: address.  The code address is the address of some machine code that
                   13083: performs the run-time action of invoking the word (e.g., the
                   13084: @code{dovar:} routine pushes the address of the body of the word (a
                   13085: variable) on the stack
                   13086: ).
1.1       anton    13087: 
1.78      anton    13088: @cindex code address
                   13089: @cindex code field address
                   13090: In an indirect threaded Forth, you can get the code address of @i{name}
                   13091: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
                   13092: >code-address}, independent of the threading method.
1.1       anton    13093: 
1.78      anton    13094: doc-threading-method
                   13095: doc->code-address
                   13096: doc-code-address!
1.1       anton    13097: 
1.78      anton    13098: @cindex @code{does>}-handler
                   13099: @cindex @code{does>}-code
                   13100: For a word defined with @code{DOES>}, the code address usually points to
                   13101: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
                   13102: routine (in Gforth on some platforms, it can also point to the dodoes
                   13103: routine itself).  What you are typically interested in, though, is
                   13104: whether a word is a @code{DOES>}-defined word, and what Forth code it
                   13105: executes; @code{>does-code} tells you that.
1.1       anton    13106: 
1.78      anton    13107: doc->does-code
1.1       anton    13108: 
1.78      anton    13109: To create a @code{DOES>}-defined word with the following basic words,
                   13110: you have to set up a @code{DOES>}-handler with @code{does-handler!};
                   13111: @code{/does-handler} aus behind you have to place your executable Forth
                   13112: code.  Finally you have to create a word and modify its behaviour with
                   13113: @code{does-handler!}.
1.1       anton    13114: 
1.78      anton    13115: doc-does-code!
                   13116: doc-does-handler!
                   13117: doc-/does-handler
1.1       anton    13118: 
1.78      anton    13119: The code addresses produced by various defining words are produced by
                   13120: the following words:
1.1       anton    13121: 
1.78      anton    13122: doc-docol:
                   13123: doc-docon:
                   13124: doc-dovar:
                   13125: doc-douser:
                   13126: doc-dodefer:
                   13127: doc-dofield:
1.1       anton    13128: 
1.99      anton    13129: @cindex definer
                   13130: The following two words generalize @code{>code-address},
                   13131: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
                   13132: 
                   13133: doc->definer
                   13134: doc-definer!
                   13135: 
1.26      crook    13136: @c -------------------------------------------------------------
1.78      anton    13137: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21      crook    13138: @section Passing Commands to the Operating System
                   13139: @cindex operating system - passing commands
                   13140: @cindex shell commands
                   13141: 
                   13142: Gforth allows you to pass an arbitrary string to the host operating
                   13143: system shell (if such a thing exists) for execution.
                   13144: 
                   13145: doc-sh
                   13146: doc-system
                   13147: doc-$?
1.23      crook    13148: doc-getenv
1.44      crook    13149: 
1.26      crook    13150: @c -------------------------------------------------------------
1.47      crook    13151: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
                   13152: @section Keeping track of Time
                   13153: @cindex time-related words
                   13154: 
                   13155: doc-ms
                   13156: doc-time&date
1.79      anton    13157: doc-utime
                   13158: doc-cputime
1.47      crook    13159: 
                   13160: 
                   13161: @c -------------------------------------------------------------
                   13162: @node Miscellaneous Words,  , Keeping track of Time, Words
1.21      crook    13163: @section Miscellaneous Words
                   13164: @cindex miscellaneous words
                   13165: 
1.29      crook    13166: @comment TODO find homes for these
                   13167: 
1.26      crook    13168: These section lists the ANS Forth words that are not documented
1.21      crook    13169: elsewhere in this manual. Ultimately, they all need proper homes.
                   13170: 
1.68      anton    13171: doc-quit
1.44      crook    13172: 
1.26      crook    13173: The following ANS Forth words are not currently supported by Gforth 
1.27      crook    13174: (@pxref{ANS conformance}):
1.21      crook    13175: 
                   13176: @code{EDITOR} 
                   13177: @code{EMIT?} 
                   13178: @code{FORGET} 
                   13179: 
1.24      anton    13180: @c ******************************************************************
                   13181: @node Error messages, Tools, Words, Top
                   13182: @chapter Error messages
                   13183: @cindex error messages
                   13184: @cindex backtrace
                   13185: 
                   13186: A typical Gforth error message looks like this:
                   13187: 
                   13188: @example
1.86      anton    13189: in file included from \evaluated string/:-1
1.24      anton    13190: in file included from ./yyy.fs:1
                   13191: ./xxx.fs:4: Invalid memory address
1.134     anton    13192: >>>bar<<<
1.79      anton    13193: Backtrace:
1.25      anton    13194: $400E664C @@
                   13195: $400E6664 foo
1.24      anton    13196: @end example
                   13197: 
                   13198: The message identifying the error is @code{Invalid memory address}.  The
                   13199: error happened when text-interpreting line 4 of the file
                   13200: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
                   13201: word on the line where the error happened, is pointed out (with
1.134     anton    13202: @code{>>>} and @code{<<<}).
1.24      anton    13203: 
                   13204: The file containing the error was included in line 1 of @file{./yyy.fs},
                   13205: and @file{yyy.fs} was included from a non-file (in this case, by giving
                   13206: @file{yyy.fs} as command-line parameter to Gforth).
                   13207: 
                   13208: At the end of the error message you find a return stack dump that can be
                   13209: interpreted as a backtrace (possibly empty). On top you find the top of
                   13210: the return stack when the @code{throw} happened, and at the bottom you
                   13211: find the return stack entry just above the return stack of the topmost
                   13212: text interpreter.
                   13213: 
                   13214: To the right of most return stack entries you see a guess for the word
                   13215: that pushed that return stack entry as its return address. This gives a
                   13216: backtrace. In our case we see that @code{bar} called @code{foo}, and
                   13217: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
                   13218: address} exception).
                   13219: 
                   13220: Note that the backtrace is not perfect: We don't know which return stack
                   13221: entries are return addresses (so we may get false positives); and in
                   13222: some cases (e.g., for @code{abort"}) we cannot determine from the return
                   13223: address the word that pushed the return address, so for some return
                   13224: addresses you see no names in the return stack dump.
1.25      anton    13225: 
                   13226: @cindex @code{catch} and backtraces
                   13227: The return stack dump represents the return stack at the time when a
                   13228: specific @code{throw} was executed.  In programs that make use of
                   13229: @code{catch}, it is not necessarily clear which @code{throw} should be
                   13230: used for the return stack dump (e.g., consider one @code{throw} that
                   13231: indicates an error, which is caught, and during recovery another error
1.160     anton    13232: happens; which @code{throw} should be used for the stack dump?).
                   13233: Gforth presents the return stack dump for the first @code{throw} after
                   13234: the last executed (not returned-to) @code{catch} or @code{nothrow};
                   13235: this works well in the usual case. To get the right backtrace, you
                   13236: usually want to insert @code{nothrow} or @code{['] false catch drop}
                   13237: after a @code{catch} if the error is not rethrown.
1.25      anton    13238: 
                   13239: @cindex @code{gforth-fast} and backtraces
                   13240: @cindex @code{gforth-fast}, difference from @code{gforth}
                   13241: @cindex backtraces with @code{gforth-fast}
                   13242: @cindex return stack dump with @code{gforth-fast}
1.79      anton    13243: @code{Gforth} is able to do a return stack dump for throws generated
1.25      anton    13244: from primitives (e.g., invalid memory address, stack empty etc.);
                   13245: @code{gforth-fast} is only able to do a return stack dump from a
1.96      anton    13246: directly called @code{throw} (including @code{abort} etc.).  Given an
1.30      anton    13247: exception caused by a primitive in @code{gforth-fast}, you will
                   13248: typically see no return stack dump at all; however, if the exception is
                   13249: caught by @code{catch} (e.g., for restoring some state), and then
                   13250: @code{throw}n again, the return stack dump will be for the first such
                   13251: @code{throw}.
1.2       jwilke   13252: 
1.5       anton    13253: @c ******************************************************************
1.24      anton    13254: @node Tools, ANS conformance, Error messages, Top
1.1       anton    13255: @chapter Tools
                   13256: 
                   13257: @menu
                   13258: * ANS Report::                  Report the words used, sorted by wordset.
1.127     anton    13259: * Stack depth changes::         Where does this stack item come from?
1.1       anton    13260: @end menu
                   13261: 
                   13262: See also @ref{Emacs and Gforth}.
                   13263: 
1.126     pazsan   13264: @node ANS Report, Stack depth changes, Tools, Tools
1.1       anton    13265: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   13266: @cindex @file{ans-report.fs}
                   13267: @cindex report the words used in your program
                   13268: @cindex words used in your program
                   13269: 
                   13270: If you want to label a Forth program as ANS Forth Program, you must
                   13271: document which wordsets the program uses; for extension wordsets, it is
                   13272: helpful to list the words the program requires from these wordsets
                   13273: (because Forth systems are allowed to provide only some words of them).
                   13274: 
                   13275: The @file{ans-report.fs} tool makes it easy for you to determine which
                   13276: words from which wordset and which non-ANS words your application
                   13277: uses. You simply have to include @file{ans-report.fs} before loading the
                   13278: program you want to check. After loading your program, you can get the
                   13279: report with @code{print-ans-report}. A typical use is to run this as
                   13280: batch job like this:
                   13281: @example
                   13282: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   13283: @end example
                   13284: 
                   13285: The output looks like this (for @file{compat/control.fs}):
                   13286: @example
                   13287: The program uses the following words
                   13288: from CORE :
                   13289: : POSTPONE THEN ; immediate ?dup IF 0= 
                   13290: from BLOCK-EXT :
                   13291: \ 
                   13292: from FILE :
                   13293: ( 
                   13294: @end example
                   13295: 
                   13296: @subsection Caveats
                   13297: 
                   13298: Note that @file{ans-report.fs} just checks which words are used, not whether
                   13299: they are used in an ANS Forth conforming way!
                   13300: 
                   13301: Some words are defined in several wordsets in the
                   13302: standard. @file{ans-report.fs} reports them for only one of the
                   13303: wordsets, and not necessarily the one you expect. It depends on usage
                   13304: which wordset is the right one to specify. E.g., if you only use the
                   13305: compilation semantics of @code{S"}, it is a Core word; if you also use
                   13306: its interpretation semantics, it is a File word.
1.124     anton    13307: 
                   13308: 
1.127     anton    13309: @node Stack depth changes,  , ANS Report, Tools
1.124     anton    13310: @section Stack depth changes during interpretation
                   13311: @cindex @file{depth-changes.fs}
                   13312: @cindex depth changes during interpretation
                   13313: @cindex stack depth changes during interpretation
                   13314: @cindex items on the stack after interpretation
                   13315: 
                   13316: Sometimes you notice that, after loading a file, there are items left
                   13317: on the stack.  The tool @file{depth-changes.fs} helps you find out
                   13318: quickly where in the file these stack items are coming from.
                   13319: 
                   13320: The simplest way of using @file{depth-changes.fs} is to include it
                   13321: before the file(s) you want to check, e.g.:
                   13322: 
                   13323: @example
                   13324: gforth depth-changes.fs my-file.fs
                   13325: @end example
                   13326: 
                   13327: This will compare the stack depths of the data and FP stack at every
                   13328: empty line (in interpretation state) against these depths at the last
                   13329: empty line (in interpretation state).  If the depths are not equal,
                   13330: the position in the file and the stack contents are printed with
                   13331: @code{~~} (@pxref{Debugging}).  This indicates that a stack depth
                   13332: change has occured in the paragraph of non-empty lines before the
                   13333: indicated line.  It is a good idea to leave an empty line at the end
                   13334: of the file, so the last paragraph is checked, too.
                   13335: 
                   13336: Checking only at empty lines usually works well, but sometimes you
                   13337: have big blocks of non-empty lines (e.g., when building a big table),
                   13338: and you want to know where in this block the stack depth changed.  You
                   13339: can check all interpreted lines with
                   13340: 
                   13341: @example
                   13342: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
                   13343: @end example
                   13344: 
                   13345: This checks the stack depth at every end-of-line.  So the depth change
                   13346: occured in the line reported by the @code{~~} (not in the line
                   13347: before).
                   13348: 
                   13349: Note that, while this offers better accuracy in indicating where the
                   13350: stack depth changes, it will often report many intentional stack depth
                   13351: changes (e.g., when an interpreted computation stretches across
                   13352: several lines).  You can suppress the checking of some lines by
                   13353: putting backslashes at the end of these lines (not followed by white
                   13354: space), and using
                   13355: 
                   13356: @example
                   13357: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
                   13358: @end example
1.1       anton    13359: 
                   13360: @c ******************************************************************
1.65      anton    13361: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1       anton    13362: @chapter ANS conformance
                   13363: @cindex ANS conformance of Gforth
                   13364: 
                   13365: To the best of our knowledge, Gforth is an
                   13366: 
                   13367: ANS Forth System
                   13368: @itemize @bullet
                   13369: @item providing the Core Extensions word set
                   13370: @item providing the Block word set
                   13371: @item providing the Block Extensions word set
                   13372: @item providing the Double-Number word set
                   13373: @item providing the Double-Number Extensions word set
                   13374: @item providing the Exception word set
                   13375: @item providing the Exception Extensions word set
                   13376: @item providing the Facility word set
1.40      anton    13377: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1       anton    13378: @item providing the File Access word set
                   13379: @item providing the File Access Extensions word set
                   13380: @item providing the Floating-Point word set
                   13381: @item providing the Floating-Point Extensions word set
                   13382: @item providing the Locals word set
                   13383: @item providing the Locals Extensions word set
                   13384: @item providing the Memory-Allocation word set
                   13385: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   13386: @item providing the Programming-Tools word set
                   13387: @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
                   13388: @item providing the Search-Order word set
                   13389: @item providing the Search-Order Extensions word set
                   13390: @item providing the String word set
                   13391: @item providing the String Extensions word set (another easy one)
                   13392: @end itemize
                   13393: 
1.118     anton    13394: Gforth has the following environmental restrictions:
                   13395: 
                   13396: @cindex environmental restrictions
                   13397: @itemize @bullet
                   13398: @item
                   13399: While processing the OS command line, if an exception is not caught,
                   13400: Gforth exits with a non-zero exit code instyead of performing QUIT.
                   13401: 
                   13402: @item
                   13403: When an @code{throw} is performed after a @code{query}, Gforth does not
                   13404: allways restore the input source specification in effect at the
                   13405: corresponding catch.
                   13406: 
                   13407: @end itemize
                   13408: 
                   13409: 
1.1       anton    13410: @cindex system documentation
                   13411: In addition, ANS Forth systems are required to document certain
                   13412: implementation choices. This chapter tries to meet these
                   13413: requirements. In many cases it gives a way to ask the system for the
                   13414: information instead of providing the information directly, in
                   13415: particular, if the information depends on the processor, the operating
                   13416: system or the installation options chosen, or if they are likely to
                   13417: change during the maintenance of Gforth.
                   13418: 
                   13419: @comment The framework for the rest has been taken from pfe.
                   13420: 
                   13421: @menu
                   13422: * The Core Words::              
                   13423: * The optional Block word set::  
                   13424: * The optional Double Number word set::  
                   13425: * The optional Exception word set::  
                   13426: * The optional Facility word set::  
                   13427: * The optional File-Access word set::  
                   13428: * The optional Floating-Point word set::  
                   13429: * The optional Locals word set::  
                   13430: * The optional Memory-Allocation word set::  
                   13431: * The optional Programming-Tools word set::  
                   13432: * The optional Search-Order word set::  
                   13433: @end menu
                   13434: 
                   13435: 
                   13436: @c =====================================================================
                   13437: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   13438: @comment  node-name,  next,  previous,  up
                   13439: @section The Core Words
                   13440: @c =====================================================================
                   13441: @cindex core words, system documentation
                   13442: @cindex system documentation, core words
                   13443: 
                   13444: @menu
                   13445: * core-idef::                   Implementation Defined Options                   
                   13446: * core-ambcond::                Ambiguous Conditions                
                   13447: * core-other::                  Other System Documentation                  
                   13448: @end menu
                   13449: 
                   13450: @c ---------------------------------------------------------------------
                   13451: @node core-idef, core-ambcond, The Core Words, The Core Words
                   13452: @subsection Implementation Defined Options
                   13453: @c ---------------------------------------------------------------------
                   13454: @cindex core words, implementation-defined options
                   13455: @cindex implementation-defined options, core words
                   13456: 
                   13457: 
                   13458: @table @i
                   13459: @item (Cell) aligned addresses:
                   13460: @cindex cell-aligned addresses
                   13461: @cindex aligned addresses
                   13462: processor-dependent. Gforth's alignment words perform natural alignment
                   13463: (e.g., an address aligned for a datum of size 8 is divisible by
                   13464: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   13465: 
                   13466: @item @code{EMIT} and non-graphic characters:
                   13467: @cindex @code{EMIT} and non-graphic characters
                   13468: @cindex non-graphic characters and @code{EMIT}
                   13469: The character is output using the C library function (actually, macro)
                   13470: @code{putc}.
                   13471: 
                   13472: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   13473: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   13474: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   13475: @cindex @code{ACCEPT}, editing
                   13476: @cindex @code{EXPECT}, editing
                   13477: This is modeled on the GNU readline library (@pxref{Readline
                   13478: Interaction, , Command Line Editing, readline, The GNU Readline
                   13479: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   13480: producing a full word completion every time you type it (instead of
1.28      crook    13481: producing the common prefix of all completions). @xref{Command-line editing}.
1.1       anton    13482: 
                   13483: @item character set:
                   13484: @cindex character set
                   13485: The character set of your computer and display device. Gforth is
                   13486: 8-bit-clean (but some other component in your system may make trouble).
                   13487: 
                   13488: @item Character-aligned address requirements:
                   13489: @cindex character-aligned address requirements
                   13490: installation-dependent. Currently a character is represented by a C
                   13491: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   13492: (Comments on that requested).
                   13493: 
                   13494: @item character-set extensions and matching of names:
                   13495: @cindex character-set extensions and matching of names
1.26      crook    13496: @cindex case-sensitivity for name lookup
                   13497: @cindex name lookup, case-sensitivity
                   13498: @cindex locale and case-sensitivity
1.21      crook    13499: Any character except the ASCII NUL character can be used in a
1.1       anton    13500: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47      crook    13501: matching is performed using the C library function @code{strncasecmp}, whose
1.1       anton    13502: function is probably influenced by the locale. E.g., the @code{C} locale
                   13503: does not know about accents and umlauts, so they are matched
                   13504: case-sensitively in that locale. For portability reasons it is best to
                   13505: write programs such that they work in the @code{C} locale. Then one can
                   13506: use libraries written by a Polish programmer (who might use words
                   13507: containing ISO Latin-2 encoded characters) and by a French programmer
                   13508: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   13509: funny results for some of the words (which ones, depends on the font you
                   13510: are using)). Also, the locale you prefer may not be available in other
                   13511: operating systems. Hopefully, Unicode will solve these problems one day.
                   13512: 
                   13513: @item conditions under which control characters match a space delimiter:
                   13514: @cindex space delimiters
                   13515: @cindex control characters as delimiters
1.117     anton    13516: If @code{word} is called with the space character as a delimiter, all
1.1       anton    13517: white-space characters (as identified by the C macro @code{isspace()})
1.117     anton    13518: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138     anton    13519: delimiters.  @code{Parse-name}, which is used by the outer
1.1       anton    13520: interpreter (aka text interpreter) by default, treats all white-space
                   13521: characters as delimiters.
                   13522: 
1.26      crook    13523: @item format of the control-flow stack:
                   13524: @cindex control-flow stack, format
                   13525: The data stack is used as control-flow stack. The size of a control-flow
1.1       anton    13526: stack item in cells is given by the constant @code{cs-item-size}. At the
                   13527: time of this writing, an item consists of a (pointer to a) locals list
                   13528: (third), an address in the code (second), and a tag for identifying the
                   13529: item (TOS). The following tags are used: @code{defstart},
                   13530: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   13531: @code{scopestart}.
                   13532: 
                   13533: @item conversion of digits > 35
                   13534: @cindex digits > 35
                   13535: The characters @code{[\]^_'} are the digits with the decimal value
                   13536: 36@minus{}41. There is no way to input many of the larger digits.
                   13537: 
                   13538: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   13539: @cindex @code{EXPECT}, display after end of input
                   13540: @cindex @code{ACCEPT}, display after end of input
                   13541: The cursor is moved to the end of the entered string. If the input is
                   13542: terminated using the @kbd{Return} key, a space is typed.
                   13543: 
                   13544: @item exception abort sequence of @code{ABORT"}:
                   13545: @cindex exception abort sequence of @code{ABORT"}
                   13546: @cindex @code{ABORT"}, exception abort sequence
                   13547: The error string is stored into the variable @code{"error} and a
                   13548: @code{-2 throw} is performed.
                   13549: 
                   13550: @item input line terminator:
                   13551: @cindex input line terminator
                   13552: @cindex line terminator on input
1.26      crook    13553: @cindex newline character on input
1.1       anton    13554: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   13555: lines. One of these characters is typically produced when you type the
                   13556: @kbd{Enter} or @kbd{Return} key.
                   13557: 
                   13558: @item maximum size of a counted string:
                   13559: @cindex maximum size of a counted string
                   13560: @cindex counted string, maximum size
                   13561: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79      anton    13562: on all platforms, but this may change.
1.1       anton    13563: 
                   13564: @item maximum size of a parsed string:
                   13565: @cindex maximum size of a parsed string
                   13566: @cindex parsed string, maximum size
                   13567: Given by the constant @code{/line}. Currently 255 characters.
                   13568: 
                   13569: @item maximum size of a definition name, in characters:
                   13570: @cindex maximum size of a definition name, in characters
                   13571: @cindex name, maximum length
1.113     anton    13572: MAXU/8
1.1       anton    13573: 
                   13574: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   13575: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   13576: @cindex @code{ENVIRONMENT?} string length, maximum
1.113     anton    13577: MAXU/8
1.1       anton    13578: 
                   13579: @item method of selecting the user input device:
                   13580: @cindex user input device, method of selecting
                   13581: The user input device is the standard input. There is currently no way to
                   13582: change it from within Gforth. However, the input can typically be
                   13583: redirected in the command line that starts Gforth.
                   13584: 
                   13585: @item method of selecting the user output device:
                   13586: @cindex user output device, method of selecting
                   13587: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    13588: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   13589: output when the user output device is a terminal, otherwise the output
                   13590: is buffered.
1.1       anton    13591: 
                   13592: @item methods of dictionary compilation:
                   13593: What are we expected to document here?
                   13594: 
                   13595: @item number of bits in one address unit:
                   13596: @cindex number of bits in one address unit
                   13597: @cindex address unit, size in bits
                   13598: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79      anton    13599: platforms.
1.1       anton    13600: 
                   13601: @item number representation and arithmetic:
                   13602: @cindex number representation and arithmetic
1.79      anton    13603: Processor-dependent. Binary two's complement on all current platforms.
1.1       anton    13604: 
                   13605: @item ranges for integer types:
                   13606: @cindex ranges for integer types
                   13607: @cindex integer types, ranges
                   13608: Installation-dependent. Make environmental queries for @code{MAX-N},
                   13609: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   13610: unsigned (and positive) types is 0. The lower bound for signed types on
                   13611: two's complement and one's complement machines machines can be computed
                   13612: by adding 1 to the upper bound.
                   13613: 
                   13614: @item read-only data space regions:
                   13615: @cindex read-only data space regions
                   13616: @cindex data-space, read-only regions
                   13617: The whole Forth data space is writable.
                   13618: 
                   13619: @item size of buffer at @code{WORD}:
                   13620: @cindex size of buffer at @code{WORD}
                   13621: @cindex @code{WORD} buffer size
                   13622: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   13623: shared with the pictured numeric output string. If overwriting
                   13624: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   13625: space, although only as much can be sensibly used as fits in a counted
                   13626: string.
                   13627: 
                   13628: @item size of one cell in address units:
                   13629: @cindex cell size
                   13630: @code{1 cells .}.
                   13631: 
                   13632: @item size of one character in address units:
                   13633: @cindex char size
1.79      anton    13634: @code{1 chars .}. 1 on all current platforms.
1.1       anton    13635: 
                   13636: @item size of the keyboard terminal buffer:
                   13637: @cindex size of the keyboard terminal buffer
                   13638: @cindex terminal buffer, size
                   13639: Varies. You can determine the size at a specific time using @code{lp@@
                   13640: tib - .}. It is shared with the locals stack and TIBs of files that
                   13641: include the current file. You can change the amount of space for TIBs
                   13642: and locals stack at Gforth startup with the command line option
                   13643: @code{-l}.
                   13644: 
                   13645: @item size of the pictured numeric output buffer:
                   13646: @cindex size of the pictured numeric output buffer
                   13647: @cindex pictured numeric output buffer, size
                   13648: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   13649: shared with @code{WORD}.
                   13650: 
                   13651: @item size of the scratch area returned by @code{PAD}:
                   13652: @cindex size of the scratch area returned by @code{PAD}
                   13653: @cindex @code{PAD} size
                   13654: The remainder of dictionary space. @code{unused pad here - - .}.
                   13655: 
                   13656: @item system case-sensitivity characteristics:
                   13657: @cindex case-sensitivity characteristics
1.26      crook    13658: Dictionary searches are case-insensitive (except in
1.1       anton    13659: @code{TABLE}s). However, as explained above under @i{character-set
                   13660: extensions}, the matching for non-ASCII characters is determined by the
                   13661: locale you are using. In the default @code{C} locale all non-ASCII
                   13662: characters are matched case-sensitively.
                   13663: 
                   13664: @item system prompt:
                   13665: @cindex system prompt
                   13666: @cindex prompt
                   13667: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   13668: 
                   13669: @item division rounding:
                   13670: @cindex division rounding
1.166     anton    13671: The ordinary division words @code{/ mod /mod */ */mod} perform floored
                   13672: division (with the default installation of Gforth).  You can check
                   13673: this with @code{s" floored" environment? drop .}.  If you write
                   13674: programs that need a specific division rounding, best use
                   13675: @code{fm/mod} or @code{sm/rem} for portability.
1.1       anton    13676: 
                   13677: @item values of @code{STATE} when true:
                   13678: @cindex @code{STATE} values
                   13679: -1.
                   13680: 
                   13681: @item values returned after arithmetic overflow:
                   13682: On two's complement machines, arithmetic is performed modulo
                   13683: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.164     anton    13684: arithmetic (with appropriate mapping for signed types). Division by
                   13685: zero typically results in a @code{-55 throw} (Floating-point
                   13686: unidentified fault) or @code{-10 throw} (divide by zero).  Integer
1.166     anton    13687: division overflow can result in these throws, or in @code{-11 throw};
                   13688: in @code{gforth-fast} division overflow and divide by zero may also
                   13689: result in returning bogus results without producing an exception.
1.1       anton    13690: 
                   13691: @item whether the current definition can be found after @t{DOES>}:
                   13692: @cindex @t{DOES>}, visibility of current definition
                   13693: No.
                   13694: 
                   13695: @end table
                   13696: 
                   13697: @c ---------------------------------------------------------------------
                   13698: @node core-ambcond, core-other, core-idef, The Core Words
                   13699: @subsection Ambiguous conditions
                   13700: @c ---------------------------------------------------------------------
                   13701: @cindex core words, ambiguous conditions
                   13702: @cindex ambiguous conditions, core words
                   13703: 
                   13704: @table @i
                   13705: 
                   13706: @item a name is neither a word nor a number:
                   13707: @cindex name not found
1.26      crook    13708: @cindex undefined word
1.80      anton    13709: @code{-13 throw} (Undefined word).
1.1       anton    13710: 
                   13711: @item a definition name exceeds the maximum length allowed:
1.26      crook    13712: @cindex word name too long
1.1       anton    13713: @code{-19 throw} (Word name too long)
                   13714: 
                   13715: @item addressing a region not inside the various data spaces of the forth system:
                   13716: @cindex Invalid memory address
1.32      anton    13717: The stacks, code space and header space are accessible. Machine code space is
1.1       anton    13718: typically readable. Accessing other addresses gives results dependent on
                   13719: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   13720: address).
                   13721: 
                   13722: @item argument type incompatible with parameter:
1.26      crook    13723: @cindex argument type mismatch
1.1       anton    13724: This is usually not caught. Some words perform checks, e.g., the control
                   13725: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   13726: mismatch).
                   13727: 
                   13728: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   13729: @cindex Interpreting a compile-only word, for @code{'} etc.
                   13730: @cindex execution token of words with undefined execution semantics
                   13731: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   13732: get an execution token for @code{compile-only-error} (which performs a
                   13733: @code{-14 throw} when executed).
                   13734: 
                   13735: @item dividing by zero:
                   13736: @cindex dividing by zero
                   13737: @cindex floating point unidentified fault, integer division
1.80      anton    13738: On some platforms, this produces a @code{-10 throw} (Division by
1.24      anton    13739: zero); on other systems, this typically results in a @code{-55 throw}
                   13740: (Floating-point unidentified fault).
1.1       anton    13741: 
                   13742: @item insufficient data stack or return stack space:
                   13743: @cindex insufficient data stack or return stack space
                   13744: @cindex stack overflow
1.26      crook    13745: @cindex address alignment exception, stack overflow
1.1       anton    13746: @cindex Invalid memory address, stack overflow
                   13747: Depending on the operating system, the installation, and the invocation
                   13748: of Gforth, this is either checked by the memory management hardware, or
1.24      anton    13749: it is not checked. If it is checked, you typically get a @code{-3 throw}
                   13750: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
                   13751: throw} (Invalid memory address) (depending on the platform and how you
                   13752: achieved the overflow) as soon as the overflow happens. If it is not
                   13753: checked, overflows typically result in mysterious illegal memory
                   13754: accesses, producing @code{-9 throw} (Invalid memory address) or
                   13755: @code{-23 throw} (Address alignment exception); they might also destroy
                   13756: the internal data structure of @code{ALLOCATE} and friends, resulting in
                   13757: various errors in these words.
1.1       anton    13758: 
                   13759: @item insufficient space for loop control parameters:
                   13760: @cindex insufficient space for loop control parameters
1.80      anton    13761: Like other return stack overflows.
1.1       anton    13762: 
                   13763: @item insufficient space in the dictionary:
                   13764: @cindex insufficient space in the dictionary
                   13765: @cindex dictionary overflow
1.12      anton    13766: If you try to allot (either directly with @code{allot}, or indirectly
                   13767: with @code{,}, @code{create} etc.) more memory than available in the
                   13768: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   13769: to access memory beyond the end of the dictionary, the results are
                   13770: similar to stack overflows.
1.1       anton    13771: 
                   13772: @item interpreting a word with undefined interpretation semantics:
                   13773: @cindex interpreting a word with undefined interpretation semantics
                   13774: @cindex Interpreting a compile-only word
                   13775: For some words, we have defined interpretation semantics. For the
                   13776: others: @code{-14 throw} (Interpreting a compile-only word).
                   13777: 
                   13778: @item modifying the contents of the input buffer or a string literal:
                   13779: @cindex modifying the contents of the input buffer or a string literal
                   13780: These are located in writable memory and can be modified.
                   13781: 
                   13782: @item overflow of the pictured numeric output string:
                   13783: @cindex overflow of the pictured numeric output string
                   13784: @cindex pictured numeric output string, overflow
1.24      anton    13785: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1       anton    13786: 
                   13787: @item parsed string overflow:
                   13788: @cindex parsed string overflow
                   13789: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   13790: 
                   13791: @item producing a result out of range:
                   13792: @cindex result out of range
                   13793: On two's complement machines, arithmetic is performed modulo
                   13794: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.166     anton    13795: arithmetic (with appropriate mapping for signed types). Division by
                   13796: zero typically results in a @code{-10 throw} (divide by zero) or
                   13797: @code{-55 throw} (floating point unidentified fault). Overflow on
                   13798: division may result in these errors or in @code{-11 throw} (result out
                   13799: of range).  @code{Gforth-fast} may silently produce bogus results on
                   13800: division overflow or division by zero.  @code{Convert} and
1.24      anton    13801: @code{>number} currently overflow silently.
1.1       anton    13802: 
                   13803: @item reading from an empty data or return stack:
                   13804: @cindex stack empty
                   13805: @cindex stack underflow
1.24      anton    13806: @cindex return stack underflow
1.1       anton    13807: The data stack is checked by the outer (aka text) interpreter after
                   13808: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   13809: underflow) is performed. Apart from that, stacks may be checked or not,
1.24      anton    13810: depending on operating system, installation, and invocation. If they are
                   13811: caught by a check, they typically result in @code{-4 throw} (Stack
                   13812: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
                   13813: (Invalid memory address), depending on the platform and which stack
                   13814: underflows and by how much. Note that even if the system uses checking
                   13815: (through the MMU), your program may have to underflow by a significant
                   13816: number of stack items to trigger the reaction (the reason for this is
                   13817: that the MMU, and therefore the checking, works with a page-size
                   13818: granularity).  If there is no checking, the symptoms resulting from an
                   13819: underflow are similar to those from an overflow.  Unbalanced return
1.80      anton    13820: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24      anton    13821: (Invalid memory address) and Illegal Instruction (typically @code{-260
                   13822: throw}).
1.1       anton    13823: 
                   13824: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   13825: @cindex unexpected end of the input buffer
                   13826: @cindex zero-length string as a name
                   13827: @cindex Attempt to use zero-length string as a name
                   13828: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   13829: use zero-length string as a name). Words like @code{'} probably will not
                   13830: find what they search. Note that it is possible to create zero-length
                   13831: names with @code{nextname} (should it not?).
                   13832: 
                   13833: @item @code{>IN} greater than input buffer:
                   13834: @cindex @code{>IN} greater than input buffer
                   13835: The next invocation of a parsing word returns a string with length 0.
                   13836: 
                   13837: @item @code{RECURSE} appears after @code{DOES>}:
                   13838: @cindex @code{RECURSE} appears after @code{DOES>}
                   13839: Compiles a recursive call to the defining word, not to the defined word.
                   13840: 
                   13841: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   13842: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26      crook    13843: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1       anton    13844: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   13845: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   13846: the end of the file was reached), its source-id may be
                   13847: reused. Therefore, restoring an input source specification referencing a
                   13848: closed file may lead to unpredictable results instead of a @code{-12
                   13849: THROW}.
                   13850: 
                   13851: In the future, Gforth may be able to restore input source specifications
                   13852: from other than the current input source.
                   13853: 
                   13854: @item data space containing definitions gets de-allocated:
                   13855: @cindex data space containing definitions gets de-allocated
                   13856: Deallocation with @code{allot} is not checked. This typically results in
                   13857: memory access faults or execution of illegal instructions.
                   13858: 
                   13859: @item data space read/write with incorrect alignment:
                   13860: @cindex data space read/write with incorrect alignment
                   13861: @cindex alignment faults
1.26      crook    13862: @cindex address alignment exception
1.1       anton    13863: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    13864: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    13865: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   13866: (Invalid memory address). There are reportedly some processors with
1.12      anton    13867: alignment restrictions that do not report violations.
1.1       anton    13868: 
                   13869: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   13870: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   13871: Like other alignment errors.
                   13872: 
                   13873: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   13874: Like other stack underflows.
                   13875: 
                   13876: @item loop control parameters not available:
                   13877: @cindex loop control parameters not available
                   13878: Not checked. The counted loop words simply assume that the top of return
                   13879: stack items are loop control parameters and behave accordingly.
                   13880: 
                   13881: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   13882: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   13883: @cindex last word was headerless
                   13884: @code{abort" last word was headerless"}.
                   13885: 
                   13886: @item name not defined by @code{VALUE} used by @code{TO}:
                   13887: @cindex name not defined by @code{VALUE} used by @code{TO}
                   13888: @cindex @code{TO} on non-@code{VALUE}s
                   13889: @cindex Invalid name argument, @code{TO}
                   13890: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   13891: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   13892: 
                   13893: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   13894: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26      crook    13895: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1       anton    13896: @code{-13 throw} (Undefined word)
                   13897: 
                   13898: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   13899: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   13900: Gforth behaves as if they were of the same type. I.e., you can predict
                   13901: the behaviour by interpreting all parameters as, e.g., signed.
                   13902: 
                   13903: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   13904: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   13905: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   13906: compilation semantics of @code{TO}.
                   13907: 
                   13908: @item String longer than a counted string returned by @code{WORD}:
1.26      crook    13909: @cindex string longer than a counted string returned by @code{WORD}
1.1       anton    13910: @cindex @code{WORD}, string overflow
                   13911: Not checked. The string will be ok, but the count will, of course,
                   13912: contain only the least significant bits of the length.
                   13913: 
                   13914: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   13915: @cindex @code{LSHIFT}, large shift counts
                   13916: @cindex @code{RSHIFT}, large shift counts
                   13917: Processor-dependent. Typical behaviours are returning 0 and using only
                   13918: the low bits of the shift count.
                   13919: 
                   13920: @item word not defined via @code{CREATE}:
                   13921: @cindex @code{>BODY} of non-@code{CREATE}d words
                   13922: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   13923: 
                   13924: @cindex @code{DOES>} of non-@code{CREATE}d words
                   13925: @code{DOES>} changes the execution semantics of the last defined word no
                   13926: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   13927: @code{CREATE , DOES>}.
                   13928: 
                   13929: @item words improperly used outside @code{<#} and @code{#>}:
                   13930: Not checked. As usual, you can expect memory faults.
                   13931: 
                   13932: @end table
                   13933: 
                   13934: 
                   13935: @c ---------------------------------------------------------------------
                   13936: @node core-other,  , core-ambcond, The Core Words
                   13937: @subsection Other system documentation
                   13938: @c ---------------------------------------------------------------------
                   13939: @cindex other system documentation, core words
                   13940: @cindex core words, other system documentation
                   13941: 
                   13942: @table @i
                   13943: @item nonstandard words using @code{PAD}:
                   13944: @cindex @code{PAD} use by nonstandard words
                   13945: None.
                   13946: 
                   13947: @item operator's terminal facilities available:
                   13948: @cindex operator's terminal facilities available
1.80      anton    13949: After processing the OS's command line, Gforth goes into interactive mode,
1.1       anton    13950: and you can give commands to Gforth interactively. The actual facilities
                   13951: available depend on how you invoke Gforth.
                   13952: 
                   13953: @item program data space available:
                   13954: @cindex program data space available
                   13955: @cindex data space available
                   13956: @code{UNUSED .} gives the remaining dictionary space. The total
                   13957: dictionary space can be specified with the @code{-m} switch
                   13958: (@pxref{Invoking Gforth}) when Gforth starts up.
                   13959: 
                   13960: @item return stack space available:
                   13961: @cindex return stack space available
                   13962: You can compute the total return stack space in cells with
                   13963: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   13964: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   13965: 
                   13966: @item stack space available:
                   13967: @cindex stack space available
                   13968: You can compute the total data stack space in cells with
                   13969: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   13970: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   13971: 
                   13972: @item system dictionary space required, in address units:
                   13973: @cindex system dictionary space required, in address units
                   13974: Type @code{here forthstart - .} after startup. At the time of this
                   13975: writing, this gives 80080 (bytes) on a 32-bit system.
                   13976: @end table
                   13977: 
                   13978: 
                   13979: @c =====================================================================
                   13980: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   13981: @section The optional Block word set
                   13982: @c =====================================================================
                   13983: @cindex system documentation, block words
                   13984: @cindex block words, system documentation
                   13985: 
                   13986: @menu
                   13987: * block-idef::                  Implementation Defined Options
                   13988: * block-ambcond::               Ambiguous Conditions               
                   13989: * block-other::                 Other System Documentation                 
                   13990: @end menu
                   13991: 
                   13992: 
                   13993: @c ---------------------------------------------------------------------
                   13994: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   13995: @subsection Implementation Defined Options
                   13996: @c ---------------------------------------------------------------------
                   13997: @cindex implementation-defined options, block words
                   13998: @cindex block words, implementation-defined options
                   13999: 
                   14000: @table @i
                   14001: @item the format for display by @code{LIST}:
                   14002: @cindex @code{LIST} display format
                   14003: First the screen number is displayed, then 16 lines of 64 characters,
                   14004: each line preceded by the line number.
                   14005: 
                   14006: @item the length of a line affected by @code{\}:
                   14007: @cindex length of a line affected by @code{\}
                   14008: @cindex @code{\}, line length in blocks
                   14009: 64 characters.
                   14010: @end table
                   14011: 
                   14012: 
                   14013: @c ---------------------------------------------------------------------
                   14014: @node block-ambcond, block-other, block-idef, The optional Block word set
                   14015: @subsection Ambiguous conditions
                   14016: @c ---------------------------------------------------------------------
                   14017: @cindex block words, ambiguous conditions
                   14018: @cindex ambiguous conditions, block words
                   14019: 
                   14020: @table @i
                   14021: @item correct block read was not possible:
                   14022: @cindex block read not possible
                   14023: Typically results in a @code{throw} of some OS-derived value (between
                   14024: -512 and -2048). If the blocks file was just not long enough, blanks are
                   14025: supplied for the missing portion.
                   14026: 
                   14027: @item I/O exception in block transfer:
                   14028: @cindex I/O exception in block transfer
                   14029: @cindex block transfer, I/O exception
                   14030: Typically results in a @code{throw} of some OS-derived value (between
                   14031: -512 and -2048).
                   14032: 
                   14033: @item invalid block number:
                   14034: @cindex invalid block number
                   14035: @cindex block number invalid
                   14036: @code{-35 throw} (Invalid block number)
                   14037: 
                   14038: @item a program directly alters the contents of @code{BLK}:
                   14039: @cindex @code{BLK}, altering @code{BLK}
                   14040: The input stream is switched to that other block, at the same
                   14041: position. If the storing to @code{BLK} happens when interpreting
                   14042: non-block input, the system will get quite confused when the block ends.
                   14043: 
                   14044: @item no current block buffer for @code{UPDATE}:
                   14045: @cindex @code{UPDATE}, no current block buffer
                   14046: @code{UPDATE} has no effect.
                   14047: 
                   14048: @end table
                   14049: 
                   14050: @c ---------------------------------------------------------------------
                   14051: @node block-other,  , block-ambcond, The optional Block word set
                   14052: @subsection Other system documentation
                   14053: @c ---------------------------------------------------------------------
                   14054: @cindex other system documentation, block words
                   14055: @cindex block words, other system documentation
                   14056: 
                   14057: @table @i
                   14058: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   14059: No restrictions (yet).
                   14060: 
                   14061: @item the number of blocks available for source and data:
                   14062: depends on your disk space.
                   14063: 
                   14064: @end table
                   14065: 
                   14066: 
                   14067: @c =====================================================================
                   14068: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   14069: @section The optional Double Number word set
                   14070: @c =====================================================================
                   14071: @cindex system documentation, double words
                   14072: @cindex double words, system documentation
                   14073: 
                   14074: @menu
                   14075: * double-ambcond::              Ambiguous Conditions              
                   14076: @end menu
                   14077: 
                   14078: 
                   14079: @c ---------------------------------------------------------------------
                   14080: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   14081: @subsection Ambiguous conditions
                   14082: @c ---------------------------------------------------------------------
                   14083: @cindex double words, ambiguous conditions
                   14084: @cindex ambiguous conditions, double words
                   14085: 
                   14086: @table @i
1.29      crook    14087: @item @i{d} outside of range of @i{n} in @code{D>S}:
                   14088: @cindex @code{D>S}, @i{d} out of range of @i{n} 
                   14089: The least significant cell of @i{d} is produced.
1.1       anton    14090: 
                   14091: @end table
                   14092: 
                   14093: 
                   14094: @c =====================================================================
                   14095: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   14096: @section The optional Exception word set
                   14097: @c =====================================================================
                   14098: @cindex system documentation, exception words
                   14099: @cindex exception words, system documentation
                   14100: 
                   14101: @menu
                   14102: * exception-idef::              Implementation Defined Options              
                   14103: @end menu
                   14104: 
                   14105: 
                   14106: @c ---------------------------------------------------------------------
                   14107: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   14108: @subsection Implementation Defined Options
                   14109: @c ---------------------------------------------------------------------
                   14110: @cindex implementation-defined options, exception words
                   14111: @cindex exception words, implementation-defined options
                   14112: 
                   14113: @table @i
                   14114: @item @code{THROW}-codes used in the system:
                   14115: @cindex @code{THROW}-codes used in the system
                   14116: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29      crook    14117: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1       anton    14118: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   14119: allocation operations). The mapping from OS error numbers to throw codes
                   14120: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   14121: undefined OS errors produce a message with a strange number; e.g.,
                   14122: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   14123: @end table
                   14124: 
                   14125: @c =====================================================================
                   14126: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   14127: @section The optional Facility word set
                   14128: @c =====================================================================
                   14129: @cindex system documentation, facility words
                   14130: @cindex facility words, system documentation
                   14131: 
                   14132: @menu
                   14133: * facility-idef::               Implementation Defined Options               
                   14134: * facility-ambcond::            Ambiguous Conditions            
                   14135: @end menu
                   14136: 
                   14137: 
                   14138: @c ---------------------------------------------------------------------
                   14139: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   14140: @subsection Implementation Defined Options
                   14141: @c ---------------------------------------------------------------------
                   14142: @cindex implementation-defined options, facility words
                   14143: @cindex facility words, implementation-defined options
                   14144: 
                   14145: @table @i
                   14146: @item encoding of keyboard events (@code{EKEY}):
                   14147: @cindex keyboard events, encoding in @code{EKEY}
                   14148: @cindex @code{EKEY}, encoding of keyboard events
1.40      anton    14149: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41      anton    14150: Other keys are encoded with the constants @code{k-left}, @code{k-right},
                   14151: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
                   14152: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
                   14153: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40      anton    14154: 
1.1       anton    14155: 
                   14156: @item duration of a system clock tick:
                   14157: @cindex duration of a system clock tick
                   14158: @cindex clock tick duration
                   14159: System dependent. With respect to @code{MS}, the time is specified in
                   14160: microseconds. How well the OS and the hardware implement this, is
                   14161: another question.
                   14162: 
                   14163: @item repeatability to be expected from the execution of @code{MS}:
                   14164: @cindex repeatability to be expected from the execution of @code{MS}
                   14165: @cindex @code{MS}, repeatability to be expected
                   14166: System dependent. On Unix, a lot depends on load. If the system is
                   14167: lightly loaded, and the delay is short enough that Gforth does not get
                   14168: swapped out, the performance should be acceptable. Under MS-DOS and
                   14169: other single-tasking systems, it should be good.
                   14170: 
                   14171: @end table
                   14172: 
                   14173: 
                   14174: @c ---------------------------------------------------------------------
                   14175: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   14176: @subsection Ambiguous conditions
                   14177: @c ---------------------------------------------------------------------
                   14178: @cindex facility words, ambiguous conditions
                   14179: @cindex ambiguous conditions, facility words
                   14180: 
                   14181: @table @i
                   14182: @item @code{AT-XY} can't be performed on user output device:
                   14183: @cindex @code{AT-XY} can't be performed on user output device
                   14184: Largely terminal dependent. No range checks are done on the arguments.
                   14185: No errors are reported. You may see some garbage appearing, you may see
                   14186: simply nothing happen.
                   14187: 
                   14188: @end table
                   14189: 
                   14190: 
                   14191: @c =====================================================================
                   14192: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   14193: @section The optional File-Access word set
                   14194: @c =====================================================================
                   14195: @cindex system documentation, file words
                   14196: @cindex file words, system documentation
                   14197: 
                   14198: @menu
                   14199: * file-idef::                   Implementation Defined Options
                   14200: * file-ambcond::                Ambiguous Conditions                
                   14201: @end menu
                   14202: 
                   14203: @c ---------------------------------------------------------------------
                   14204: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   14205: @subsection Implementation Defined Options
                   14206: @c ---------------------------------------------------------------------
                   14207: @cindex implementation-defined options, file words
                   14208: @cindex file words, implementation-defined options
                   14209: 
                   14210: @table @i
                   14211: @item file access methods used:
                   14212: @cindex file access methods used
                   14213: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   14214: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   14215: @code{wb}): The file is cleared, if it exists, and created, if it does
                   14216: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   14217: @code{create-file} creates a file with 666 permissions modified by your
                   14218: umask.
                   14219: 
                   14220: @item file exceptions:
                   14221: @cindex file exceptions
                   14222: The file words do not raise exceptions (except, perhaps, memory access
                   14223: faults when you pass illegal addresses or file-ids).
                   14224: 
                   14225: @item file line terminator:
                   14226: @cindex file line terminator
                   14227: System-dependent. Gforth uses C's newline character as line
                   14228: terminator. What the actual character code(s) of this are is
                   14229: system-dependent.
                   14230: 
                   14231: @item file name format:
                   14232: @cindex file name format
                   14233: System dependent. Gforth just uses the file name format of your OS.
                   14234: 
                   14235: @item information returned by @code{FILE-STATUS}:
                   14236: @cindex @code{FILE-STATUS}, returned information
                   14237: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   14238: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   14239: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   14240: along with the returned mode.
                   14241: 
                   14242: @item input file state after an exception when including source:
                   14243: @cindex exception when including source
                   14244: All files that are left via the exception are closed.
                   14245: 
1.29      crook    14246: @item @i{ior} values and meaning:
                   14247: @cindex @i{ior} values and meaning
1.68      anton    14248: @cindex @i{wior} values and meaning
1.29      crook    14249: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    14250: intended as throw codes. They typically are in the range
                   14251: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    14252: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    14253: 
                   14254: @item maximum depth of file input nesting:
                   14255: @cindex maximum depth of file input nesting
                   14256: @cindex file input nesting, maximum depth
                   14257: limited by the amount of return stack, locals/TIB stack, and the number
                   14258: of open files available. This should not give you troubles.
                   14259: 
                   14260: @item maximum size of input line:
                   14261: @cindex maximum size of input line
                   14262: @cindex input line size, maximum
                   14263: @code{/line}. Currently 255.
                   14264: 
                   14265: @item methods of mapping block ranges to files:
                   14266: @cindex mapping block ranges to files
                   14267: @cindex files containing blocks
                   14268: @cindex blocks in files
                   14269: By default, blocks are accessed in the file @file{blocks.fb} in the
                   14270: current working directory. The file can be switched with @code{USE}.
                   14271: 
                   14272: @item number of string buffers provided by @code{S"}:
                   14273: @cindex @code{S"}, number of string buffers
                   14274: 1
                   14275: 
                   14276: @item size of string buffer used by @code{S"}:
                   14277: @cindex @code{S"}, size of string buffer
                   14278: @code{/line}. currently 255.
                   14279: 
                   14280: @end table
                   14281: 
                   14282: @c ---------------------------------------------------------------------
                   14283: @node file-ambcond,  , file-idef, The optional File-Access word set
                   14284: @subsection Ambiguous conditions
                   14285: @c ---------------------------------------------------------------------
                   14286: @cindex file words, ambiguous conditions
                   14287: @cindex ambiguous conditions, file words
                   14288: 
                   14289: @table @i
                   14290: @item attempting to position a file outside its boundaries:
                   14291: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   14292: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   14293: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   14294: 
                   14295: @item attempting to read from file positions not yet written:
                   14296: @cindex reading from file positions not yet written
                   14297: End-of-file, i.e., zero characters are read and no error is reported.
                   14298: 
1.29      crook    14299: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
                   14300: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
1.1       anton    14301: An appropriate exception may be thrown, but a memory fault or other
                   14302: problem is more probable.
                   14303: 
1.29      crook    14304: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
                   14305: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
                   14306: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
                   14307: The @i{ior} produced by the operation, that discovered the problem, is
1.1       anton    14308: thrown.
                   14309: 
                   14310: @item named file cannot be opened (@code{INCLUDED}):
                   14311: @cindex @code{INCLUDED}, named file cannot be opened
1.29      crook    14312: The @i{ior} produced by @code{open-file} is thrown.
1.1       anton    14313: 
                   14314: @item requesting an unmapped block number:
                   14315: @cindex unmapped block numbers
                   14316: There are no unmapped legal block numbers. On some operating systems,
                   14317: writing a block with a large number may overflow the file system and
                   14318: have an error message as consequence.
                   14319: 
                   14320: @item using @code{source-id} when @code{blk} is non-zero:
                   14321: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   14322: @code{source-id} performs its function. Typically it will give the id of
                   14323: the source which loaded the block. (Better ideas?)
                   14324: 
                   14325: @end table
                   14326: 
                   14327: 
                   14328: @c =====================================================================
                   14329: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   14330: @section The optional Floating-Point word set
                   14331: @c =====================================================================
                   14332: @cindex system documentation, floating-point words
                   14333: @cindex floating-point words, system documentation
                   14334: 
                   14335: @menu
                   14336: * floating-idef::               Implementation Defined Options
                   14337: * floating-ambcond::            Ambiguous Conditions            
                   14338: @end menu
                   14339: 
                   14340: 
                   14341: @c ---------------------------------------------------------------------
                   14342: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   14343: @subsection Implementation Defined Options
                   14344: @c ---------------------------------------------------------------------
                   14345: @cindex implementation-defined options, floating-point words
                   14346: @cindex floating-point words, implementation-defined options
                   14347: 
                   14348: @table @i
                   14349: @item format and range of floating point numbers:
                   14350: @cindex format and range of floating point numbers
                   14351: @cindex floating point numbers, format and range
                   14352: System-dependent; the @code{double} type of C.
                   14353: 
1.29      crook    14354: @item results of @code{REPRESENT} when @i{float} is out of range:
                   14355: @cindex  @code{REPRESENT}, results when @i{float} is out of range
1.1       anton    14356: System dependent; @code{REPRESENT} is implemented using the C library
                   14357: function @code{ecvt()} and inherits its behaviour in this respect.
                   14358: 
                   14359: @item rounding or truncation of floating-point numbers:
                   14360: @cindex rounding of floating-point numbers
                   14361: @cindex truncation of floating-point numbers
                   14362: @cindex floating-point numbers, rounding or truncation
                   14363: System dependent; the rounding behaviour is inherited from the hosting C
                   14364: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   14365: nearest, and break ties by rounding to even (i.e., such that the last
                   14366: bit of the mantissa is 0).
                   14367: 
                   14368: @item size of floating-point stack:
                   14369: @cindex floating-point stack size
                   14370: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   14371: the floating-point stack (in floats). You can specify this on startup
                   14372: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   14373: 
                   14374: @item width of floating-point stack:
                   14375: @cindex floating-point stack width 
                   14376: @code{1 floats}.
                   14377: 
                   14378: @end table
                   14379: 
                   14380: 
                   14381: @c ---------------------------------------------------------------------
                   14382: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   14383: @subsection Ambiguous conditions
                   14384: @c ---------------------------------------------------------------------
                   14385: @cindex floating-point words, ambiguous conditions
                   14386: @cindex ambiguous conditions, floating-point words
                   14387: 
                   14388: @table @i
                   14389: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   14390: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   14391: System-dependent. Typically results in a @code{-23 THROW} like other
                   14392: alignment violations.
                   14393: 
                   14394: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   14395: @cindex @code{f@@} used with an address that is not float aligned
                   14396: @cindex @code{f!} used with an address that is not float aligned
                   14397: System-dependent. Typically results in a @code{-23 THROW} like other
                   14398: alignment violations.
                   14399: 
                   14400: @item floating-point result out of range:
                   14401: @cindex floating-point result out of range
1.80      anton    14402: System-dependent. Can result in a @code{-43 throw} (floating point
                   14403: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
                   14404: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1       anton    14405: unidentified fault), or can produce a special value representing, e.g.,
                   14406: Infinity.
                   14407: 
                   14408: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   14409: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   14410: System-dependent. Typically results in an alignment fault like other
                   14411: alignment violations.
                   14412: 
1.35      anton    14413: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   14414: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1       anton    14415: The floating-point number is converted into decimal nonetheless.
                   14416: 
                   14417: @item Both arguments are equal to zero (@code{FATAN2}):
                   14418: @cindex @code{FATAN2}, both arguments are equal to zero
                   14419: System-dependent. @code{FATAN2} is implemented using the C library
                   14420: function @code{atan2()}.
                   14421: 
1.29      crook    14422: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
                   14423: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
                   14424: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1       anton    14425: because of small errors and the tan will be a very large (or very small)
                   14426: but finite number.
                   14427: 
1.29      crook    14428: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
                   14429: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1       anton    14430: The result is rounded to the nearest float.
                   14431: 
                   14432: @item dividing by zero:
                   14433: @cindex dividing by zero, floating-point
                   14434: @cindex floating-point dividing by zero
                   14435: @cindex floating-point unidentified fault, FP divide-by-zero
1.80      anton    14436: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
                   14437: (floating point divide by zero) or @code{-55 throw} (Floating-point
                   14438: unidentified fault).
1.1       anton    14439: 
                   14440: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   14441: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   14442: System dependent. On IEEE-FP based systems the number is converted into
                   14443: an infinity.
                   14444: 
1.29      crook    14445: @item @i{float}<1 (@code{FACOSH}):
                   14446: @cindex @code{FACOSH}, @i{float}<1
1.1       anton    14447: @cindex floating-point unidentified fault, @code{FACOSH}
1.80      anton    14448: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1       anton    14449: 
1.29      crook    14450: @item @i{float}=<-1 (@code{FLNP1}):
                   14451: @cindex @code{FLNP1}, @i{float}=<-1
1.1       anton    14452: @cindex floating-point unidentified fault, @code{FLNP1}
1.80      anton    14453: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
                   14454: negative infinity for @i{float}=-1).
1.1       anton    14455: 
1.29      crook    14456: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
                   14457: @cindex @code{FLN}, @i{float}=<0
                   14458: @cindex @code{FLOG}, @i{float}=<0
1.1       anton    14459: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80      anton    14460: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
                   14461: negative infinity for @i{float}=0).
1.1       anton    14462: 
1.29      crook    14463: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
                   14464: @cindex @code{FASINH}, @i{float}<0
                   14465: @cindex @code{FSQRT}, @i{float}<0
1.1       anton    14466: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80      anton    14467: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
                   14468: @code{fasinh} some platforms produce a NaN, others a number (bug in the
                   14469: C library?).
1.1       anton    14470: 
1.29      crook    14471: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
                   14472: @cindex @code{FACOS}, |@i{float}|>1
                   14473: @cindex @code{FASIN}, |@i{float}|>1
                   14474: @cindex @code{FATANH}, |@i{float}|>1
1.1       anton    14475: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80      anton    14476: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1       anton    14477: 
1.29      crook    14478: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
                   14479: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1       anton    14480: @cindex floating-point unidentified fault, @code{F>D}
1.80      anton    14481: Platform-dependent; typically, some double number is produced and no
                   14482: error is reported.
1.1       anton    14483: 
                   14484: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   14485: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80      anton    14486: @code{Precision} characters of the numeric output area are used.  If
                   14487: @code{precision} is too high, these words will smash the data or code
                   14488: close to @code{here}.
1.1       anton    14489: @end table
                   14490: 
                   14491: @c =====================================================================
                   14492: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   14493: @section The optional Locals word set
                   14494: @c =====================================================================
                   14495: @cindex system documentation, locals words
                   14496: @cindex locals words, system documentation
                   14497: 
                   14498: @menu
                   14499: * locals-idef::                 Implementation Defined Options                 
                   14500: * locals-ambcond::              Ambiguous Conditions              
                   14501: @end menu
                   14502: 
                   14503: 
                   14504: @c ---------------------------------------------------------------------
                   14505: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   14506: @subsection Implementation Defined Options
                   14507: @c ---------------------------------------------------------------------
                   14508: @cindex implementation-defined options, locals words
                   14509: @cindex locals words, implementation-defined options
                   14510: 
                   14511: @table @i
                   14512: @item maximum number of locals in a definition:
                   14513: @cindex maximum number of locals in a definition
                   14514: @cindex locals, maximum number in a definition
                   14515: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   14516: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   14517: characters. The number of locals in a definition is bounded by the size
                   14518: of locals-buffer, which contains the names of the locals.
                   14519: 
                   14520: @end table
                   14521: 
                   14522: 
                   14523: @c ---------------------------------------------------------------------
                   14524: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   14525: @subsection Ambiguous conditions
                   14526: @c ---------------------------------------------------------------------
                   14527: @cindex locals words, ambiguous conditions
                   14528: @cindex ambiguous conditions, locals words
                   14529: 
                   14530: @table @i
                   14531: @item executing a named local in interpretation state:
                   14532: @cindex local in interpretation state
                   14533: @cindex Interpreting a compile-only word, for a local
                   14534: Locals have no interpretation semantics. If you try to perform the
                   14535: interpretation semantics, you will get a @code{-14 throw} somewhere
                   14536: (Interpreting a compile-only word). If you perform the compilation
                   14537: semantics, the locals access will be compiled (irrespective of state).
                   14538: 
1.29      crook    14539: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1       anton    14540: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   14541: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   14542: @cindex Invalid name argument, @code{TO}
                   14543: @code{-32 throw} (Invalid name argument)
                   14544: 
                   14545: @end table
                   14546: 
                   14547: 
                   14548: @c =====================================================================
                   14549: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   14550: @section The optional Memory-Allocation word set
                   14551: @c =====================================================================
                   14552: @cindex system documentation, memory-allocation words
                   14553: @cindex memory-allocation words, system documentation
                   14554: 
                   14555: @menu
                   14556: * memory-idef::                 Implementation Defined Options                 
                   14557: @end menu
                   14558: 
                   14559: 
                   14560: @c ---------------------------------------------------------------------
                   14561: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   14562: @subsection Implementation Defined Options
                   14563: @c ---------------------------------------------------------------------
                   14564: @cindex implementation-defined options, memory-allocation words
                   14565: @cindex memory-allocation words, implementation-defined options
                   14566: 
                   14567: @table @i
1.29      crook    14568: @item values and meaning of @i{ior}:
                   14569: @cindex  @i{ior} values and meaning
                   14570: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    14571: intended as throw codes. They typically are in the range
                   14572: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    14573: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    14574: 
                   14575: @end table
                   14576: 
                   14577: @c =====================================================================
                   14578: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   14579: @section The optional Programming-Tools word set
                   14580: @c =====================================================================
                   14581: @cindex system documentation, programming-tools words
                   14582: @cindex programming-tools words, system documentation
                   14583: 
                   14584: @menu
                   14585: * programming-idef::            Implementation Defined Options            
                   14586: * programming-ambcond::         Ambiguous Conditions         
                   14587: @end menu
                   14588: 
                   14589: 
                   14590: @c ---------------------------------------------------------------------
                   14591: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   14592: @subsection Implementation Defined Options
                   14593: @c ---------------------------------------------------------------------
                   14594: @cindex implementation-defined options, programming-tools words
                   14595: @cindex programming-tools words, implementation-defined options
                   14596: 
                   14597: @table @i
                   14598: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   14599: @cindex @code{;CODE} ending sequence
                   14600: @cindex @code{CODE} ending sequence
                   14601: @code{END-CODE}
                   14602: 
                   14603: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   14604: @cindex @code{;CODE}, processing input
                   14605: @cindex @code{CODE}, processing input
                   14606: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   14607: the input is processed by the text interpreter, (starting) in interpret
                   14608: state.
                   14609: 
                   14610: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   14611: @cindex @code{ASSEMBLER}, search order capability
                   14612: The ANS Forth search order word set.
                   14613: 
                   14614: @item source and format of display by @code{SEE}:
                   14615: @cindex @code{SEE}, source and format of output
1.80      anton    14616: The source for @code{see} is the executable code used by the inner
1.1       anton    14617: interpreter.  The current @code{see} tries to output Forth source code
1.80      anton    14618: (and on some platforms, assembly code for primitives) as well as
                   14619: possible.
1.1       anton    14620: 
                   14621: @end table
                   14622: 
                   14623: @c ---------------------------------------------------------------------
                   14624: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   14625: @subsection Ambiguous conditions
                   14626: @c ---------------------------------------------------------------------
                   14627: @cindex programming-tools words, ambiguous conditions
                   14628: @cindex ambiguous conditions, programming-tools words
                   14629: 
                   14630: @table @i
                   14631: 
1.21      crook    14632: @item deleting the compilation word list (@code{FORGET}):
                   14633: @cindex @code{FORGET}, deleting the compilation word list
1.1       anton    14634: Not implemented (yet).
                   14635: 
1.29      crook    14636: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
                   14637: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
                   14638: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1       anton    14639: @cindex control-flow stack underflow
                   14640: This typically results in an @code{abort"} with a descriptive error
                   14641: message (may change into a @code{-22 throw} (Control structure mismatch)
                   14642: in the future). You may also get a memory access error. If you are
                   14643: unlucky, this ambiguous condition is not caught.
                   14644: 
1.29      crook    14645: @item @i{name} can't be found (@code{FORGET}):
                   14646: @cindex @code{FORGET}, @i{name} can't be found
1.1       anton    14647: Not implemented (yet).
                   14648: 
1.29      crook    14649: @item @i{name} not defined via @code{CREATE}:
                   14650: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1       anton    14651: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   14652: the execution semantics of the last defined word no matter how it was
                   14653: defined.
                   14654: 
                   14655: @item @code{POSTPONE} applied to @code{[IF]}:
                   14656: @cindex @code{POSTPONE} applied to @code{[IF]}
                   14657: @cindex @code{[IF]} and @code{POSTPONE}
                   14658: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   14659: equivalent to @code{[IF]}.
                   14660: 
                   14661: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   14662: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   14663: Continue in the same state of conditional compilation in the next outer
                   14664: input source. Currently there is no warning to the user about this.
                   14665: 
                   14666: @item removing a needed definition (@code{FORGET}):
                   14667: @cindex @code{FORGET}, removing a needed definition
                   14668: Not implemented (yet).
                   14669: 
                   14670: @end table
                   14671: 
                   14672: 
                   14673: @c =====================================================================
                   14674: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   14675: @section The optional Search-Order word set
                   14676: @c =====================================================================
                   14677: @cindex system documentation, search-order words
                   14678: @cindex search-order words, system documentation
                   14679: 
                   14680: @menu
                   14681: * search-idef::                 Implementation Defined Options                 
                   14682: * search-ambcond::              Ambiguous Conditions              
                   14683: @end menu
                   14684: 
                   14685: 
                   14686: @c ---------------------------------------------------------------------
                   14687: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   14688: @subsection Implementation Defined Options
                   14689: @c ---------------------------------------------------------------------
                   14690: @cindex implementation-defined options, search-order words
                   14691: @cindex search-order words, implementation-defined options
                   14692: 
                   14693: @table @i
                   14694: @item maximum number of word lists in search order:
                   14695: @cindex maximum number of word lists in search order
                   14696: @cindex search order, maximum depth
                   14697: @code{s" wordlists" environment? drop .}. Currently 16.
                   14698: 
                   14699: @item minimum search order:
                   14700: @cindex minimum search order
                   14701: @cindex search order, minimum
                   14702: @code{root root}.
                   14703: 
                   14704: @end table
                   14705: 
                   14706: @c ---------------------------------------------------------------------
                   14707: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   14708: @subsection Ambiguous conditions
                   14709: @c ---------------------------------------------------------------------
                   14710: @cindex search-order words, ambiguous conditions
                   14711: @cindex ambiguous conditions, search-order words
                   14712: 
                   14713: @table @i
1.21      crook    14714: @item changing the compilation word list (during compilation):
                   14715: @cindex changing the compilation word list (during compilation)
                   14716: @cindex compilation word list, change before definition ends
                   14717: The word is entered into the word list that was the compilation word list
1.1       anton    14718: at the start of the definition. Any changes to the name field (e.g.,
                   14719: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116     anton    14720: are applied to the latest defined word (as reported by @code{latest} or
                   14721: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1       anton    14722: 
                   14723: @item search order empty (@code{previous}):
                   14724: @cindex @code{previous}, search order empty
1.26      crook    14725: @cindex vocstack empty, @code{previous}
1.1       anton    14726: @code{abort" Vocstack empty"}.
                   14727: 
                   14728: @item too many word lists in search order (@code{also}):
                   14729: @cindex @code{also}, too many word lists in search order
1.26      crook    14730: @cindex vocstack full, @code{also}
1.1       anton    14731: @code{abort" Vocstack full"}.
                   14732: 
                   14733: @end table
                   14734: 
                   14735: @c ***************************************************************
1.65      anton    14736: @node Standard vs Extensions, Model, ANS conformance, Top
                   14737: @chapter Should I use Gforth extensions?
                   14738: @cindex Gforth extensions
                   14739: 
                   14740: As you read through the rest of this manual, you will see documentation
                   14741: for @i{Standard} words, and documentation for some appealing Gforth
                   14742: @i{extensions}. You might ask yourself the question: @i{``Should I
                   14743: restrict myself to the standard, or should I use the extensions?''}
                   14744: 
                   14745: The answer depends on the goals you have for the program you are working
                   14746: on:
                   14747: 
                   14748: @itemize @bullet
                   14749: 
                   14750: @item Is it just for yourself or do you want to share it with others?
                   14751: 
                   14752: @item
                   14753: If you want to share it, do the others all use Gforth?
                   14754: 
                   14755: @item
                   14756: If it is just for yourself, do you want to restrict yourself to Gforth?
                   14757: 
                   14758: @end itemize
                   14759: 
                   14760: If restricting the program to Gforth is ok, then there is no reason not
                   14761: to use extensions.  It is still a good idea to keep to the standard
                   14762: where it is easy, in case you want to reuse these parts in another
                   14763: program that you want to be portable.
                   14764: 
                   14765: If you want to be able to port the program to other Forth systems, there
                   14766: are the following points to consider:
                   14767: 
                   14768: @itemize @bullet
                   14769: 
                   14770: @item
                   14771: Most Forth systems that are being maintained support the ANS Forth
                   14772: standard.  So if your program complies with the standard, it will be
                   14773: portable among many systems.
                   14774: 
                   14775: @item
                   14776: A number of the Gforth extensions can be implemented in ANS Forth using
                   14777: public-domain files provided in the @file{compat/} directory. These are
                   14778: mentioned in the text in passing.  There is no reason not to use these
                   14779: extensions, your program will still be ANS Forth compliant; just include
                   14780: the appropriate compat files with your program.
                   14781: 
                   14782: @item
                   14783: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
                   14784: analyse your program and determine what non-Standard words it relies
                   14785: upon.  However, it does not check whether you use standard words in a
                   14786: non-standard way.
                   14787: 
                   14788: @item
                   14789: Some techniques are not standardized by ANS Forth, and are hard or
                   14790: impossible to implement in a standard way, but can be implemented in
                   14791: most Forth systems easily, and usually in similar ways (e.g., accessing
                   14792: word headers).  Forth has a rich historical precedent for programmers
                   14793: taking advantage of implementation-dependent features of their tools
                   14794: (for example, relying on a knowledge of the dictionary
                   14795: structure). Sometimes these techniques are necessary to extract every
                   14796: last bit of performance from the hardware, sometimes they are just a
                   14797: programming shorthand.
                   14798: 
                   14799: @item
                   14800: Does using a Gforth extension save more work than the porting this part
                   14801: to other Forth systems (if any) will cost?
                   14802: 
                   14803: @item
                   14804: Is the additional functionality worth the reduction in portability and
                   14805: the additional porting problems?
                   14806: 
                   14807: @end itemize
                   14808: 
                   14809: In order to perform these consideratios, you need to know what's
                   14810: standard and what's not.  This manual generally states if something is
1.81      anton    14811: non-standard, but the authoritative source is the
                   14812: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65      anton    14813: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
                   14814: into the thought processes of the technical committee.
                   14815: 
                   14816: Note also that portability between Forth systems is not the only
                   14817: portability issue; there is also the issue of portability between
                   14818: different platforms (processor/OS combinations).
                   14819: 
                   14820: @c ***************************************************************
                   14821: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1       anton    14822: @chapter Model
                   14823: 
                   14824: This chapter has yet to be written. It will contain information, on
                   14825: which internal structures you can rely.
                   14826: 
                   14827: @c ***************************************************************
                   14828: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   14829: @chapter Integrating Gforth into C programs
                   14830: 
                   14831: This is not yet implemented.
                   14832: 
                   14833: Several people like to use Forth as scripting language for applications
                   14834: that are otherwise written in C, C++, or some other language.
                   14835: 
                   14836: The Forth system ATLAST provides facilities for embedding it into
                   14837: applications; unfortunately it has several disadvantages: most
                   14838: importantly, it is not based on ANS Forth, and it is apparently dead
                   14839: (i.e., not developed further and not supported). The facilities
1.21      crook    14840: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1       anton    14841: making the switch should not be hard.
                   14842: 
                   14843: We also tried to design the interface such that it can easily be
                   14844: implemented by other Forth systems, so that we may one day arrive at a
                   14845: standardized interface. Such a standard interface would allow you to
                   14846: replace the Forth system without having to rewrite C code.
                   14847: 
                   14848: You embed the Gforth interpreter by linking with the library
                   14849: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   14850: global symbols in this library that belong to the interface, have the
                   14851: prefix @code{forth_}. (Global symbols that are used internally have the
                   14852: prefix @code{gforth_}).
                   14853: 
                   14854: You can include the declarations of Forth types and the functions and
                   14855: variables of the interface with @code{#include <forth.h>}.
                   14856: 
                   14857: Types.
                   14858: 
                   14859: Variables.
                   14860: 
                   14861: Data and FP Stack pointer. Area sizes.
                   14862: 
                   14863: functions.
                   14864: 
                   14865: forth_init(imagefile)
                   14866: forth_evaluate(string) exceptions?
                   14867: forth_goto(address) (or forth_execute(xt)?)
                   14868: forth_continue() (a corountining mechanism)
                   14869: 
                   14870: Adding primitives.
                   14871: 
                   14872: No checking.
                   14873: 
                   14874: Signals?
                   14875: 
                   14876: Accessing the Stacks
                   14877: 
1.26      crook    14878: @c ******************************************************************
1.1       anton    14879: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   14880: @chapter Emacs and Gforth
                   14881: @cindex Emacs and Gforth
                   14882: 
                   14883: @cindex @file{gforth.el}
                   14884: @cindex @file{forth.el}
                   14885: @cindex Rydqvist, Goran
1.107     dvdkhlng 14886: @cindex Kuehling, David
1.1       anton    14887: @cindex comment editing commands
                   14888: @cindex @code{\}, editing with Emacs
                   14889: @cindex debug tracer editing commands
                   14890: @cindex @code{~~}, removal with Emacs
                   14891: @cindex Forth mode in Emacs
1.107     dvdkhlng 14892: 
1.1       anton    14893: Gforth comes with @file{gforth.el}, an improved version of
                   14894: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26      crook    14895: improvements are:
                   14896: 
                   14897: @itemize @bullet
                   14898: @item
1.107     dvdkhlng 14899: A better handling of indentation.
                   14900: @item
                   14901: A custom hilighting engine for Forth-code.
1.26      crook    14902: @item
                   14903: Comment paragraph filling (@kbd{M-q})
                   14904: @item
                   14905: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
                   14906: @item
                   14907: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41      anton    14908: @item
                   14909: Support of the @code{info-lookup} feature for looking up the
                   14910: documentation of a word.
1.107     dvdkhlng 14911: @item
                   14912: Support for reading and writing blocks files.
1.26      crook    14913: @end itemize
                   14914: 
1.107     dvdkhlng 14915: To get a basic description of these features, enter Forth mode and
                   14916: type @kbd{C-h m}.
1.1       anton    14917: 
                   14918: @cindex source location of error or debugging output in Emacs
                   14919: @cindex error output, finding the source location in Emacs
                   14920: @cindex debugging output, finding the source location in Emacs
                   14921: In addition, Gforth supports Emacs quite well: The source code locations
                   14922: given in error messages, debugging output (from @code{~~}) and failed
                   14923: assertion messages are in the right format for Emacs' compilation mode
                   14924: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   14925: Manual}) so the source location corresponding to an error or other
                   14926: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   14927: @kbd{C-c C-c} for the error under the cursor).
                   14928: 
1.107     dvdkhlng 14929: @cindex viewing the documentation of a word in Emacs
                   14930: @cindex context-sensitive help
                   14931: Moreover, for words documented in this manual, you can look up the
                   14932: glossary entry quickly by using @kbd{C-h TAB}
                   14933: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
                   14934: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
                   14935: later and does not work for words containing @code{:}.
                   14936: 
                   14937: @menu
                   14938: * Installing gforth.el::        Making Emacs aware of Forth.
                   14939: * Emacs Tags::                  Viewing the source of a word in Emacs.
                   14940: * Hilighting::                  Making Forth code look prettier.
                   14941: * Auto-Indentation::            Customizing auto-indentation.
                   14942: * Blocks Files::                Reading and writing blocks files.
                   14943: @end menu
                   14944: 
                   14945: @c ----------------------------------
1.109     anton    14946: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107     dvdkhlng 14947: @section Installing gforth.el
                   14948: @cindex @file{.emacs}
                   14949: @cindex @file{gforth.el}, installation
                   14950: To make the features from @file{gforth.el} available in Emacs, add
                   14951: the following lines to your @file{.emacs} file:
                   14952: 
                   14953: @example
                   14954: (autoload 'forth-mode "gforth.el")
                   14955: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) 
                   14956:                            auto-mode-alist))
                   14957: (autoload 'forth-block-mode "gforth.el")
                   14958: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode) 
                   14959:                            auto-mode-alist))
                   14960: (add-hook 'forth-mode-hook (function (lambda ()
                   14961:    ;; customize variables here:
                   14962:    (setq forth-indent-level 4)
                   14963:    (setq forth-minor-indent-level 2)
                   14964:    (setq forth-hilight-level 3)
                   14965:    ;;; ...
                   14966: )))
                   14967: @end example
                   14968: 
                   14969: @c ----------------------------------
                   14970: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
                   14971: @section Emacs Tags
1.1       anton    14972: @cindex @file{TAGS} file
                   14973: @cindex @file{etags.fs}
                   14974: @cindex viewing the source of a word in Emacs
1.43      anton    14975: @cindex @code{require}, placement in files
                   14976: @cindex @code{include}, placement in files
1.107     dvdkhlng 14977: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
                   14978: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1       anton    14979: contains the definitions of all words defined afterwards. You can then
1.107     dvdkhlng 14980: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1       anton    14981: several tags files at the same time (e.g., one for the Gforth sources
                   14982: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   14983: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   14984: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43      anton    14985: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
                   14986: with @file{etags.fs}, you should avoid putting definitions both before
                   14987: and after @code{require} etc., otherwise you will see the same file
                   14988: visited several times by commands like @code{tags-search}.
1.1       anton    14989: 
1.107     dvdkhlng 14990: @c ----------------------------------
                   14991: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
                   14992: @section Hilighting
                   14993: @cindex hilighting Forth code in Emacs
                   14994: @cindex highlighting Forth code in Emacs
                   14995: @file{gforth.el} comes with a custom source hilighting engine.  When
                   14996: you open a file in @code{forth-mode}, it will be completely parsed,
                   14997: assigning faces to keywords, comments, strings etc.  While you edit
                   14998: the file, modified regions get parsed and updated on-the-fly. 
                   14999: 
                   15000: Use the variable `forth-hilight-level' to change the level of
                   15001: decoration from 0 (no hilighting at all) to 3 (the default).  Even if
                   15002: you set the hilighting level to 0, the parser will still work in the
                   15003: background, collecting information about whether regions of text are
                   15004: ``compiled'' or ``interpreted''.  Those information are required for
                   15005: auto-indentation to work properly.  Set `forth-disable-parser' to
                   15006: non-nil if your computer is too slow to handle parsing.  This will
                   15007: have an impact on the smartness of the auto-indentation engine,
                   15008: though.
                   15009: 
                   15010: Sometimes Forth sources define new features that should be hilighted,
                   15011: new control structures, defining-words etc.  You can use the variable
                   15012: `forth-custom-words' to make @code{forth-mode} hilight additional
                   15013: words and constructs.  See the docstring of `forth-words' for details
                   15014: (in Emacs, type @kbd{C-h v forth-words}).
                   15015: 
                   15016: `forth-custom-words' is meant to be customized in your
                   15017: @file{.emacs} file.  To customize hilighing in a file-specific manner,
                   15018: set `forth-local-words' in a local-variables section at the end of
                   15019: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
                   15020: 
                   15021: Example:
                   15022: @example
                   15023: 0 [IF]
                   15024:    Local Variables:
                   15025:    forth-local-words:
                   15026:       ((("t:") definition-starter (font-lock-keyword-face . 1)
                   15027:         "[ \t\n]" t name (font-lock-function-name-face . 3))
                   15028:        ((";t") definition-ender (font-lock-keyword-face . 1)))
                   15029:    End:
                   15030: [THEN]
                   15031: @end example
                   15032: 
                   15033: @c ----------------------------------
                   15034: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
                   15035: @section Auto-Indentation
                   15036: @cindex auto-indentation of Forth code in Emacs
                   15037: @cindex indentation of Forth code in Emacs
                   15038: @code{forth-mode} automatically tries to indent lines in a smart way,
                   15039: whenever you type @key{TAB} or break a line with @kbd{C-m}.
                   15040: 
                   15041: Simple customization can be achieved by setting
                   15042: `forth-indent-level' and `forth-minor-indent-level' in your
                   15043: @file{.emacs} file. For historical reasons @file{gforth.el} indents
                   15044: per default by multiples of 4 columns.  To use the more traditional
                   15045: 3-column indentation, add the following lines to your @file{.emacs}:
                   15046: 
                   15047: @example
                   15048: (add-hook 'forth-mode-hook (function (lambda ()
                   15049:    ;; customize variables here:
                   15050:    (setq forth-indent-level 3)
                   15051:    (setq forth-minor-indent-level 1)
                   15052: )))
                   15053: @end example
                   15054: 
                   15055: If you want indentation to recognize non-default words, customize it
                   15056: by setting `forth-custom-indent-words' in your @file{.emacs}.  See the
                   15057: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
                   15058: v forth-indent-words}).
                   15059: 
                   15060: To customize indentation in a file-specific manner, set
                   15061: `forth-local-indent-words' in a local-variables section at the end of
                   15062: your source file (@pxref{Local Variables in Files, Variables,,emacs,
                   15063: Emacs Manual}).
                   15064: 
                   15065: Example:
                   15066: @example
                   15067: 0 [IF]
                   15068:    Local Variables:
                   15069:    forth-local-indent-words:
                   15070:       ((("t:") (0 . 2) (0 . 2))
                   15071:        ((";t") (-2 . 0) (0 . -2)))
                   15072:    End:
                   15073: [THEN]
                   15074: @end example
                   15075: 
                   15076: @c ----------------------------------
1.109     anton    15077: @node Blocks Files,  , Auto-Indentation, Emacs and Gforth
1.107     dvdkhlng 15078: @section Blocks Files
                   15079: @cindex blocks files, use with Emacs
                   15080: @code{forth-mode} Autodetects blocks files by checking whether the
                   15081: length of the first line exceeds 1023 characters.  It then tries to
                   15082: convert the file into normal text format.  When you save the file, it
                   15083: will be written to disk as normal stream-source file.
                   15084: 
                   15085: If you want to write blocks files, use @code{forth-blocks-mode}.  It
                   15086: inherits all the features from @code{forth-mode}, plus some additions:
1.41      anton    15087: 
1.107     dvdkhlng 15088: @itemize @bullet
                   15089: @item
                   15090: Files are written to disk in blocks file format.
                   15091: @item
                   15092: Screen numbers are displayed in the mode line (enumerated beginning
                   15093: with the value of `forth-block-base')
                   15094: @item
                   15095: Warnings are displayed when lines exceed 64 characters.
                   15096: @item
                   15097: The beginning of the currently edited block is marked with an
                   15098: overlay-arrow. 
                   15099: @end itemize
1.41      anton    15100: 
1.107     dvdkhlng 15101: There are some restrictions you should be aware of.  When you open a
                   15102: blocks file that contains tabulator or newline characters, these
                   15103: characters will be translated into spaces when the file is written
                   15104: back to disk.  If tabs or newlines are encountered during blocks file
                   15105: reading, an error is output to the echo area. So have a look at the
                   15106: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1       anton    15107: 
1.107     dvdkhlng 15108: Please consult the docstring of @code{forth-blocks-mode} for more
                   15109: information by typing @kbd{C-h v forth-blocks-mode}).
1.1       anton    15110: 
1.26      crook    15111: @c ******************************************************************
1.1       anton    15112: @node Image Files, Engine, Emacs and Gforth, Top
                   15113: @chapter Image Files
1.26      crook    15114: @cindex image file
                   15115: @cindex @file{.fi} files
1.1       anton    15116: @cindex precompiled Forth code
                   15117: @cindex dictionary in persistent form
                   15118: @cindex persistent form of dictionary
                   15119: 
                   15120: An image file is a file containing an image of the Forth dictionary,
                   15121: i.e., compiled Forth code and data residing in the dictionary.  By
                   15122: convention, we use the extension @code{.fi} for image files.
                   15123: 
                   15124: @menu
1.18      anton    15125: * Image Licensing Issues::      Distribution terms for images.
                   15126: * Image File Background::       Why have image files?
1.67      anton    15127: * Non-Relocatable Image Files::  don't always work.
1.18      anton    15128: * Data-Relocatable Image Files::  are better.
1.67      anton    15129: * Fully Relocatable Image Files::  better yet.
1.18      anton    15130: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.29      crook    15131: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.18      anton    15132: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    15133: @end menu
                   15134: 
1.18      anton    15135: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   15136: @section Image Licensing Issues
                   15137: @cindex license for images
                   15138: @cindex image license
                   15139: 
                   15140: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   15141: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   15142: original image; i.e., according to copyright law it is a derived work of
                   15143: the original image.
                   15144: 
                   15145: Since Gforth is distributed under the GNU GPL, the newly created image
                   15146: falls under the GNU GPL, too. In particular, this means that if you
                   15147: distribute the image, you have to make all of the sources for the image
1.113     anton    15148: available, including those you wrote.  For details see @ref{Copying, ,
1.18      anton    15149: GNU General Public License (Section 3)}.
                   15150: 
                   15151: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   15152: contains only code compiled from the sources you gave it; if none of
                   15153: these sources is under the GPL, the terms discussed above do not apply
                   15154: to the image. However, if your image needs an engine (a gforth binary)
                   15155: that is under the GPL, you should make sure that you distribute both in
                   15156: a way that is at most a @emph{mere aggregation}, if you don't want the
                   15157: terms of the GPL to apply to the image.
                   15158: 
                   15159: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    15160: @section Image File Background
                   15161: @cindex image file background
                   15162: 
1.80      anton    15163: Gforth consists not only of primitives (in the engine), but also of
1.1       anton    15164: definitions written in Forth. Since the Forth compiler itself belongs to
                   15165: those definitions, it is not possible to start the system with the
1.80      anton    15166: engine and the Forth source alone. Therefore we provide the Forth
1.26      crook    15167: code as an image file in nearly executable form. When Gforth starts up,
                   15168: a C routine loads the image file into memory, optionally relocates the
                   15169: addresses, then sets up the memory (stacks etc.) according to
                   15170: information in the image file, and (finally) starts executing Forth
                   15171: code.
1.1       anton    15172: 
1.204     anton    15173: The default image file is @file{gforth.fi} (in the @code{GFORTHPATH}).
                   15174: You can use a different image by using the @code{-i},
                   15175: @code{--image-file} or @code{--appl-image} options (@pxref{Invoking
                   15176: Gforth}), e.g.:
                   15177: 
                   15178: @example
                   15179: gforth-fast -i myimage.fi
                   15180: @end example
                   15181: 
                   15182: There are different variants of image files, and they represent
                   15183: different compromises between the goals of making it easy to generate
                   15184: image files and making them portable.
1.1       anton    15185: 
                   15186: @cindex relocation at run-time
1.26      crook    15187: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1       anton    15188: run-time. This avoids many of the complications discussed below (image
                   15189: files are data relocatable without further ado), but costs performance
1.204     anton    15190: (one addition per memory access) and makes it difficult to pass
                   15191: addresses between Forth and library calls or other programs.
1.1       anton    15192: 
                   15193: @cindex relocation at load-time
1.26      crook    15194: By contrast, the Gforth loader performs relocation at image load time. The
                   15195: loader also has to replace tokens that represent primitive calls with the
1.1       anton    15196: appropriate code-field addresses (or code addresses in the case of
                   15197: direct threading).
                   15198: 
                   15199: There are three kinds of image files, with different degrees of
                   15200: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   15201: image files.
                   15202: 
                   15203: @cindex image file loader
                   15204: @cindex relocating loader
                   15205: @cindex loader for image files
                   15206: These image file variants have several restrictions in common; they are
                   15207: caused by the design of the image file loader:
                   15208: 
                   15209: @itemize @bullet
                   15210: @item
                   15211: There is only one segment; in particular, this means, that an image file
                   15212: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26      crook    15213: them). The contents of the stacks are not represented, either.
1.1       anton    15214: 
                   15215: @item
                   15216: The only kinds of relocation supported are: adding the same offset to
                   15217: all cells that represent data addresses; and replacing special tokens
                   15218: with code addresses or with pieces of machine code.
                   15219: 
                   15220: If any complex computations involving addresses are performed, the
                   15221: results cannot be represented in the image file. Several applications that
                   15222: use such computations come to mind:
1.204     anton    15223: 
1.1       anton    15224: @itemize @minus
                   15225: @item
                   15226: Hashing addresses (or data structures which contain addresses) for table
                   15227: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   15228: purpose, you will have no problem, because the hash tables are
                   15229: recomputed automatically when the system is started. If you use your own
                   15230: hash tables, you will have to do something similar.
                   15231: 
                   15232: @item
                   15233: There's a cute implementation of doubly-linked lists that uses
                   15234: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   15235: in the image file, and restore the doubly-linked representation on
                   15236: startup.@footnote{In my opinion, though, you should think thrice before
                   15237: using a doubly-linked list (whatever implementation).}
                   15238: 
                   15239: @item
                   15240: The code addresses of run-time routines like @code{docol:} cannot be
                   15241: represented in the image file (because their tokens would be replaced by
                   15242: machine code in direct threaded implementations). As a workaround,
                   15243: compute these addresses at run-time with @code{>code-address} from the
                   15244: executions tokens of appropriate words (see the definitions of
1.80      anton    15245: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1       anton    15246: 
                   15247: @item
                   15248: On many architectures addresses are represented in machine code in some
                   15249: shifted or mangled form. You cannot put @code{CODE} words that contain
                   15250: absolute addresses in this form in a relocatable image file. Workarounds
                   15251: are representing the address in some relative form (e.g., relative to
                   15252: the CFA, which is present in some register), or loading the address from
                   15253: a place where it is stored in a non-mangled form.
                   15254: @end itemize
                   15255: @end itemize
                   15256: 
                   15257: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   15258: @section Non-Relocatable Image Files
                   15259: @cindex non-relocatable image files
1.26      crook    15260: @cindex image file, non-relocatable
1.1       anton    15261: 
1.204     anton    15262: These files are simple memory dumps of the dictionary. They are
                   15263: specific to the executable (i.e., @file{gforth} file) they were
                   15264: created with. What's worse, they are specific to the place on which
                   15265: the dictionary resided when the image was created. Now, there is no
1.1       anton    15266: guarantee that the dictionary will reside at the same place the next
                   15267: time you start Gforth, so there's no guarantee that a non-relocatable
1.204     anton    15268: image will work the next time (Gforth will complain instead of
                   15269: crashing, though).  Indeed, on OSs with (enabled) address-space
                   15270: randomization non-relocatable images are unlikely to work.
1.1       anton    15271: 
1.204     anton    15272: You can create a non-relocatable image file with @code{savesystem}, e.g.:
1.1       anton    15273: 
1.204     anton    15274: @example
                   15275: gforth app.fs -e "savesystem app.fi bye"
                   15276: @end example
1.44      crook    15277: 
1.1       anton    15278: doc-savesystem
                   15279: 
1.44      crook    15280: 
1.1       anton    15281: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   15282: @section Data-Relocatable Image Files
                   15283: @cindex data-relocatable image files
1.26      crook    15284: @cindex image file, data-relocatable
1.1       anton    15285: 
1.204     anton    15286: These files contain relocatable data addresses, but fixed code
                   15287: addresses (instead of tokens). They are specific to the executable
                   15288: (i.e., @file{gforth} file) they were created with.  Also, they disable
                   15289: dynamic native code generation (typically a factor of 2 in speed).
                   15290: You get a data-relocatable image, if you pass the engine you want to
                   15291: use through the @code{GFORTHD} environment variable to @file{gforthmi}
                   15292: (@pxref{gforthmi}), e.g.
                   15293: 
                   15294: @example
                   15295: GFORTHD="/usr/bin/gforth-fast --no-dynamic" gforthmi myimage.fi source.fs
                   15296: @end example
                   15297: 
                   15298: Note that the @code{--no-dynamic} is required here for the image to
                   15299: work (otherwise it will contain references to dynamically generated
                   15300: code that is not saved in the image).
                   15301: 
1.1       anton    15302: 
                   15303: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   15304: @section Fully Relocatable Image Files
                   15305: @cindex fully relocatable image files
1.26      crook    15306: @cindex image file, fully relocatable
1.1       anton    15307: 
                   15308: @cindex @file{kern*.fi}, relocatability
                   15309: @cindex @file{gforth.fi}, relocatability
                   15310: These image files have relocatable data addresses, and tokens for code
                   15311: addresses. They can be used with different binaries (e.g., with and
                   15312: without debugging) on the same machine, and even across machines with
1.204     anton    15313: the same data formats (byte order, cell size, floating point format),
                   15314: and they work with dynamic native code generation.  However, they are
                   15315: usually specific to the version of Gforth they were created with. The
                   15316: files @file{gforth.fi} and @file{kernl*.fi} are fully relocatable.
1.1       anton    15317: 
                   15318: There are two ways to create a fully relocatable image file:
                   15319: 
                   15320: @menu
1.29      crook    15321: * gforthmi::                    The normal way
1.1       anton    15322: * cross.fs::                    The hard way
                   15323: @end menu
                   15324: 
                   15325: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   15326: @subsection @file{gforthmi}
                   15327: @cindex @file{comp-i.fs}
                   15328: @cindex @file{gforthmi}
                   15329: 
                   15330: You will usually use @file{gforthmi}. If you want to create an
1.29      crook    15331: image @i{file} that contains everything you would load by invoking
                   15332: Gforth with @code{gforth @i{options}}, you simply say:
1.1       anton    15333: @example
1.29      crook    15334: gforthmi @i{file} @i{options}
1.1       anton    15335: @end example
                   15336: 
                   15337: E.g., if you want to create an image @file{asm.fi} that has the file
                   15338: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   15339: like this:
                   15340: 
                   15341: @example
                   15342: gforthmi asm.fi asm.fs
                   15343: @end example
                   15344: 
1.27      crook    15345: @file{gforthmi} is implemented as a sh script and works like this: It
                   15346: produces two non-relocatable images for different addresses and then
                   15347: compares them. Its output reflects this: first you see the output (if
1.62      crook    15348: any) of the two Gforth invocations that produce the non-relocatable image
1.27      crook    15349: files, then you see the output of the comparing program: It displays the
                   15350: offset used for data addresses and the offset used for code addresses;
1.1       anton    15351: moreover, for each cell that cannot be represented correctly in the
1.44      crook    15352: image files, it displays a line like this:
1.1       anton    15353: 
                   15354: @example
                   15355:      78DC         BFFFFA50         BFFFFA40
                   15356: @end example
                   15357: 
                   15358: This means that at offset $78dc from @code{forthstart}, one input image
                   15359: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   15360: cannot be represented correctly in the output image, you should examine
                   15361: these places in the dictionary and verify that these cells are dead
                   15362: (i.e., not read before they are written).
1.39      anton    15363: 
                   15364: @cindex --application, @code{gforthmi} option
                   15365: If you insert the option @code{--application} in front of the image file
                   15366: name, you will get an image that uses the @code{--appl-image} option
                   15367: instead of the @code{--image-file} option (@pxref{Invoking
                   15368: Gforth}). When you execute such an image on Unix (by typing the image
                   15369: name as command), the Gforth engine will pass all options to the image
                   15370: instead of trying to interpret them as engine options.
1.1       anton    15371: 
1.27      crook    15372: If you type @file{gforthmi} with no arguments, it prints some usage
                   15373: instructions.
                   15374: 
1.1       anton    15375: @cindex @code{savesystem} during @file{gforthmi}
                   15376: @cindex @code{bye} during @file{gforthmi}
                   15377: @cindex doubly indirect threaded code
1.44      crook    15378: @cindex environment variables
                   15379: @cindex @code{GFORTHD} -- environment variable
                   15380: @cindex @code{GFORTH} -- environment variable
1.1       anton    15381: @cindex @code{gforth-ditc}
1.29      crook    15382: There are a few wrinkles: After processing the passed @i{options}, the
1.204     anton    15383: words @code{savesystem} and @code{bye} must be visible. A special
                   15384: doubly indirect threaded version of the @file{gforth} executable is
                   15385: used for creating the non-relocatable images; you can pass the exact
                   15386: filename of this executable through the environment variable
                   15387: @code{GFORTHD} (default: @file{gforth-ditc}); if you pass a version
                   15388: that is not doubly indirect threaded, you will not get a fully
                   15389: relocatable image, but a data-relocatable image
                   15390: (@pxref{Data-Relocatable Image Files}), because there is no code
                   15391: address offset). The normal @file{gforth} executable is used for
                   15392: creating the relocatable image; you can pass the exact filename of
                   15393: this executable through the environment variable @code{GFORTH}.
1.1       anton    15394: 
                   15395: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   15396: @subsection @file{cross.fs}
                   15397: @cindex @file{cross.fs}
                   15398: @cindex cross-compiler
                   15399: @cindex metacompiler
1.47      crook    15400: @cindex target compiler
1.1       anton    15401: 
                   15402: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47      crook    15403: programming language (@pxref{Cross Compiler}).
1.1       anton    15404: 
1.47      crook    15405: @code{cross} allows you to create image files for machines with
1.1       anton    15406: different data sizes and data formats than the one used for generating
                   15407: the image file. You can also use it to create an application image that
                   15408: does not contain a Forth compiler. These features are bought with
                   15409: restrictions and inconveniences in programming. E.g., addresses have to
                   15410: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   15411: order to make the code relocatable.
                   15412: 
                   15413: 
                   15414: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   15415: @section Stack and Dictionary Sizes
                   15416: @cindex image file, stack and dictionary sizes
                   15417: @cindex dictionary size default
                   15418: @cindex stack size default
                   15419: 
                   15420: If you invoke Gforth with a command line flag for the size
                   15421: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   15422: dictionary. If you save the dictionary with @code{savesystem} or create
                   15423: an image with @file{gforthmi}, this size will become the default
                   15424: for the resulting image file. E.g., the following will create a
1.21      crook    15425: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1       anton    15426: 
                   15427: @example
                   15428: gforthmi gforth.fi -m 1M
                   15429: @end example
                   15430: 
                   15431: In other words, if you want to set the default size for the dictionary
                   15432: and the stacks of an image, just invoke @file{gforthmi} with the
                   15433: appropriate options when creating the image.
                   15434: 
                   15435: @cindex stack size, cache-friendly
                   15436: Note: For cache-friendly behaviour (i.e., good performance), you should
                   15437: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   15438: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   15439: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   15440: 
                   15441: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   15442: @section Running Image Files
                   15443: @cindex running image files
                   15444: @cindex invoking image files
                   15445: @cindex image file invocation
                   15446: 
                   15447: @cindex -i, invoke image file
                   15448: @cindex --image file, invoke image file
1.29      crook    15449: You can invoke Gforth with an image file @i{image} instead of the
1.1       anton    15450: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   15451: @example
1.29      crook    15452: gforth -i @i{image}
1.1       anton    15453: @end example
                   15454: 
                   15455: @cindex executable image file
1.26      crook    15456: @cindex image file, executable
1.1       anton    15457: If your operating system supports starting scripts with a line of the
                   15458: form @code{#! ...}, you just have to type the image file name to start
                   15459: Gforth with this image file (note that the file extension @code{.fi} is
1.29      crook    15460: just a convention). I.e., to run Gforth with the image file @i{image},
                   15461: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27      crook    15462: This works because every @code{.fi} file starts with a line of this
                   15463: format:
                   15464: 
                   15465: @example
                   15466: #! /usr/local/bin/gforth-0.4.0 -i
                   15467: @end example
                   15468: 
                   15469: The file and pathname for the Gforth engine specified on this line is
                   15470: the specific Gforth executable that it was built against; i.e. the value
                   15471: of the environment variable @code{GFORTH} at the time that
                   15472: @file{gforthmi} was executed.
1.1       anton    15473: 
1.27      crook    15474: You can make use of the same shell capability to make a Forth source
                   15475: file into an executable. For example, if you place this text in a file:
1.26      crook    15476: 
                   15477: @example
                   15478: #! /usr/local/bin/gforth
                   15479: 
                   15480: ." Hello, world" CR
                   15481: bye
                   15482: @end example
                   15483: 
                   15484: @noindent
1.27      crook    15485: and then make the file executable (chmod +x in Unix), you can run it
1.26      crook    15486: directly from the command line. The sequence @code{#!} is used in two
                   15487: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29      crook    15488: system@footnote{The Unix kernel actually recognises two types of files:
                   15489: executable files and files of data, where the data is processed by an
                   15490: interpreter that is specified on the ``interpreter line'' -- the first
                   15491: line of the file, starting with the sequence #!. There may be a small
                   15492: limit (e.g., 32) on the number of characters that may be specified on
                   15493: the interpreter line.} secondly it is treated as a comment character by
                   15494: Gforth. Because of the second usage, a space is required between
1.80      anton    15495: @code{#!} and the path to the executable (moreover, some Unixes
                   15496: require the sequence @code{#! /}).
1.27      crook    15497: 
                   15498: The disadvantage of this latter technique, compared with using
1.80      anton    15499: @file{gforthmi}, is that it is slightly slower; the Forth source code is
                   15500: compiled on-the-fly, each time the program is invoked.
1.26      crook    15501: 
1.1       anton    15502: doc-#!
                   15503: 
1.44      crook    15504: 
1.1       anton    15505: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   15506: @section Modifying the Startup Sequence
                   15507: @cindex startup sequence for image file
                   15508: @cindex image file initialization sequence
                   15509: @cindex initialization sequence of image file
                   15510: 
1.120     anton    15511: You can add your own initialization to the startup sequence of an image
                   15512: through the deferred word @code{'cold}. @code{'cold} is invoked just
                   15513: before the image-specific command line processing (i.e., loading files
                   15514: and evaluating (@code{-e}) strings) starts.
1.1       anton    15515: 
                   15516: A sequence for adding your initialization usually looks like this:
                   15517: 
                   15518: @example
                   15519: :noname
                   15520:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   15521:     ... \ your stuff
                   15522: ; IS 'cold
                   15523: @end example
                   15524: 
1.157     anton    15525: After @code{'cold}, Gforth processes the image options
                   15526: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
                   15527: another deferred word.  This normally prints Gforth's startup message
                   15528: and does nothing else.
                   15529: 
1.1       anton    15530: @cindex turnkey image files
1.26      crook    15531: @cindex image file, turnkey applications
1.157     anton    15532: So, if you want to make a turnkey image (i.e., an image for an
                   15533: application instead of an extended Forth system), you can do this in
                   15534: two ways:
                   15535: 
                   15536: @itemize @bullet
                   15537: 
                   15538: @item
                   15539: If you want to do your interpretation of the OS command-line
                   15540: arguments, hook into @code{'cold}.  In that case you probably also
                   15541: want to build the image with @code{gforthmi --application}
                   15542: (@pxref{gforthmi}) to keep the engine from processing OS command line
                   15543: options.  You can then do your own command-line processing with
                   15544: @code{next-arg} 
                   15545: 
                   15546: @item
                   15547: If you want to have the normal Gforth processing of OS command-line
                   15548: arguments, hook into @code{bootmessage}.
                   15549: 
                   15550: @end itemize
                   15551: 
                   15552: In either case, you probably do not want the word that you execute in
                   15553: these hooks to exit normally, but use @code{bye} or @code{throw}.
                   15554: Otherwise the Gforth startup process would continue and eventually
                   15555: present the Forth command line to the user.
1.26      crook    15556: 
                   15557: doc-'cold
1.157     anton    15558: doc-bootmessage
1.44      crook    15559: 
1.1       anton    15560: @c ******************************************************************
1.113     anton    15561: @node Engine, Cross Compiler, Image Files, Top
1.1       anton    15562: @chapter Engine
                   15563: @cindex engine
                   15564: @cindex virtual machine
                   15565: 
1.26      crook    15566: Reading this chapter is not necessary for programming with Gforth. It
1.1       anton    15567: may be helpful for finding your way in the Gforth sources.
                   15568: 
1.109     anton    15569: The ideas in this section have also been published in the following
                   15570: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
                   15571: Forth-Tagung '93; M. Anton Ertl,
                   15572: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
                   15573: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
                   15574: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
                   15575: Threaded code variations and optimizations (extended version)}},
                   15576: Forth-Tagung '02.
1.1       anton    15577: 
                   15578: @menu
                   15579: * Portability::                 
                   15580: * Threading::                   
                   15581: * Primitives::                  
                   15582: * Performance::                 
                   15583: @end menu
                   15584: 
                   15585: @node Portability, Threading, Engine, Engine
                   15586: @section Portability
                   15587: @cindex engine portability
                   15588: 
1.26      crook    15589: An important goal of the Gforth Project is availability across a wide
                   15590: range of personal machines. fig-Forth, and, to a lesser extent, F83,
                   15591: achieved this goal by manually coding the engine in assembly language
                   15592: for several then-popular processors. This approach is very
                   15593: labor-intensive and the results are short-lived due to progress in
                   15594: computer architecture.
1.1       anton    15595: 
                   15596: @cindex C, using C for the engine
                   15597: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   15598: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   15599: particularly popular for UNIX-based Forths due to the large variety of
                   15600: architectures of UNIX machines. Unfortunately an implementation in C
                   15601: does not mix well with the goals of efficiency and with using
                   15602: traditional techniques: Indirect or direct threading cannot be expressed
                   15603: in C, and switch threading, the fastest technique available in C, is
                   15604: significantly slower. Another problem with C is that it is very
                   15605: cumbersome to express double integer arithmetic.
                   15606: 
                   15607: @cindex GNU C for the engine
                   15608: @cindex long long
                   15609: Fortunately, there is a portable language that does not have these
                   15610: limitations: GNU C, the version of C processed by the GNU C compiler
                   15611: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   15612: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   15613: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   15614: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   15615: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109     anton    15616: double numbers on many systems.  GNU C is freely available on all
1.1       anton    15617: important (and many unimportant) UNIX machines, VMS, 80386s running
                   15618: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   15619: on all these machines.
                   15620: 
                   15621: Writing in a portable language has the reputation of producing code that
                   15622: is slower than assembly. For our Forth engine we repeatedly looked at
                   15623: the code produced by the compiler and eliminated most compiler-induced
                   15624: inefficiencies by appropriate changes in the source code.
                   15625: 
                   15626: @cindex explicit register declarations
                   15627: @cindex --enable-force-reg, configuration flag
                   15628: @cindex -DFORCE_REG
                   15629: However, register allocation cannot be portably influenced by the
                   15630: programmer, leading to some inefficiencies on register-starved
                   15631: machines. We use explicit register declarations (@pxref{Explicit Reg
                   15632: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   15633: improve the speed on some machines. They are turned on by using the
                   15634: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   15635: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   15636: machine, but also on the compiler version: On some machines some
                   15637: compiler versions produce incorrect code when certain explicit register
                   15638: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   15639: 
                   15640: @node Threading, Primitives, Portability, Engine
                   15641: @section Threading
                   15642: @cindex inner interpreter implementation
                   15643: @cindex threaded code implementation
                   15644: 
                   15645: @cindex labels as values
                   15646: GNU C's labels as values extension (available since @code{gcc-2.0},
                   15647: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29      crook    15648: makes it possible to take the address of @i{label} by writing
                   15649: @code{&&@i{label}}.  This address can then be used in a statement like
                   15650: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1       anton    15651: @code{goto x}.
                   15652: 
1.26      crook    15653: @cindex @code{NEXT}, indirect threaded
1.1       anton    15654: @cindex indirect threaded inner interpreter
                   15655: @cindex inner interpreter, indirect threaded
1.26      crook    15656: With this feature an indirect threaded @code{NEXT} looks like:
1.1       anton    15657: @example
                   15658: cfa = *ip++;
                   15659: ca = *cfa;
                   15660: goto *ca;
                   15661: @end example
                   15662: @cindex instruction pointer
                   15663: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   15664: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   15665: execution token and points to the code field of the next word to be
                   15666: executed; The @code{ca} (code address) fetched from there points to some
                   15667: executable code, e.g., a primitive or the colon definition handler
                   15668: @code{docol}.
                   15669: 
1.26      crook    15670: @cindex @code{NEXT}, direct threaded
1.1       anton    15671: @cindex direct threaded inner interpreter
                   15672: @cindex inner interpreter, direct threaded
                   15673: Direct threading is even simpler:
                   15674: @example
                   15675: ca = *ip++;
                   15676: goto *ca;
                   15677: @end example
                   15678: 
                   15679: Of course we have packaged the whole thing neatly in macros called
1.26      crook    15680: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1       anton    15681: 
                   15682: @menu
                   15683: * Scheduling::                  
                   15684: * Direct or Indirect Threaded?::  
1.109     anton    15685: * Dynamic Superinstructions::   
1.1       anton    15686: * DOES>::                       
                   15687: @end menu
                   15688: 
                   15689: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   15690: @subsection Scheduling
                   15691: @cindex inner interpreter optimization
                   15692: 
                   15693: There is a little complication: Pipelined and superscalar processors,
                   15694: i.e., RISC and some modern CISC machines can process independent
                   15695: instructions while waiting for the results of an instruction. The
                   15696: compiler usually reorders (schedules) the instructions in a way that
                   15697: achieves good usage of these delay slots. However, on our first tries
                   15698: the compiler did not do well on scheduling primitives. E.g., for
                   15699: @code{+} implemented as
                   15700: @example
                   15701: n=sp[0]+sp[1];
                   15702: sp++;
                   15703: sp[0]=n;
                   15704: NEXT;
                   15705: @end example
1.81      anton    15706: the @code{NEXT} comes strictly after the other code, i.e., there is
                   15707: nearly no scheduling. After a little thought the problem becomes clear:
                   15708: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21      crook    15709: addresses (and the version of @code{gcc} we used would not know it even
                   15710: if it was possible), so it could not move the load of the cfa above the
                   15711: store to the TOS. Indeed the pointers could be the same, if code on or
                   15712: very near the top of stack were executed. In the interest of speed we
                   15713: chose to forbid this probably unused ``feature'' and helped the compiler
1.81      anton    15714: in scheduling: @code{NEXT} is divided into several parts:
                   15715: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
                   15716: like:
1.1       anton    15717: @example
1.81      anton    15718: NEXT_P0;
1.1       anton    15719: n=sp[0]+sp[1];
                   15720: sp++;
                   15721: NEXT_P1;
                   15722: sp[0]=n;
                   15723: NEXT_P2;
                   15724: @end example
                   15725: 
1.81      anton    15726: There are various schemes that distribute the different operations of
                   15727: NEXT between these parts in several ways; in general, different schemes
                   15728: perform best on different processors.  We use a scheme for most
                   15729: architectures that performs well for most processors of this
1.109     anton    15730: architecture; in the future we may switch to benchmarking and chosing
1.81      anton    15731: the scheme on installation time.
                   15732: 
1.1       anton    15733: 
1.109     anton    15734: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1       anton    15735: @subsection Direct or Indirect Threaded?
                   15736: @cindex threading, direct or indirect?
                   15737: 
1.109     anton    15738: Threaded forth code consists of references to primitives (simple machine
                   15739: code routines like @code{+}) and to non-primitives (e.g., colon
                   15740: definitions, variables, constants); for a specific class of
                   15741: non-primitives (e.g., variables) there is one code routine (e.g.,
                   15742: @code{dovar}), but each variable needs a separate reference to its data.
                   15743: 
                   15744: Traditionally Forth has been implemented as indirect threaded code,
                   15745: because this allows to use only one cell to reference a non-primitive
                   15746: (basically you point to the data, and find the code address there).
                   15747: 
                   15748: @cindex primitive-centric threaded code
                   15749: However, threaded code in Gforth (since 0.6.0) uses two cells for
                   15750: non-primitives, one for the code address, and one for the data address;
                   15751: the data pointer is an immediate argument for the virtual machine
                   15752: instruction represented by the code address.  We call this
                   15753: @emph{primitive-centric} threaded code, because all code addresses point
                   15754: to simple primitives.  E.g., for a variable, the code address is for
                   15755: @code{lit} (also used for integer literals like @code{99}).
                   15756: 
                   15757: Primitive-centric threaded code allows us to use (faster) direct
                   15758: threading as dispatch method, completely portably (direct threaded code
                   15759: in Gforth before 0.6.0 required architecture-specific code).  It also
                   15760: eliminates the performance problems related to I-cache consistency that
                   15761: 386 implementations have with direct threaded code, and allows
                   15762: additional optimizations.
                   15763: 
                   15764: @cindex hybrid direct/indirect threaded code
                   15765: There is a catch, however: the @var{xt} parameter of @code{execute} can
                   15766: occupy only one cell, so how do we pass non-primitives with their code
                   15767: @emph{and} data addresses to them?  Our answer is to use indirect
                   15768: threaded dispatch for @code{execute} and other words that use a
                   15769: single-cell xt.  So, normal threaded code in colon definitions uses
                   15770: direct threading, and @code{execute} and similar words, which dispatch
                   15771: to xts on the data stack, use indirect threaded code.  We call this
                   15772: @emph{hybrid direct/indirect} threaded code.
                   15773: 
                   15774: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
                   15775: @cindex gforth engine
                   15776: @cindex gforth-fast engine
                   15777: The engines @command{gforth} and @command{gforth-fast} use hybrid
                   15778: direct/indirect threaded code.  This means that with these engines you
                   15779: cannot use @code{,} to compile an xt.  Instead, you have to use
                   15780: @code{compile,}.
                   15781: 
                   15782: @cindex gforth-itc engine
1.115     anton    15783: If you want to compile xts with @code{,}, use @command{gforth-itc}.
                   15784: This engine uses plain old indirect threaded code.  It still compiles in
                   15785: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109     anton    15786: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115     anton    15787: ... [}).  If you want to do that, you have to use @command{gforth-itc}
1.109     anton    15788: and execute @code{' , is compile,}.  Your program can check if it is
                   15789: running on a hybrid direct/indirect threaded engine or a pure indirect
                   15790: threaded engine with @code{threading-method} (@pxref{Threading Words}).
                   15791: 
                   15792: 
                   15793: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
                   15794: @subsection Dynamic Superinstructions
                   15795: @cindex Dynamic superinstructions with replication
                   15796: @cindex Superinstructions
                   15797: @cindex Replication
                   15798: 
                   15799: The engines @command{gforth} and @command{gforth-fast} use another
                   15800: optimization: Dynamic superinstructions with replication.  As an
                   15801: example, consider the following colon definition:
                   15802: 
                   15803: @example
                   15804: : squared ( n1 -- n2 )
                   15805:   dup * ;
                   15806: @end example
                   15807: 
                   15808: Gforth compiles this into the threaded code sequence
                   15809: 
                   15810: @example
                   15811: dup
                   15812: *
                   15813: ;s
                   15814: @end example
                   15815: 
                   15816: In normal direct threaded code there is a code address occupying one
                   15817: cell for each of these primitives.  Each code address points to a
                   15818: machine code routine, and the interpreter jumps to this machine code in
                   15819: order to execute the primitive.  The routines for these three
                   15820: primitives are (in @command{gforth-fast} on the 386):
                   15821: 
                   15822: @example
                   15823: Code dup  
                   15824: ( $804B950 )  add     esi , # -4  \ $83 $C6 $FC 
                   15825: ( $804B953 )  add     ebx , # 4  \ $83 $C3 $4 
                   15826: ( $804B956 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
                   15827: ( $804B959 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   15828: end-code
                   15829: Code *  
                   15830: ( $804ACC4 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
                   15831: ( $804ACC7 )  add     esi , # 4  \ $83 $C6 $4 
                   15832: ( $804ACCA )  add     ebx , # 4  \ $83 $C3 $4 
                   15833: ( $804ACCD )  imul    ecx , eax  \ $F $AF $C8 
                   15834: ( $804ACD0 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   15835: end-code
                   15836: Code ;s  
                   15837: ( $804A693 )  mov     eax , dword ptr [edi]  \ $8B $7 
                   15838: ( $804A695 )  add     edi , # 4  \ $83 $C7 $4 
                   15839: ( $804A698 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
                   15840: ( $804A69B )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   15841: end-code
                   15842: @end example
                   15843: 
                   15844: With dynamic superinstructions and replication the compiler does not
                   15845: just lay down the threaded code, but also copies the machine code
                   15846: fragments, usually without the jump at the end.
                   15847: 
                   15848: @example
                   15849: ( $4057D27D )  add     esi , # -4  \ $83 $C6 $FC 
                   15850: ( $4057D280 )  add     ebx , # 4  \ $83 $C3 $4 
                   15851: ( $4057D283 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
                   15852: ( $4057D286 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
                   15853: ( $4057D289 )  add     esi , # 4  \ $83 $C6 $4 
                   15854: ( $4057D28C )  add     ebx , # 4  \ $83 $C3 $4 
                   15855: ( $4057D28F )  imul    ecx , eax  \ $F $AF $C8 
                   15856: ( $4057D292 )  mov     eax , dword ptr [edi]  \ $8B $7 
                   15857: ( $4057D294 )  add     edi , # 4  \ $83 $C7 $4 
                   15858: ( $4057D297 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
                   15859: ( $4057D29A )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   15860: @end example
                   15861: 
                   15862: Only when a threaded-code control-flow change happens (e.g., in
                   15863: @code{;s}), the jump is appended.  This optimization eliminates many of
                   15864: these jumps and makes the rest much more predictable.  The speedup
                   15865: depends on the processor and the application; on the Athlon and Pentium
                   15866: III this optimization typically produces a speedup by a factor of 2.
                   15867: 
                   15868: The code addresses in the direct-threaded code are set to point to the
                   15869: appropriate points in the copied machine code, in this example like
                   15870: this:
1.1       anton    15871: 
1.109     anton    15872: @example
                   15873: primitive  code address
                   15874:    dup       $4057D27D
                   15875:    *         $4057D286
                   15876:    ;s        $4057D292
                   15877: @end example
                   15878: 
                   15879: Thus there can be threaded-code jumps to any place in this piece of
                   15880: code.  This also simplifies decompilation quite a bit.
                   15881: 
                   15882: @cindex --no-dynamic command-line option
                   15883: @cindex --no-super command-line option
                   15884: You can disable this optimization with @option{--no-dynamic}.  You can
                   15885: use the copying without eliminating the jumps (i.e., dynamic
                   15886: replication, but without superinstructions) with @option{--no-super};
                   15887: this gives the branch prediction benefit alone; the effect on
1.110     anton    15888: performance depends on the CPU; on the Athlon and Pentium III the
                   15889: speedup is a little less than for dynamic superinstructions with
                   15890: replication.
                   15891: 
                   15892: @cindex patching threaded code
                   15893: One use of these options is if you want to patch the threaded code.
                   15894: With superinstructions, many of the dispatch jumps are eliminated, so
                   15895: patching often has no effect.  These options preserve all the dispatch
                   15896: jumps.
1.109     anton    15897: 
                   15898: @cindex --dynamic command-line option
1.110     anton    15899: On some machines dynamic superinstructions are disabled by default,
                   15900: because it is unsafe on these machines.  However, if you feel
                   15901: adventurous, you can enable it with @option{--dynamic}.
1.109     anton    15902: 
                   15903: @node DOES>,  , Dynamic Superinstructions, Threading
1.1       anton    15904: @subsection DOES>
                   15905: @cindex @code{DOES>} implementation
                   15906: 
1.26      crook    15907: @cindex @code{dodoes} routine
                   15908: @cindex @code{DOES>}-code
1.1       anton    15909: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   15910: the chunk of code executed by every word defined by a
1.109     anton    15911: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
                   15912: this is only needed if the xt of the word is @code{execute}d. The main
                   15913: problem here is: How to find the Forth code to be executed, i.e. the
                   15914: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
                   15915: solutions:
1.1       anton    15916: 
1.21      crook    15917: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109     anton    15918: @code{DOES>}-code address is stored in the cell after the code address
                   15919: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
                   15920: illegal in the Forth-79 and all later standards, because in fig-Forth
                   15921: this address lies in the body (which is illegal in these
                   15922: standards). However, by making the code field larger for all words this
                   15923: solution becomes legal again.  We use this approach.  Leaving a cell
                   15924: unused in most words is a bit wasteful, but on the machines we are
                   15925: targeting this is hardly a problem.
                   15926: 
1.1       anton    15927: 
                   15928: @node Primitives, Performance, Threading, Engine
                   15929: @section Primitives
                   15930: @cindex primitives, implementation
                   15931: @cindex virtual machine instructions, implementation
                   15932: 
                   15933: @menu
                   15934: * Automatic Generation::        
                   15935: * TOS Optimization::            
                   15936: * Produced code::               
                   15937: @end menu
                   15938: 
                   15939: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   15940: @subsection Automatic Generation
                   15941: @cindex primitives, automatic generation
                   15942: 
                   15943: @cindex @file{prims2x.fs}
1.109     anton    15944: 
1.1       anton    15945: Since the primitives are implemented in a portable language, there is no
                   15946: longer any need to minimize the number of primitives. On the contrary,
                   15947: having many primitives has an advantage: speed. In order to reduce the
                   15948: number of errors in primitives and to make programming them easier, we
1.109     anton    15949: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
                   15950: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
                   15951: generates most (and sometimes all) of the C code for a primitive from
                   15952: the stack effect notation.  The source for a primitive has the following
                   15953: form:
1.1       anton    15954: 
                   15955: @cindex primitive source format
                   15956: @format
1.58      anton    15957: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
1.29      crook    15958: [@code{""}@i{glossary entry}@code{""}]
                   15959: @i{C code}
1.1       anton    15960: [@code{:}
1.29      crook    15961: @i{Forth code}]
1.1       anton    15962: @end format
                   15963: 
                   15964: The items in brackets are optional. The category and glossary fields
                   15965: are there for generating the documentation, the Forth code is there
                   15966: for manual implementations on machines without GNU C. E.g., the source
                   15967: for the primitive @code{+} is:
                   15968: @example
1.58      anton    15969: +    ( n1 n2 -- n )   core    plus
1.1       anton    15970: n = n1+n2;
                   15971: @end example
                   15972: 
                   15973: This looks like a specification, but in fact @code{n = n1+n2} is C
                   15974: code. Our primitive generation tool extracts a lot of information from
                   15975: the stack effect notations@footnote{We use a one-stack notation, even
                   15976: though we have separate data and floating-point stacks; The separate
                   15977: notation can be generated easily from the unified notation.}: The number
                   15978: of items popped from and pushed on the stack, their type, and by what
                   15979: name they are referred to in the C code. It then generates a C code
                   15980: prelude and postlude for each primitive. The final C code for @code{+}
                   15981: looks like this:
                   15982: 
                   15983: @example
1.46      pazsan   15984: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
1.1       anton    15985: /*  */                          /* documentation */
1.81      anton    15986: NAME("+")                       /* debugging output (with -DDEBUG) */
1.1       anton    15987: @{
                   15988: DEF_CA                          /* definition of variable ca (indirect threading) */
                   15989: Cell n1;                        /* definitions of variables */
                   15990: Cell n2;
                   15991: Cell n;
1.81      anton    15992: NEXT_P0;                        /* NEXT part 0 */
1.1       anton    15993: n1 = (Cell) sp[1];              /* input */
                   15994: n2 = (Cell) TOS;
                   15995: sp += 1;                        /* stack adjustment */
                   15996: @{
                   15997: n = n1+n2;                      /* C code taken from the source */
                   15998: @}
                   15999: NEXT_P1;                        /* NEXT part 1 */
                   16000: TOS = (Cell)n;                  /* output */
                   16001: NEXT_P2;                        /* NEXT part 2 */
                   16002: @}
                   16003: @end example
                   16004: 
                   16005: This looks long and inefficient, but the GNU C compiler optimizes quite
                   16006: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   16007: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   16008: using them as intermediate storage also adds no cost.
                   16009: 
1.26      crook    16010: There are also other optimizations that are not illustrated by this
                   16011: example: assignments between simple variables are usually for free (copy
1.1       anton    16012: propagation). If one of the stack items is not used by the primitive
                   16013: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   16014: (dead code elimination). On the other hand, there are some things that
                   16015: the compiler does not do, therefore they are performed by
                   16016: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   16017: a stack item to the place where it just came from (e.g., @code{over}).
                   16018: 
                   16019: While programming a primitive is usually easy, there are a few cases
                   16020: where the programmer has to take the actions of the generator into
                   16021: account, most notably @code{?dup}, but also words that do not (always)
1.26      crook    16022: fall through to @code{NEXT}.
1.109     anton    16023: 
                   16024: For more information
1.1       anton    16025: 
                   16026: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   16027: @subsection TOS Optimization
                   16028: @cindex TOS optimization for primitives
                   16029: @cindex primitives, keeping the TOS in a register
                   16030: 
                   16031: An important optimization for stack machine emulators, e.g., Forth
                   16032: engines, is keeping  one or more of the top stack items in
1.29      crook    16033: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
                   16034: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1       anton    16035: @itemize @bullet
                   16036: @item
1.29      crook    16037: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1       anton    16038: due to fewer loads from and stores to the stack.
1.29      crook    16039: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
                   16040: @i{y<n}, due to additional moves between registers.
1.1       anton    16041: @end itemize
                   16042: 
                   16043: @cindex -DUSE_TOS
                   16044: @cindex -DUSE_NO_TOS
                   16045: In particular, keeping one item in a register is never a disadvantage,
                   16046: if there are enough registers. Keeping two items in registers is a
                   16047: disadvantage for frequent words like @code{?branch}, constants,
                   16048: variables, literals and @code{i}. Therefore our generator only produces
                   16049: code that keeps zero or one items in registers. The generated C code
                   16050: covers both cases; the selection between these alternatives is made at
                   16051: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   16052: code for @code{+} is just a simple variable name in the one-item case,
                   16053: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   16054: GNU C compiler tries to keep simple variables like @code{TOS} in
                   16055: registers, and it usually succeeds, if there are enough registers.
                   16056: 
                   16057: @cindex -DUSE_FTOS
                   16058: @cindex -DUSE_NO_FTOS
                   16059: The primitive generator performs the TOS optimization for the
                   16060: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   16061: operations the benefit of this optimization is even larger:
                   16062: floating-point operations take quite long on most processors, but can be
                   16063: performed in parallel with other operations as long as their results are
                   16064: not used. If the FP-TOS is kept in a register, this works. If
                   16065: it is kept on the stack, i.e., in memory, the store into memory has to
                   16066: wait for the result of the floating-point operation, lengthening the
                   16067: execution time of the primitive considerably.
                   16068: 
                   16069: The TOS optimization makes the automatic generation of primitives a
                   16070: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   16071: @code{TOS} is not sufficient. There are some special cases to
                   16072: consider:
                   16073: @itemize @bullet
                   16074: @item In the case of @code{dup ( w -- w w )} the generator must not
                   16075: eliminate the store to the original location of the item on the stack,
                   16076: if the TOS optimization is turned on.
                   16077: @item Primitives with stack effects of the form @code{--}
1.29      crook    16078: @i{out1}...@i{outy} must store the TOS to the stack at the start.
                   16079: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1       anton    16080: must load the TOS from the stack at the end. But for the null stack
                   16081: effect @code{--} no stores or loads should be generated.
                   16082: @end itemize
                   16083: 
                   16084: @node Produced code,  , TOS Optimization, Primitives
                   16085: @subsection Produced code
                   16086: @cindex primitives, assembly code listing
                   16087: 
                   16088: @cindex @file{engine.s}
                   16089: To see what assembly code is produced for the primitives on your machine
                   16090: with your compiler and your flag settings, type @code{make engine.s} and
1.81      anton    16091: look at the resulting file @file{engine.s}.  Alternatively, you can also
                   16092: disassemble the code of primitives with @code{see} on some architectures.
1.1       anton    16093: 
                   16094: @node  Performance,  , Primitives, Engine
                   16095: @section Performance
                   16096: @cindex performance of some Forth interpreters
                   16097: @cindex engine performance
                   16098: @cindex benchmarking Forth systems
                   16099: @cindex Gforth performance
                   16100: 
                   16101: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112     anton    16102: impossible to write a significantly faster threaded-code engine.
1.1       anton    16103: 
                   16104: On register-starved machines like the 386 architecture processors
                   16105: improvements are possible, because @code{gcc} does not utilize the
                   16106: registers as well as a human, even with explicit register declarations;
                   16107: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   16108: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   16109: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40      anton    16110: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
                   16111: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
                   16112: registers fit in real registers (and we can even afford to use the TOS
                   16113: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112     anton    16114: earlier results.  And dynamic superinstructions provide another speedup
                   16115: (but only around a factor 1.2 on the 486).
1.1       anton    16116: 
                   16117: @cindex Win32Forth performance
                   16118: @cindex NT Forth performance
                   16119: @cindex eforth performance
                   16120: @cindex ThisForth performance
                   16121: @cindex PFE performance
                   16122: @cindex TILE performance
1.81      anton    16123: The potential advantage of assembly language implementations is not
1.112     anton    16124: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81      anton    16125: (direct threaded, compiled with @code{gcc-2.95.1} and
                   16126: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
                   16127: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
                   16128: (with and without peephole (aka pinhole) optimization of the threaded
                   16129: code); all these systems were written in assembly language. We also
                   16130: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
                   16131: with @code{gcc-2.6.3} with the default configuration for Linux:
                   16132: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
                   16133: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
                   16134: employs peephole optimization of the threaded code) and TILE (compiled
                   16135: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
                   16136: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
                   16137: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
                   16138: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
                   16139: then extended it to run the benchmarks, added the peephole optimizer,
                   16140: ran the benchmarks and reported the results.
1.40      anton    16141: 
1.1       anton    16142: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   16143: matrix multiplication come from the Stanford integer benchmarks and have
                   16144: been translated into Forth by Martin Fraeman; we used the versions
                   16145: included in the TILE Forth package, but with bigger data set sizes; and
                   16146: a recursive Fibonacci number computation for benchmarking calling
                   16147: performance. The following table shows the time taken for the benchmarks
                   16148: scaled by the time taken by Gforth (in other words, it shows the speedup
                   16149: factor that Gforth achieved over the other systems).
                   16150: 
                   16151: @example
1.112     anton    16152: relative       Win32-    NT       eforth       This-      
                   16153: time     Gforth Forth Forth eforth  +opt   PFE Forth  TILE
                   16154: sieve      1.00  2.16  1.78   2.16  1.32  2.46  4.96 13.37
                   16155: bubble     1.00  1.93  2.07   2.18  1.29  2.21        5.70
                   16156: matmul     1.00  1.92  1.76   1.90  0.96  2.06        5.32
                   16157: fib        1.00  2.32  2.03   1.86  1.31  2.64  4.55  6.54
1.1       anton    16158: @end example
                   16159: 
1.26      crook    16160: You may be quite surprised by the good performance of Gforth when
                   16161: compared with systems written in assembly language. One important reason
                   16162: for the disappointing performance of these other systems is probably
                   16163: that they are not written optimally for the 486 (e.g., they use the
                   16164: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
                   16165: but costly method for relocating the Forth image: like @code{cforth}, it
                   16166: computes the actual addresses at run time, resulting in two address
                   16167: computations per @code{NEXT} (@pxref{Image File Background}).
                   16168: 
1.1       anton    16169: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   16170: explained with the self-imposed restriction of the latter systems to
                   16171: standard C, which makes efficient threading impossible (however, the
1.4       anton    16172: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    16173: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   16174: Moreover, current C compilers have a hard time optimizing other aspects
                   16175: of the ThisForth and the TILE source.
                   16176: 
1.26      crook    16177: The performance of Gforth on 386 architecture processors varies widely
                   16178: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
                   16179: allocate any of the virtual machine registers into real machine
                   16180: registers by itself and would not work correctly with explicit register
1.112     anton    16181: declarations, giving a significantly slower engine (on a 486DX2/66
                   16182: running the Sieve) than the one measured above.
1.1       anton    16183: 
1.26      crook    16184: Note that there have been several releases of Win32Forth since the
                   16185: release presented here, so the results presented above may have little
1.40      anton    16186: predictive value for the performance of Win32Forth today (results for
                   16187: the current release on an i486DX2/66 are welcome).
1.1       anton    16188: 
                   16189: @cindex @file{Benchres}
1.66      anton    16190: In
                   16191: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
                   16192: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1       anton    16193: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66      anton    16194: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
                   16195: several native code systems; that version of Gforth is slower on a 486
1.112     anton    16196: than the version used here. You can find a newer version of these
                   16197: measurements at
1.47      crook    16198: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1       anton    16199: find numbers for Gforth on various machines in @file{Benchres}.
                   16200: 
1.26      crook    16201: @c ******************************************************************
1.113     anton    16202: @c @node Binding to System Library, Cross Compiler, Engine, Top
                   16203: @c @chapter Binding to System Library
1.13      pazsan   16204: 
1.113     anton    16205: @c ****************************************************************
                   16206: @node Cross Compiler, Bugs, Engine, Top
1.14      pazsan   16207: @chapter Cross Compiler
1.47      crook    16208: @cindex @file{cross.fs}
                   16209: @cindex cross-compiler
                   16210: @cindex metacompiler
                   16211: @cindex target compiler
1.13      pazsan   16212: 
1.46      pazsan   16213: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
                   16214: mostly written in Forth, including crucial parts like the outer
                   16215: interpreter and compiler, it needs compiled Forth code to get
                   16216: started. The cross compiler allows to create new images for other
                   16217: architectures, even running under another Forth system.
1.13      pazsan   16218: 
                   16219: @menu
1.67      anton    16220: * Using the Cross Compiler::    
                   16221: * How the Cross Compiler Works::  
1.13      pazsan   16222: @end menu
                   16223: 
1.21      crook    16224: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14      pazsan   16225: @section Using the Cross Compiler
1.46      pazsan   16226: 
                   16227: The cross compiler uses a language that resembles Forth, but isn't. The
                   16228: main difference is that you can execute Forth code after definition,
                   16229: while you usually can't execute the code compiled by cross, because the
                   16230: code you are compiling is typically for a different computer than the
                   16231: one you are compiling on.
                   16232: 
1.81      anton    16233: @c anton: This chapter is somewhat different from waht I would expect: I
                   16234: @c would expect an explanation of the cross language and how to create an
                   16235: @c application image with it.  The section explains some aspects of
                   16236: @c creating a Gforth kernel.
                   16237: 
1.46      pazsan   16238: The Makefile is already set up to allow you to create kernels for new
                   16239: architectures with a simple make command. The generic kernels using the
                   16240: GCC compiled virtual machine are created in the normal build process
                   16241: with @code{make}. To create a embedded Gforth executable for e.g. the
                   16242: 8086 processor (running on a DOS machine), type
                   16243: 
                   16244: @example
                   16245: make kernl-8086.fi
                   16246: @end example
                   16247: 
                   16248: This will use the machine description from the @file{arch/8086}
                   16249: directory to create a new kernel. A machine file may look like that:
                   16250: 
                   16251: @example
                   16252: \ Parameter for target systems                         06oct92py
                   16253: 
                   16254:     4 Constant cell             \ cell size in bytes
                   16255:     2 Constant cell<<           \ cell shift to bytes
                   16256:     5 Constant cell>bit         \ cell shift to bits
                   16257:     8 Constant bits/char        \ bits per character
                   16258:     8 Constant bits/byte        \ bits per byte [default: 8]
                   16259:     8 Constant float            \ bytes per float
                   16260:     8 Constant /maxalign        \ maximum alignment in bytes
                   16261: false Constant bigendian        \ byte order
                   16262: ( true=big, false=little )
                   16263: 
                   16264: include machpc.fs               \ feature list
                   16265: @end example
                   16266: 
                   16267: This part is obligatory for the cross compiler itself, the feature list
                   16268: is used by the kernel to conditionally compile some features in and out,
                   16269: depending on whether the target supports these features.
                   16270: 
                   16271: There are some optional features, if you define your own primitives,
                   16272: have an assembler, or need special, nonstandard preparation to make the
1.81      anton    16273: boot process work. @code{asm-include} includes an assembler,
1.46      pazsan   16274: @code{prims-include} includes primitives, and @code{>boot} prepares for
                   16275: booting.
                   16276: 
                   16277: @example
                   16278: : asm-include    ." Include assembler" cr
                   16279:   s" arch/8086/asm.fs" included ;
                   16280: 
                   16281: : prims-include  ." Include primitives" cr
                   16282:   s" arch/8086/prim.fs" included ;
                   16283: 
                   16284: : >boot          ." Prepare booting" cr
                   16285:   s" ' boot >body into-forth 1+ !" evaluate ;
                   16286: @end example
                   16287: 
                   16288: These words are used as sort of macro during the cross compilation in
1.81      anton    16289: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46      pazsan   16290: be possible --- but more complicated --- to write a new kernel project
                   16291: file, too.
                   16292: 
                   16293: @file{kernel/main.fs} expects the machine description file name on the
                   16294: stack; the cross compiler itself (@file{cross.fs}) assumes that either
                   16295: @code{mach-file} leaves a counted string on the stack, or
                   16296: @code{machine-file} leaves an address, count pair of the filename on the
                   16297: stack.
                   16298: 
                   16299: The feature list is typically controlled using @code{SetValue}, generic
                   16300: files that are used by several projects can use @code{DefaultValue}
                   16301: instead. Both functions work like @code{Value}, when the value isn't
                   16302: defined, but @code{SetValue} works like @code{to} if the value is
                   16303: defined, and @code{DefaultValue} doesn't set anything, if the value is
                   16304: defined.
                   16305: 
                   16306: @example
                   16307: \ generic mach file for pc gforth                       03sep97jaw
                   16308: 
                   16309: true DefaultValue NIL  \ relocating
                   16310: 
                   16311: >ENVIRON
                   16312: 
                   16313: true DefaultValue file          \ controls the presence of the
                   16314:                                 \ file access wordset
                   16315: true DefaultValue OS            \ flag to indicate a operating system
                   16316: 
                   16317: true DefaultValue prims         \ true: primitives are c-code
                   16318: 
                   16319: true DefaultValue floating      \ floating point wordset is present
                   16320: 
                   16321: true DefaultValue glocals       \ gforth locals are present
                   16322:                                 \ will be loaded
                   16323: true DefaultValue dcomps        \ double number comparisons
                   16324: 
                   16325: true DefaultValue hash          \ hashing primitives are loaded/present
                   16326: 
                   16327: true DefaultValue xconds        \ used together with glocals,
                   16328:                                 \ special conditionals supporting gforths'
                   16329:                                 \ local variables
                   16330: true DefaultValue header        \ save a header information
                   16331: 
                   16332: true DefaultValue backtrace     \ enables backtrace code
                   16333: 
                   16334: false DefaultValue ec
                   16335: false DefaultValue crlf
                   16336: 
                   16337: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
                   16338: 
                   16339: &16 KB          DefaultValue stack-size
                   16340: &15 KB &512 +   DefaultValue fstack-size
                   16341: &15 KB          DefaultValue rstack-size
                   16342: &14 KB &512 +   DefaultValue lstack-size
                   16343: @end example
1.13      pazsan   16344: 
1.48      anton    16345: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
1.14      pazsan   16346: @section How the Cross Compiler Works
1.13      pazsan   16347: 
                   16348: @node Bugs, Origin, Cross Compiler, Top
1.21      crook    16349: @appendix Bugs
1.1       anton    16350: @cindex bug reporting
                   16351: 
1.21      crook    16352: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1       anton    16353: 
1.103     anton    16354: If you find a bug, please submit a bug report through
                   16355: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21      crook    16356: 
                   16357: @itemize @bullet
                   16358: @item
1.81      anton    16359: A program (or a sequence of keyboard commands) that reproduces the bug.
                   16360: @item
                   16361: A description of what you think constitutes the buggy behaviour.
                   16362: @item
1.21      crook    16363: The Gforth version used (it is announced at the start of an
                   16364: interactive Gforth session).
                   16365: @item
                   16366: The machine and operating system (on Unix
                   16367: systems @code{uname -a} will report this information).
                   16368: @item
1.81      anton    16369: The installation options (you can find the configure options at the
                   16370: start of @file{config.status}) and configuration (@code{configure}
                   16371: output or @file{config.cache}).
1.21      crook    16372: @item
                   16373: A complete list of changes (if any) you (or your installer) have made to the
                   16374: Gforth sources.
                   16375: @end itemize
1.1       anton    16376: 
                   16377: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   16378: to Report Bugs, gcc.info, GNU C Manual}.
                   16379: 
                   16380: 
1.21      crook    16381: @node Origin, Forth-related information, Bugs, Top
                   16382: @appendix Authors and Ancestors of Gforth
1.1       anton    16383: 
                   16384: @section Authors and Contributors
                   16385: @cindex authors of Gforth
                   16386: @cindex contributors to Gforth
                   16387: 
                   16388: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81      anton    16389: Ertl. The third major author was Jens Wilke.  Neal Crook contributed a
                   16390: lot to the manual.  Assemblers and disassemblers were contributed by
1.161     anton    16391: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
                   16392: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
                   16393: and Stuart Ramsden inspired us with their continuous feedback. Lennart
                   16394: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
                   16395: working on automatic support for calling C libraries. Helpful comments
                   16396: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
                   16397: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
                   16398: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
                   16399: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
                   16400: comments from many others; thank you all, sorry for not listing you
                   16401: here (but digging through my mailbox to extract your names is on my
                   16402: to-do list).
1.1       anton    16403: 
                   16404: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   16405: and autoconf, among others), and to the creators of the Internet: Gforth
1.21      crook    16406: was developed across the Internet, and its authors did not meet
1.20      pazsan   16407: physically for the first 4 years of development.
1.1       anton    16408: 
                   16409: @section Pedigree
1.26      crook    16410: @cindex pedigree of Gforth
1.1       anton    16411: 
1.81      anton    16412: Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
                   16413: significant part of the design of Gforth was prescribed by ANS Forth.
1.1       anton    16414: 
1.20      pazsan   16415: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1       anton    16416: 32 bit native code version of VolksForth for the Atari ST, written
                   16417: mostly by Dietrich Weineck.
                   16418: 
1.81      anton    16419: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
                   16420: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147     anton    16421: the mid-80s and ported to the Atari ST in 1986.  It descends from fig-Forth.
1.1       anton    16422: 
1.147     anton    16423: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   16424: @c Forth-83 standard. !! Pedigree? When?
1.1       anton    16425: 
                   16426: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   16427: 1979. Robert Selzer and Bill Ragsdale developed the original
                   16428: implementation of fig-Forth for the 6502 based on microForth.
                   16429: 
                   16430: The principal architect of microForth was Dean Sanderson. microForth was
                   16431: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   16432: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   16433: Z80.
                   16434: 
                   16435: All earlier Forth systems were custom-made, usually by Charles Moore,
                   16436: who discovered (as he puts it) Forth during the late 60s. The first full
                   16437: Forth existed in 1971.
                   16438: 
1.81      anton    16439: A part of the information in this section comes from
                   16440: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
                   16441: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147     anton    16442: Charles H. Moore, presented at the HOPL-II conference and preprinted
                   16443: in SIGPLAN Notices 28(3), 1993.  You can find more historical and
                   16444: genealogical information about Forth there.  For a more general (and
                   16445: graphical) Forth family tree look see
                   16446: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
                   16447: Forth Family Tree and Timeline}.
1.1       anton    16448: 
1.81      anton    16449: @c ------------------------------------------------------------------
1.113     anton    16450: @node Forth-related information, Licenses, Origin, Top
1.21      crook    16451: @appendix Other Forth-related information
                   16452: @cindex Forth-related information
                   16453: 
1.81      anton    16454: @c anton: I threw most of this stuff out, because it can be found through
                   16455: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21      crook    16456: 
                   16457: @cindex comp.lang.forth
                   16458: @cindex frequently asked questions
1.81      anton    16459: There is an active news group (comp.lang.forth) discussing Forth
                   16460: (including Gforth) and Forth-related issues. Its
                   16461: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
                   16462: (frequently asked questions and their answers) contains a lot of
                   16463: information on Forth.  You should read it before posting to
                   16464: comp.lang.forth.
1.21      crook    16465: 
1.81      anton    16466: The ANS Forth standard is most usable in its
                   16467: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21      crook    16468: 
1.113     anton    16469: @c ---------------------------------------------------
                   16470: @node  Licenses, Word Index, Forth-related information, Top
                   16471: @appendix Licenses
                   16472: 
                   16473: @menu
                   16474: * GNU Free Documentation License::  License for copying this manual.
1.192     anton    16475: * Copying::                     GPL (for copying this software).
1.113     anton    16476: @end menu
                   16477: 
1.192     anton    16478: @node GNU Free Documentation License, Copying, Licenses, Licenses
                   16479: @appendixsec GNU Free Documentation License
1.113     anton    16480: @include fdl.texi
                   16481: 
1.192     anton    16482: @node Copying,  , GNU Free Documentation License, Licenses
                   16483: @appendixsec GNU GENERAL PUBLIC LICENSE
1.113     anton    16484: @include gpl.texi
                   16485: 
                   16486: 
                   16487: 
1.81      anton    16488: @c ------------------------------------------------------------------
1.113     anton    16489: @node Word Index, Concept Index, Licenses, Top
1.1       anton    16490: @unnumbered Word Index
                   16491: 
1.26      crook    16492: This index is a list of Forth words that have ``glossary'' entries
                   16493: within this manual. Each word is listed with its stack effect and
                   16494: wordset.
1.1       anton    16495: 
                   16496: @printindex fn
                   16497: 
1.81      anton    16498: @c anton: the name index seems superfluous given the word and concept indices.
                   16499: 
                   16500: @c @node Name Index, Concept Index, Word Index, Top
                   16501: @c @unnumbered Name Index
1.41      anton    16502: 
1.81      anton    16503: @c This index is a list of Forth words that have ``glossary'' entries
                   16504: @c within this manual.
1.41      anton    16505: 
1.81      anton    16506: @c @printindex ky
1.41      anton    16507: 
1.113     anton    16508: @c -------------------------------------------------------
1.81      anton    16509: @node Concept Index,  , Word Index, Top
1.1       anton    16510: @unnumbered Concept and Word Index
                   16511: 
1.26      crook    16512: Not all entries listed in this index are present verbatim in the
                   16513: text. This index also duplicates, in abbreviated form, all of the words
                   16514: listed in the Word Index (only the names are listed for the words here).
1.1       anton    16515: 
                   16516: @printindex cp
                   16517: 
                   16518: @bye
1.81      anton    16519: 
                   16520: 
1.1       anton    16521: 

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