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

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.169     anton      64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006 Free Software Foundation, Inc.
1.29      crook      65: 
1.113     anton      66: @quotation
                     67: Permission is granted to copy, distribute and/or modify this document
                     68: under the terms of the GNU Free Documentation License, Version 1.1 or
                     69: any later version published by the Free Software Foundation; with no
                     70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
                     71: and with the Back-Cover Texts as in (a) below.  A copy of the
                     72: license is included in the section entitled ``GNU Free Documentation
                     73: License.''
                     74: 
                     75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
                     76: this GNU Manual, like GNU software.  Copies published by the Free
                     77: Software Foundation raise funds for GNU development.''
                     78: @end quotation
                     79: @end copying
1.10      anton      80: 
1.113     anton      81: @dircategory Software development
                     82: @direntry
                     83: * Gforth: (gforth).             A fast interpreter for the Forth language.
                     84: @end direntry
                     85: @c The Texinfo manual also recommends doing this, but for Gforth it may
                     86: @c  not make much sense
                     87: @c @dircategory Individual utilities
                     88: @c @direntry
                     89: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
                     90: @c @end direntry
1.1       anton      91: 
                     92: @titlepage
1.113     anton      93: @title Gforth
                     94: @subtitle for version @value{VERSION}, @value{UPDATED}
                     95: @author Neal Crook
                     96: @author Anton Ertl
1.114     anton      97: @author David Kuehling
1.113     anton      98: @author Bernd Paysan
                     99: @author Jens Wilke
1.1       anton     100: @page
                    101: @vskip 0pt plus 1filll
1.113     anton     102: @insertcopying
                    103: @end titlepage
1.1       anton     104: 
1.113     anton     105: @contents
1.1       anton     106: 
1.113     anton     107: @ifnottex
                    108: @node Top, Goals, (dir), (dir)
                    109: @top Gforth
1.1       anton     110: 
1.113     anton     111: @insertcopying
1.49      anton     112: @end ifnottex
1.1       anton     113: 
                    114: @menu
1.26      crook     115: * Goals::                       About the Gforth Project
1.29      crook     116: * Gforth Environment::          Starting (and exiting) Gforth
1.48      anton     117: * Tutorial::                    Hands-on Forth Tutorial
1.21      crook     118: * Introduction::                An introduction to ANS Forth
1.1       anton     119: * Words::                       Forth words available in Gforth
1.24      anton     120: * Error messages::              How to interpret them
1.1       anton     121: * Tools::                       Programming tools
                    122: * ANS conformance::             Implementation-defined options etc.
1.65      anton     123: * Standard vs Extensions::      Should I use extensions?
1.1       anton     124: * Model::                       The abstract machine of Gforth
                    125: * Integrating Gforth::          Forth as scripting language for applications
                    126: * Emacs and Gforth::            The Gforth Mode
                    127: * Image Files::                 @code{.fi} files contain compiled code
                    128: * Engine::                      The inner interpreter and the primitives
1.13      pazsan    129: * Cross Compiler::              The Cross Compiler
1.1       anton     130: * Bugs::                        How to report them
                    131: * Origin::                      Authors and ancestors of Gforth
1.21      crook     132: * Forth-related information::   Books and places to look on the WWW
1.113     anton     133: * Licenses::                    
1.1       anton     134: * Word Index::                  An item for each Forth word
                    135: * Concept Index::               A menu covering many topics
1.12      anton     136: 
1.91      anton     137: @detailmenu
                    138:  --- The Detailed Node Listing ---
1.12      anton     139: 
1.29      crook     140: Gforth Environment
                    141: 
1.32      anton     142: * Invoking Gforth::             Getting in
                    143: * Leaving Gforth::              Getting out
                    144: * Command-line editing::        
1.48      anton     145: * Environment variables::       that affect how Gforth starts up
1.32      anton     146: * Gforth Files::                What gets installed and where
1.112     anton     147: * Gforth in pipes::             
1.48      anton     148: * Startup speed::               When 35ms is not fast enough ...
                    149: 
                    150: Forth Tutorial
                    151: 
                    152: * Starting Gforth Tutorial::    
                    153: * Syntax Tutorial::             
                    154: * Crash Course Tutorial::       
                    155: * Stack Tutorial::              
                    156: * Arithmetics Tutorial::        
                    157: * Stack Manipulation Tutorial::  
                    158: * Using files for Forth code Tutorial::  
                    159: * Comments Tutorial::           
                    160: * Colon Definitions Tutorial::  
                    161: * Decompilation Tutorial::      
                    162: * Stack-Effect Comments Tutorial::  
                    163: * Types Tutorial::              
                    164: * Factoring Tutorial::          
                    165: * Designing the stack effect Tutorial::  
                    166: * Local Variables Tutorial::    
                    167: * Conditional execution Tutorial::  
                    168: * Flags and Comparisons Tutorial::  
                    169: * General Loops Tutorial::      
                    170: * Counted loops Tutorial::      
                    171: * Recursion Tutorial::          
                    172: * Leaving definitions or loops Tutorial::  
                    173: * Return Stack Tutorial::       
                    174: * Memory Tutorial::             
                    175: * Characters and Strings Tutorial::  
                    176: * Alignment Tutorial::          
1.87      anton     177: * Files Tutorial::              
1.48      anton     178: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                    179: * Execution Tokens Tutorial::   
                    180: * Exceptions Tutorial::         
                    181: * Defining Words Tutorial::     
                    182: * Arrays and Records Tutorial::  
                    183: * POSTPONE Tutorial::           
                    184: * Literal Tutorial::            
                    185: * Advanced macros Tutorial::    
                    186: * Compilation Tokens Tutorial::  
                    187: * Wordlists and Search Order Tutorial::  
1.29      crook     188: 
1.24      anton     189: An Introduction to ANS Forth
                    190: 
1.67      anton     191: * Introducing the Text Interpreter::  
                    192: * Stacks and Postfix notation::  
                    193: * Your first definition::       
                    194: * How does that work?::         
                    195: * Forth is written in Forth::   
                    196: * Review - elements of a Forth system::  
                    197: * Where to go next::            
                    198: * Exercises::                   
1.24      anton     199: 
1.12      anton     200: Forth Words
                    201: 
                    202: * Notation::                    
1.65      anton     203: * Case insensitivity::          
                    204: * Comments::                    
                    205: * Boolean Flags::               
1.12      anton     206: * Arithmetic::                  
                    207: * Stack Manipulation::          
                    208: * Memory::                      
                    209: * Control Structures::          
                    210: * Defining Words::              
1.65      anton     211: * Interpretation and Compilation Semantics::  
1.47      crook     212: * Tokens for Words::            
1.81      anton     213: * Compiling words::             
1.65      anton     214: * The Text Interpreter::        
1.111     anton     215: * The Input Stream::            
1.65      anton     216: * Word Lists::                  
                    217: * Environmental Queries::       
1.12      anton     218: * Files::                       
                    219: * Blocks::                      
                    220: * Other I/O::                   
1.121     anton     221: * OS command line arguments::   
1.78      anton     222: * Locals::                      
                    223: * Structures::                  
                    224: * Object-oriented Forth::       
1.12      anton     225: * Programming Tools::           
1.150     anton     226: * C Interface::                 
1.12      anton     227: * Assembler and Code Words::    
                    228: * Threading Words::             
1.65      anton     229: * Passing Commands to the OS::  
                    230: * Keeping track of Time::       
                    231: * Miscellaneous Words::         
1.12      anton     232: 
                    233: Arithmetic
                    234: 
                    235: * Single precision::            
1.67      anton     236: * Double precision::            Double-cell integer arithmetic
1.12      anton     237: * Bitwise operations::          
1.67      anton     238: * Numeric comparison::          
1.32      anton     239: * Mixed precision::             Operations with single and double-cell integers
1.12      anton     240: * Floating Point::              
                    241: 
                    242: Stack Manipulation
                    243: 
                    244: * Data stack::                  
                    245: * Floating point stack::        
                    246: * Return stack::                
                    247: * Locals stack::                
                    248: * Stack pointer manipulation::  
                    249: 
                    250: Memory
                    251: 
1.32      anton     252: * Memory model::                
                    253: * Dictionary allocation::       
                    254: * Heap Allocation::             
                    255: * Memory Access::               
                    256: * Address arithmetic::          
                    257: * Memory Blocks::               
1.12      anton     258: 
                    259: Control Structures
                    260: 
1.41      anton     261: * Selection::                   IF ... ELSE ... ENDIF
                    262: * Simple Loops::                BEGIN ...
1.32      anton     263: * Counted Loops::               DO
1.67      anton     264: * Arbitrary control structures::  
                    265: * Calls and returns::           
1.12      anton     266: * Exception Handling::          
                    267: 
                    268: Defining Words
                    269: 
1.67      anton     270: * CREATE::                      
1.44      crook     271: * Variables::                   Variables and user variables
1.67      anton     272: * Constants::                   
1.44      crook     273: * Values::                      Initialised variables
1.67      anton     274: * Colon Definitions::           
1.44      crook     275: * Anonymous Definitions::       Definitions without names
1.71      anton     276: * Supplying names::             Passing definition names as strings
1.67      anton     277: * User-defined Defining Words::  
1.170     pazsan    278: * Deferred Words::              Allow forward references
1.67      anton     279: * Aliases::                     
1.47      crook     280: 
1.63      anton     281: User-defined Defining Words
                    282: 
                    283: * CREATE..DOES> applications::  
                    284: * CREATE..DOES> details::       
                    285: * Advanced does> usage example::  
1.155     anton     286: * Const-does>::                 
1.63      anton     287: 
1.47      crook     288: Interpretation and Compilation Semantics
                    289: 
1.67      anton     290: * Combined words::              
1.12      anton     291: 
1.71      anton     292: Tokens for Words
                    293: 
                    294: * Execution token::             represents execution/interpretation semantics
                    295: * Compilation token::           represents compilation semantics
                    296: * Name token::                  represents named words
                    297: 
1.82      anton     298: Compiling words
                    299: 
                    300: * Literals::                    Compiling data values
                    301: * Macros::                      Compiling words
                    302: 
1.21      crook     303: The Text Interpreter
                    304: 
1.67      anton     305: * Input Sources::               
                    306: * Number Conversion::           
                    307: * Interpret/Compile states::    
                    308: * Interpreter Directives::      
1.21      crook     309: 
1.26      crook     310: Word Lists
                    311: 
1.75      anton     312: * Vocabularies::                
1.67      anton     313: * Why use word lists?::         
1.75      anton     314: * Word list example::           
1.26      crook     315: 
                    316: Files
                    317: 
1.48      anton     318: * Forth source files::          
                    319: * General files::               
1.167     anton     320: * Redirection::                 
1.48      anton     321: * Search Paths::                
                    322: 
                    323: Search Paths
                    324: 
1.75      anton     325: * Source Search Paths::         
1.26      crook     326: * General Search Paths::        
                    327: 
                    328: Other I/O
                    329: 
1.32      anton     330: * Simple numeric output::       Predefined formats
                    331: * Formatted numeric output::    Formatted (pictured) output
                    332: * String Formats::              How Forth stores strings in memory
1.67      anton     333: * Displaying characters and strings::  Other stuff
1.178     anton     334: * Terminal output::             Cursor positioning etc.
1.181     anton     335: * Single-key input::            
                    336: * Line input and conversion::   
1.112     anton     337: * Pipes::                       How to create your own pipes
1.149     pazsan    338: * Xchars and Unicode::          Non-ASCII characters
1.26      crook     339: 
                    340: Locals
                    341: 
                    342: * Gforth locals::               
                    343: * ANS Forth locals::            
                    344: 
                    345: Gforth locals
                    346: 
                    347: * Where are locals visible by name?::  
                    348: * How long do locals live?::    
1.78      anton     349: * Locals programming style::    
                    350: * Locals implementation::       
1.26      crook     351: 
1.12      anton     352: Structures
                    353: 
                    354: * Why explicit structure support?::  
                    355: * Structure Usage::             
                    356: * Structure Naming Convention::  
                    357: * Structure Implementation::    
                    358: * Structure Glossary::          
                    359: 
                    360: Object-oriented Forth
                    361: 
1.48      anton     362: * Why object-oriented programming?::  
                    363: * Object-Oriented Terminology::  
                    364: * Objects::                     
                    365: * OOF::                         
                    366: * Mini-OOF::                    
1.23      crook     367: * Comparison with other object models::  
1.12      anton     368: 
1.24      anton     369: The @file{objects.fs} model
1.12      anton     370: 
                    371: * Properties of the Objects model::  
                    372: * Basic Objects Usage::         
1.41      anton     373: * The Objects base class::      
1.12      anton     374: * Creating objects::            
                    375: * Object-Oriented Programming Style::  
                    376: * Class Binding::               
                    377: * Method conveniences::         
                    378: * Classes and Scoping::         
1.41      anton     379: * Dividing classes::            
1.12      anton     380: * Object Interfaces::           
                    381: * Objects Implementation::      
                    382: * Objects Glossary::            
                    383: 
1.24      anton     384: The @file{oof.fs} model
1.12      anton     385: 
1.67      anton     386: * Properties of the OOF model::  
                    387: * Basic OOF Usage::             
                    388: * The OOF base class::          
                    389: * Class Declaration::           
                    390: * Class Implementation::        
1.12      anton     391: 
1.24      anton     392: The @file{mini-oof.fs} model
1.23      crook     393: 
1.48      anton     394: * Basic Mini-OOF Usage::        
                    395: * Mini-OOF Example::            
                    396: * Mini-OOF Implementation::     
1.23      crook     397: 
1.78      anton     398: Programming Tools
                    399: 
1.150     anton     400: * Examining::                   Data and Code.
                    401: * Forgetting words::            Usually before reloading.
1.78      anton     402: * Debugging::                   Simple and quick.
                    403: * Assertions::                  Making your programs self-checking.
                    404: * Singlestep Debugger::         Executing your program word by word.
                    405: 
1.155     anton     406: C Interface
                    407: 
                    408: * Calling C Functions::         
                    409: * Declaring C Functions::       
1.180     anton     410: * Calling C function pointers::  
1.155     anton     411: * Callbacks::                   
1.178     anton     412: * C interface internals::       
1.155     anton     413: * Low-Level C Interface Words::  
                    414: 
1.78      anton     415: Assembler and Code Words
                    416: 
                    417: * Code and ;code::              
                    418: * Common Assembler::            Assembler Syntax
                    419: * Common Disassembler::         
                    420: * 386 Assembler::               Deviations and special cases
                    421: * Alpha Assembler::             Deviations and special cases
                    422: * MIPS assembler::              Deviations and special cases
1.167     anton     423: * PowerPC assembler::           Deviations and special cases
1.78      anton     424: * Other assemblers::            How to write them
                    425: 
1.12      anton     426: Tools
                    427: 
                    428: * ANS Report::                  Report the words used, sorted by wordset.
1.127     anton     429: * Stack depth changes::         Where does this stack item come from?
1.12      anton     430: 
                    431: ANS conformance
                    432: 
                    433: * The Core Words::              
                    434: * The optional Block word set::  
                    435: * The optional Double Number word set::  
                    436: * The optional Exception word set::  
                    437: * The optional Facility word set::  
                    438: * The optional File-Access word set::  
                    439: * The optional Floating-Point word set::  
                    440: * The optional Locals word set::  
                    441: * The optional Memory-Allocation word set::  
                    442: * The optional Programming-Tools word set::  
                    443: * The optional Search-Order word set::  
                    444: 
                    445: The Core Words
                    446: 
                    447: * core-idef::                   Implementation Defined Options                   
                    448: * core-ambcond::                Ambiguous Conditions                
                    449: * core-other::                  Other System Documentation                  
                    450: 
                    451: The optional Block word set
                    452: 
                    453: * block-idef::                  Implementation Defined Options
                    454: * block-ambcond::               Ambiguous Conditions               
                    455: * block-other::                 Other System Documentation                 
                    456: 
                    457: The optional Double Number word set
                    458: 
                    459: * double-ambcond::              Ambiguous Conditions              
                    460: 
                    461: The optional Exception word set
                    462: 
                    463: * exception-idef::              Implementation Defined Options              
                    464: 
                    465: The optional Facility word set
                    466: 
                    467: * facility-idef::               Implementation Defined Options               
                    468: * facility-ambcond::            Ambiguous Conditions            
                    469: 
                    470: The optional File-Access word set
                    471: 
                    472: * file-idef::                   Implementation Defined Options
                    473: * file-ambcond::                Ambiguous Conditions                
                    474: 
                    475: The optional Floating-Point word set
                    476: 
                    477: * floating-idef::               Implementation Defined Options
                    478: * floating-ambcond::            Ambiguous Conditions            
                    479: 
                    480: The optional Locals word set
                    481: 
                    482: * locals-idef::                 Implementation Defined Options                 
                    483: * locals-ambcond::              Ambiguous Conditions              
                    484: 
                    485: The optional Memory-Allocation word set
                    486: 
                    487: * memory-idef::                 Implementation Defined Options                 
                    488: 
                    489: The optional Programming-Tools word set
                    490: 
                    491: * programming-idef::            Implementation Defined Options            
                    492: * programming-ambcond::         Ambiguous Conditions         
                    493: 
                    494: The optional Search-Order word set
                    495: 
                    496: * search-idef::                 Implementation Defined Options                 
                    497: * search-ambcond::              Ambiguous Conditions              
                    498: 
1.109     anton     499: Emacs and Gforth
                    500: 
                    501: * Installing gforth.el::        Making Emacs aware of Forth.
                    502: * Emacs Tags::                  Viewing the source of a word in Emacs.
                    503: * Hilighting::                  Making Forth code look prettier.
                    504: * Auto-Indentation::            Customizing auto-indentation.
                    505: * Blocks Files::                Reading and writing blocks files.
                    506: 
1.12      anton     507: Image Files
                    508: 
1.24      anton     509: * Image Licensing Issues::      Distribution terms for images.
                    510: * Image File Background::       Why have image files?
1.67      anton     511: * Non-Relocatable Image Files::  don't always work.
1.24      anton     512: * Data-Relocatable Image Files::  are better.
1.67      anton     513: * Fully Relocatable Image Files::  better yet.
1.24      anton     514: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.32      anton     515: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.24      anton     516: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     517: 
                    518: Fully Relocatable Image Files
                    519: 
1.27      crook     520: * gforthmi::                    The normal way
1.12      anton     521: * cross.fs::                    The hard way
                    522: 
                    523: Engine
                    524: 
                    525: * Portability::                 
                    526: * Threading::                   
                    527: * Primitives::                  
                    528: * Performance::                 
                    529: 
                    530: Threading
                    531: 
                    532: * Scheduling::                  
                    533: * Direct or Indirect Threaded?::  
1.109     anton     534: * Dynamic Superinstructions::   
1.12      anton     535: * DOES>::                       
                    536: 
                    537: Primitives
                    538: 
                    539: * Automatic Generation::        
                    540: * TOS Optimization::            
                    541: * Produced code::               
1.13      pazsan    542: 
                    543: Cross Compiler
                    544: 
1.67      anton     545: * Using the Cross Compiler::    
                    546: * How the Cross Compiler Works::  
1.13      pazsan    547: 
1.113     anton     548: Licenses
                    549: 
                    550: * GNU Free Documentation License::  License for copying this manual.
                    551: * Copying::                         GPL (for copying this software).
                    552: 
1.24      anton     553: @end detailmenu
1.1       anton     554: @end menu
                    555: 
1.113     anton     556: @c ----------------------------------------------------------
1.1       anton     557: @iftex
                    558: @unnumbered Preface
                    559: @cindex Preface
1.21      crook     560: This manual documents Gforth. Some introductory material is provided for
                    561: readers who are unfamiliar with Forth or who are migrating to Gforth
                    562: from other Forth compilers. However, this manual is primarily a
                    563: reference manual.
1.1       anton     564: @end iftex
                    565: 
1.28      crook     566: @comment TODO much more blurb here.
1.26      crook     567: 
                    568: @c ******************************************************************
1.113     anton     569: @node Goals, Gforth Environment, Top, Top
1.26      crook     570: @comment node-name,     next,           previous, up
                    571: @chapter Goals of Gforth
                    572: @cindex goals of the Gforth project
                    573: The goal of the Gforth Project is to develop a standard model for
                    574: ANS Forth. This can be split into several subgoals:
                    575: 
                    576: @itemize @bullet
                    577: @item
                    578: Gforth should conform to the ANS Forth Standard.
                    579: @item
                    580: It should be a model, i.e. it should define all the
                    581: implementation-dependent things.
                    582: @item
                    583: It should become standard, i.e. widely accepted and used. This goal
                    584: is the most difficult one.
                    585: @end itemize
                    586: 
                    587: To achieve these goals Gforth should be
                    588: @itemize @bullet
                    589: @item
                    590: Similar to previous models (fig-Forth, F83)
                    591: @item
                    592: Powerful. It should provide for all the things that are considered
                    593: necessary today and even some that are not yet considered necessary.
                    594: @item
                    595: Efficient. It should not get the reputation of being exceptionally
                    596: slow.
                    597: @item
                    598: Free.
                    599: @item
                    600: Available on many machines/easy to port.
                    601: @end itemize
                    602: 
                    603: Have we achieved these goals? Gforth conforms to the ANS Forth
                    604: standard. It may be considered a model, but we have not yet documented
                    605: which parts of the model are stable and which parts we are likely to
                    606: change. It certainly has not yet become a de facto standard, but it
                    607: appears to be quite popular. It has some similarities to and some
                    608: differences from previous models. It has some powerful features, but not
                    609: yet everything that we envisioned. We certainly have achieved our
1.65      anton     610: execution speed goals (@pxref{Performance})@footnote{However, in 1998
                    611: the bar was raised when the major commercial Forth vendors switched to
                    612: native code compilers.}.  It is free and available on many machines.
1.29      crook     613: 
1.26      crook     614: @c ******************************************************************
1.48      anton     615: @node Gforth Environment, Tutorial, Goals, Top
1.29      crook     616: @chapter Gforth Environment
                    617: @cindex Gforth environment
1.21      crook     618: 
1.45      crook     619: Note: ultimately, the Gforth man page will be auto-generated from the
1.29      crook     620: material in this chapter.
1.21      crook     621: 
                    622: @menu
1.29      crook     623: * Invoking Gforth::             Getting in
                    624: * Leaving Gforth::              Getting out
                    625: * Command-line editing::        
1.48      anton     626: * Environment variables::       that affect how Gforth starts up
1.29      crook     627: * Gforth Files::                What gets installed and where
1.112     anton     628: * Gforth in pipes::             
1.48      anton     629: * Startup speed::               When 35ms is not fast enough ...
1.21      crook     630: @end menu
                    631: 
1.49      anton     632: For related information about the creation of images see @ref{Image Files}.
1.29      crook     633: 
1.21      crook     634: @comment ----------------------------------------------
1.48      anton     635: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29      crook     636: @section Invoking Gforth
                    637: @cindex invoking Gforth
                    638: @cindex running Gforth
                    639: @cindex command-line options
                    640: @cindex options on the command line
                    641: @cindex flags on the command line
1.21      crook     642: 
1.30      anton     643: Gforth is made up of two parts; an executable ``engine'' (named
1.109     anton     644: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30      anton     645: will usually just say @code{gforth} -- this automatically loads the
                    646: default image file @file{gforth.fi}. In many other cases the default
                    647: Gforth image will be invoked like this:
1.21      crook     648: @example
1.30      anton     649: gforth [file | -e forth-code] ...
1.21      crook     650: @end example
1.29      crook     651: @noindent
                    652: This interprets the contents of the files and the Forth code in the order they
                    653: are given.
1.21      crook     654: 
1.109     anton     655: In addition to the @command{gforth} engine, there is also an engine
                    656: called @command{gforth-fast}, which is faster, but gives less
                    657: informative error messages (@pxref{Error messages}) and may catch some
1.166     anton     658: errors (in particular, stack underflows and integer division errors)
                    659: later or not at all.  You should use it for debugged,
1.109     anton     660: performance-critical programs.
                    661: 
                    662: Moreover, there is an engine called @command{gforth-itc}, which is
                    663: useful in some backwards-compatibility situations (@pxref{Direct or
                    664: Indirect Threaded?}).
1.30      anton     665: 
1.29      crook     666: In general, the command line looks like this:
1.21      crook     667: 
                    668: @example
1.30      anton     669: gforth[-fast] [engine options] [image options]
1.21      crook     670: @end example
                    671: 
1.30      anton     672: The engine options must come before the rest of the command
1.29      crook     673: line. They are:
1.26      crook     674: 
1.29      crook     675: @table @code
                    676: @cindex -i, command-line option
                    677: @cindex --image-file, command-line option
                    678: @item --image-file @i{file}
                    679: @itemx -i @i{file}
                    680: Loads the Forth image @i{file} instead of the default
                    681: @file{gforth.fi} (@pxref{Image Files}).
1.21      crook     682: 
1.39      anton     683: @cindex --appl-image, command-line option
                    684: @item --appl-image @i{file}
                    685: Loads the image @i{file} and leaves all further command-line arguments
1.65      anton     686: to the image (instead of processing them as engine options).  This is
                    687: useful for building executable application images on Unix, built with
1.39      anton     688: @code{gforthmi --application ...}.
                    689: 
1.29      crook     690: @cindex --path, command-line option
                    691: @cindex -p, command-line option
                    692: @item --path @i{path}
                    693: @itemx -p @i{path}
                    694: Uses @i{path} for searching the image file and Forth source code files
                    695: instead of the default in the environment variable @code{GFORTHPATH} or
                    696: the path specified at installation time (e.g.,
                    697: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                    698: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook     699: 
1.29      crook     700: @cindex --dictionary-size, command-line option
                    701: @cindex -m, command-line option
                    702: @cindex @i{size} parameters for command-line options
                    703: @cindex size of the dictionary and the stacks
                    704: @item --dictionary-size @i{size}
                    705: @itemx -m @i{size}
                    706: Allocate @i{size} space for the Forth dictionary space instead of
                    707: using the default specified in the image (typically 256K). The
                    708: @i{size} specification for this and subsequent options consists of
                    709: an integer and a unit (e.g.,
                    710: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
                    711: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                    712: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                    713: @code{e} is used.
1.21      crook     714: 
1.29      crook     715: @cindex --data-stack-size, command-line option
                    716: @cindex -d, command-line option
                    717: @item --data-stack-size @i{size}
                    718: @itemx -d @i{size}
                    719: Allocate @i{size} space for the data stack instead of using the
                    720: default specified in the image (typically 16K).
1.21      crook     721: 
1.29      crook     722: @cindex --return-stack-size, command-line option
                    723: @cindex -r, command-line option
                    724: @item --return-stack-size @i{size}
                    725: @itemx -r @i{size}
                    726: Allocate @i{size} space for the return stack instead of using the
                    727: default specified in the image (typically 15K).
1.21      crook     728: 
1.29      crook     729: @cindex --fp-stack-size, command-line option
                    730: @cindex -f, command-line option
                    731: @item --fp-stack-size @i{size}
                    732: @itemx -f @i{size}
                    733: Allocate @i{size} space for the floating point stack instead of
                    734: using the default specified in the image (typically 15.5K). In this case
                    735: the unit specifier @code{e} refers to floating point numbers.
1.21      crook     736: 
1.48      anton     737: @cindex --locals-stack-size, command-line option
                    738: @cindex -l, command-line option
                    739: @item --locals-stack-size @i{size}
                    740: @itemx -l @i{size}
                    741: Allocate @i{size} space for the locals stack instead of using the
                    742: default specified in the image (typically 14.5K).
                    743: 
1.176     anton     744: @cindex --vm-commit, command-line option
                    745: @cindex overcommit memory for dictionary and stacks
                    746: @cindex memory overcommit for dictionary and stacks
                    747: @item --vm-commit
                    748: Normally, Gforth tries to start up even if there is not enough virtual
                    749: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
                    750: on OSs that support it); so you can ask for a really big dictionary
                    751: and/or stacks, and as long as you don't use more virtual memory than
                    752: is available, everything will be fine (but if you use more, processes
                    753: get killed).  With this option you just use the default allocation
                    754: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
                    755: means that you cannot and should not ask for as big dictionary and
                    756: stacks, but once Gforth successfully starts up, out-of-memory won't
                    757: kill it.
                    758: 
1.48      anton     759: @cindex -h, command-line option
                    760: @cindex --help, command-line option
                    761: @item --help
                    762: @itemx -h
                    763: Print a message about the command-line options
                    764: 
                    765: @cindex -v, command-line option
                    766: @cindex --version, command-line option
                    767: @item --version
                    768: @itemx -v
                    769: Print version and exit
                    770: 
                    771: @cindex --debug, command-line option
                    772: @item --debug
                    773: Print some information useful for debugging on startup.
                    774: 
                    775: @cindex --offset-image, command-line option
                    776: @item --offset-image
                    777: Start the dictionary at a slightly different position than would be used
                    778: otherwise (useful for creating data-relocatable images,
                    779: @pxref{Data-Relocatable Image Files}).
                    780: 
                    781: @cindex --no-offset-im, command-line option
                    782: @item --no-offset-im
                    783: Start the dictionary at the normal position.
                    784: 
                    785: @cindex --clear-dictionary, command-line option
                    786: @item --clear-dictionary
                    787: Initialize all bytes in the dictionary to 0 before loading the image
                    788: (@pxref{Data-Relocatable Image Files}).
                    789: 
                    790: @cindex --die-on-signal, command-line-option
                    791: @item --die-on-signal
                    792: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                    793: or the segmentation violation SIGSEGV) by translating it into a Forth
                    794: @code{THROW}. With this option, Gforth exits if it receives such a
                    795: signal. This option is useful when the engine and/or the image might be
                    796: severely broken (such that it causes another signal before recovering
                    797: from the first); this option avoids endless loops in such cases.
1.109     anton     798: 
1.119     anton     799: @cindex --no-dynamic, command-line option
                    800: @cindex --dynamic, command-line option
1.109     anton     801: @item --no-dynamic
                    802: @item --dynamic
                    803: Disable or enable dynamic superinstructions with replication
                    804: (@pxref{Dynamic Superinstructions}).
                    805: 
1.119     anton     806: @cindex --no-super, command-line option
1.109     anton     807: @item --no-super
1.110     anton     808: Disable dynamic superinstructions, use just dynamic replication; this is
                    809: useful if you want to patch threaded code (@pxref{Dynamic
                    810: Superinstructions}).
1.119     anton     811: 
                    812: @cindex --ss-number, command-line option
                    813: @item --ss-number=@var{N}
                    814: Use only the first @var{N} static superinstructions compiled into the
                    815: engine (default: use them all; note that only @code{gforth-fast} has
                    816: any).  This option is useful for measuring the performance impact of
                    817: static superinstructions.
                    818: 
                    819: @cindex --ss-min-..., command-line options
                    820: @item --ss-min-codesize
                    821: @item --ss-min-ls
                    822: @item --ss-min-lsu
                    823: @item --ss-min-nexts
                    824: Use specified metric for determining the cost of a primitive or static
                    825: superinstruction for static superinstruction selection.  @code{Codesize}
                    826: is the native code size of the primive or static superinstruction,
                    827: @code{ls} is the number of loads and stores, @code{lsu} is the number of
                    828: loads, stores, and updates, and @code{nexts} is the number of dispatches
                    829: (not taking dynamic superinstructions into account), i.e. every
                    830: primitive or static superinstruction has cost 1. Default:
                    831: @code{codesize} if you use dynamic code generation, otherwise
                    832: @code{nexts}.
                    833: 
                    834: @cindex --ss-greedy, command-line option
                    835: @item --ss-greedy
                    836: This option is useful for measuring the performance impact of static
                    837: superinstructions.  By default, an optimal shortest-path algorithm is
                    838: used for selecting static superinstructions.  With @option{--ss-greedy}
                    839: this algorithm is modified to assume that anything after the static
                    840: superinstruction currently under consideration is not combined into
                    841: static superinstructions.  With @option{--ss-min-nexts} this produces
                    842: the same result as a greedy algorithm that always selects the longest
                    843: superinstruction available at the moment.  E.g., if there are
                    844: superinstructions AB and BCD, then for the sequence A B C D the optimal
                    845: algorithm will select A BCD and the greedy algorithm will select AB C D.
                    846: 
                    847: @cindex --print-metrics, command-line option
                    848: @item --print-metrics
                    849: Prints some metrics used during static superinstruction selection:
                    850: @code{code size} is the actual size of the dynamically generated code.
                    851: @code{Metric codesize} is the sum of the codesize metrics as seen by
                    852: static superinstruction selection; there is a difference from @code{code
                    853: size}, because not all primitives and static superinstructions are
                    854: compiled into dynamically generated code, and because of markers.  The
                    855: other metrics correspond to the @option{ss-min-...} options.  This
                    856: option is useful for evaluating the effects of the @option{--ss-...}
                    857: options.
1.109     anton     858: 
1.48      anton     859: @end table
                    860: 
                    861: @cindex loading files at startup
                    862: @cindex executing code on startup
                    863: @cindex batch processing with Gforth
                    864: As explained above, the image-specific command-line arguments for the
                    865: default image @file{gforth.fi} consist of a sequence of filenames and
                    866: @code{-e @var{forth-code}} options that are interpreted in the sequence
                    867: in which they are given. The @code{-e @var{forth-code}} or
1.121     anton     868: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
                    869: option takes only one argument; if you want to evaluate more Forth
                    870: words, you have to quote them or use @code{-e} several times. To exit
1.48      anton     871: after processing the command line (instead of entering interactive mode)
1.121     anton     872: append @code{-e bye} to the command line.  You can also process the
                    873: command-line arguments with a Forth program (@pxref{OS command line
                    874: arguments}).
1.48      anton     875: 
                    876: @cindex versions, invoking other versions of Gforth
                    877: If you have several versions of Gforth installed, @code{gforth} will
                    878: invoke the version that was installed last. @code{gforth-@i{version}}
                    879: invokes a specific version. If your environment contains the variable
                    880: @code{GFORTHPATH}, you may want to override it by using the
                    881: @code{--path} option.
                    882: 
                    883: Not yet implemented:
                    884: On startup the system first executes the system initialization file
                    885: (unless the option @code{--no-init-file} is given; note that the system
                    886: resulting from using this option may not be ANS Forth conformant). Then
                    887: the user initialization file @file{.gforth.fs} is executed, unless the
1.62      crook     888: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48      anton     889: then in @file{~}, then in the normal path (see above).
                    890: 
                    891: 
                    892: 
                    893: @comment ----------------------------------------------
                    894: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
                    895: @section Leaving Gforth
                    896: @cindex Gforth - leaving
                    897: @cindex leaving Gforth
                    898: 
                    899: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
                    900: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
                    901: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49      anton     902: data are discarded.  For ways of saving the state of the system before
                    903: leaving Gforth see @ref{Image Files}.
1.48      anton     904: 
                    905: doc-bye
                    906: 
                    907: 
                    908: @comment ----------------------------------------------
1.65      anton     909: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48      anton     910: @section Command-line editing
                    911: @cindex command-line editing
                    912: 
                    913: Gforth maintains a history file that records every line that you type to
                    914: the text interpreter. This file is preserved between sessions, and is
                    915: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
                    916: repeatedly you can recall successively older commands from this (or
                    917: previous) session(s). The full list of command-line editing facilities is:
                    918: 
                    919: @itemize @bullet
                    920: @item
                    921: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
                    922: commands from the history buffer.
                    923: @item
                    924: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
                    925: from the history buffer.
                    926: @item
                    927: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
                    928: @item
                    929: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
                    930: @item
                    931: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
                    932: closing up the line.
                    933: @item
                    934: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
                    935: @item
                    936: @kbd{Ctrl-a} to move the cursor to the start of the line.
                    937: @item
                    938: @kbd{Ctrl-e} to move the cursor to the end of the line.
                    939: @item
                    940: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
                    941: line.
                    942: @item
                    943: @key{TAB} to step through all possible full-word completions of the word
                    944: currently being typed.
                    945: @item
1.65      anton     946: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
                    947: using @code{bye}). 
                    948: @item
                    949: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
                    950: character under the cursor.
1.48      anton     951: @end itemize
                    952: 
                    953: When editing, displayable characters are inserted to the left of the
                    954: cursor position; the line is always in ``insert'' (as opposed to
                    955: ``overstrike'') mode.
                    956: 
                    957: @cindex history file
                    958: @cindex @file{.gforth-history}
                    959: On Unix systems, the history file is @file{~/.gforth-history} by
                    960: default@footnote{i.e. it is stored in the user's home directory.}. You
                    961: can find out the name and location of your history file using:
                    962: 
                    963: @example 
                    964: history-file type \ Unix-class systems
                    965: 
                    966: history-file type \ Other systems
                    967: history-dir  type
                    968: @end example
                    969: 
                    970: If you enter long definitions by hand, you can use a text editor to
                    971: paste them out of the history file into a Forth source file for reuse at
                    972: a later time.
                    973: 
                    974: Gforth never trims the size of the history file, so you should do this
                    975: periodically, if necessary.
                    976: 
                    977: @comment this is all defined in history.fs
                    978: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
                    979: @comment chosen?
                    980: 
                    981: 
                    982: @comment ----------------------------------------------
1.65      anton     983: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48      anton     984: @section Environment variables
                    985: @cindex environment variables
                    986: 
                    987: Gforth uses these environment variables:
                    988: 
                    989: @itemize @bullet
                    990: @item
                    991: @cindex @code{GFORTHHIST} -- environment variable
                    992: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
                    993: open/create the history file, @file{.gforth-history}. Default:
                    994: @code{$HOME}.
                    995: 
                    996: @item
                    997: @cindex @code{GFORTHPATH} -- environment variable
                    998: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
                    999: for Forth source-code files.
                   1000: 
                   1001: @item
1.147     anton    1002: @cindex @code{LANG} -- environment variable
                   1003: @code{LANG} -- see @code{LC_CTYPE}
                   1004: 
                   1005: @item
                   1006: @cindex @code{LC_ALL} -- environment variable
                   1007: @code{LC_ALL} -- see @code{LC_CTYPE}
                   1008: 
                   1009: @item
                   1010: @cindex @code{LC_CTYPE} -- environment variable
                   1011: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
                   1012: startup, Gforth uses the UTF-8 encoding for strings internally and
                   1013: expects its input and produces its output in UTF-8 encoding, otherwise
                   1014: the encoding is 8bit (see @pxref{Xchars and Unicode}).  If this
                   1015: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
                   1016: that is unset, in @code{LANG}.
                   1017: 
                   1018: @item
1.129     anton    1019: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
                   1020: 
                   1021: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
                   1022: of @code{system} before passing it to C's @code{system()}.  Default:
1.130     anton    1023: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs.  The prefix
1.129     anton    1024: and the command are directly concatenated, so if a space between them is
                   1025: necessary, append it to the prefix.
                   1026: 
                   1027: @item
1.48      anton    1028: @cindex @code{GFORTH} -- environment variable
1.49      anton    1029: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1030: 
                   1031: @item
                   1032: @cindex @code{GFORTHD} -- environment variable
1.62      crook    1033: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1034: 
                   1035: @item
                   1036: @cindex @code{TMP}, @code{TEMP} - environment variable
                   1037: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
                   1038: location for the history file.
                   1039: @end itemize
                   1040: 
                   1041: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
                   1042: @comment mentioning these.
                   1043: 
                   1044: All the Gforth environment variables default to sensible values if they
                   1045: are not set.
                   1046: 
                   1047: 
                   1048: @comment ----------------------------------------------
1.112     anton    1049: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48      anton    1050: @section Gforth files
                   1051: @cindex Gforth files
                   1052: 
                   1053: When you install Gforth on a Unix system, it installs files in these
                   1054: locations by default:
                   1055: 
                   1056: @itemize @bullet
                   1057: @item
                   1058: @file{/usr/local/bin/gforth}
                   1059: @item
                   1060: @file{/usr/local/bin/gforthmi}
                   1061: @item
                   1062: @file{/usr/local/man/man1/gforth.1} - man page.
                   1063: @item
                   1064: @file{/usr/local/info} - the Info version of this manual.
                   1065: @item
                   1066: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
                   1067: @item
                   1068: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
                   1069: @item
                   1070: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
                   1071: @item
                   1072: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
                   1073: @end itemize
                   1074: 
                   1075: You can select different places for installation by using
                   1076: @code{configure} options (listed with @code{configure --help}).
                   1077: 
                   1078: @comment ----------------------------------------------
1.112     anton    1079: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
                   1080: @section Gforth in pipes
                   1081: @cindex pipes, Gforth as part of
                   1082: 
                   1083: Gforth can be used in pipes created elsewhere (described here).  It can
                   1084: also create pipes on its own (@pxref{Pipes}).
                   1085: 
                   1086: @cindex input from pipes
                   1087: If you pipe into Gforth, your program should read with @code{read-file}
                   1088: or @code{read-line} from @code{stdin} (@pxref{General files}).
                   1089: @code{Key} does not recognize the end of input.  Words like
                   1090: @code{accept} echo the input and are therefore usually not useful for
                   1091: reading from a pipe.  You have to invoke the Forth program with an OS
                   1092: command-line option, as you have no chance to use the Forth command line
                   1093: (the text interpreter would try to interpret the pipe input).
                   1094: 
                   1095: @cindex output in pipes
                   1096: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
                   1097: 
                   1098: @cindex silent exiting from Gforth
                   1099: When you write to a pipe that has been closed at the other end, Gforth
                   1100: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
                   1101: into the exception @code{broken-pipe-error}.  If your application does
                   1102: not catch that exception, the system catches it and exits, usually
                   1103: silently (unless you were working on the Forth command line; then it
                   1104: prints an error message and exits).  This is usually the desired
                   1105: behaviour.
                   1106: 
                   1107: If you do not like this behaviour, you have to catch the exception
                   1108: yourself, and react to it.
                   1109: 
                   1110: Here's an example of an invocation of Gforth that is usable in a pipe:
                   1111: 
                   1112: @example
                   1113: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
                   1114:  type repeat ; foo bye"
                   1115: @end example
                   1116: 
                   1117: This example just copies the input verbatim to the output.  A very
                   1118: simple pipe containing this example looks like this:
                   1119: 
                   1120: @example
                   1121: cat startup.fs |
                   1122: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
                   1123:  type repeat ; foo bye"|
                   1124: head
                   1125: @end example
                   1126: 
                   1127: @cindex stderr and pipes
                   1128: Pipes involving Gforth's @code{stderr} output do not work.
                   1129: 
                   1130: @comment ----------------------------------------------
                   1131: @node Startup speed,  , Gforth in pipes, Gforth Environment
1.48      anton    1132: @section Startup speed
                   1133: @cindex Startup speed
                   1134: @cindex speed, startup
                   1135: 
                   1136: If Gforth is used for CGI scripts or in shell scripts, its startup
                   1137: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
                   1138: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
                   1139: system time.
                   1140: 
                   1141: If startup speed is a problem, you may consider the following ways to
                   1142: improve it; or you may consider ways to reduce the number of startups
1.62      crook    1143: (for example, by using Fast-CGI).
1.48      anton    1144: 
1.112     anton    1145: An easy step that influences Gforth startup speed is the use of the
                   1146: @option{--no-dynamic} option; this decreases image loading speed, but
                   1147: increases compile-time and run-time.
                   1148: 
                   1149: Another step to improve startup speed is to statically link Gforth, by
1.48      anton    1150: building it with @code{XLDFLAGS=-static}.  This requires more memory for
                   1151: the code and will therefore slow down the first invocation, but
                   1152: subsequent invocations avoid the dynamic linking overhead.  Another
                   1153: disadvantage is that Gforth won't profit from library upgrades.  As a
                   1154: result, @code{gforth-static -e bye} takes about 17.1ms user and
                   1155: 8.2ms system time.
                   1156: 
                   1157: The next step to improve startup speed is to use a non-relocatable image
1.65      anton    1158: (@pxref{Non-Relocatable Image Files}).  You can create this image with
1.48      anton    1159: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
                   1160: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
                   1161: and a part of the copy-on-write overhead.  The disadvantage is that the
1.62      crook    1162: non-relocatable image does not work if the OS gives Gforth a different
1.48      anton    1163: address for the dictionary, for whatever reason; so you better provide a
                   1164: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
                   1165: bye} takes about 15.3ms user and 7.5ms system time.
                   1166: 
                   1167: The final step is to disable dictionary hashing in Gforth.  Gforth
                   1168: builds the hash table on startup, which takes much of the startup
                   1169: overhead. You can do this by commenting out the @code{include hash.fs}
                   1170: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
                   1171: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
                   1172: The disadvantages are that functionality like @code{table} and
                   1173: @code{ekey} is missing and that text interpretation (e.g., compiling)
                   1174: now takes much longer. So, you should only use this method if there is
                   1175: no significant text interpretation to perform (the script should be
1.62      crook    1176: compiled into the image, amongst other things).  @code{gforth-static -i
1.48      anton    1177: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
                   1178: 
                   1179: @c ******************************************************************
                   1180: @node Tutorial, Introduction, Gforth Environment, Top
                   1181: @chapter Forth Tutorial
                   1182: @cindex Tutorial
                   1183: @cindex Forth Tutorial
                   1184: 
1.67      anton    1185: @c Topics from nac's Introduction that could be mentioned:
                   1186: @c press <ret> after each line
                   1187: @c Prompt
                   1188: @c numbers vs. words in dictionary on text interpretation
                   1189: @c what happens on redefinition
                   1190: @c parsing words (in particular, defining words)
                   1191: 
1.83      anton    1192: The difference of this chapter from the Introduction
                   1193: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
                   1194: be used while sitting in front of a computer, and covers much more
                   1195: material, but does not explain how the Forth system works.
                   1196: 
1.62      crook    1197: This tutorial can be used with any ANS-compliant Forth; any
                   1198: Gforth-specific features are marked as such and you can skip them if you
                   1199: work with another Forth.  This tutorial does not explain all features of
                   1200: Forth, just enough to get you started and give you some ideas about the
                   1201: facilities available in Forth.  Read the rest of the manual and the
                   1202: standard when you are through this.
1.48      anton    1203: 
                   1204: The intended way to use this tutorial is that you work through it while
                   1205: sitting in front of the console, take a look at the examples and predict
                   1206: what they will do, then try them out; if the outcome is not as expected,
                   1207: find out why (e.g., by trying out variations of the example), so you
                   1208: understand what's going on.  There are also some assignments that you
                   1209: should solve.
                   1210: 
                   1211: This tutorial assumes that you have programmed before and know what,
                   1212: e.g., a loop is.
                   1213: 
                   1214: @c !! explain compat library
                   1215: 
                   1216: @menu
                   1217: * Starting Gforth Tutorial::    
                   1218: * Syntax Tutorial::             
                   1219: * Crash Course Tutorial::       
                   1220: * Stack Tutorial::              
                   1221: * Arithmetics Tutorial::        
                   1222: * Stack Manipulation Tutorial::  
                   1223: * Using files for Forth code Tutorial::  
                   1224: * Comments Tutorial::           
                   1225: * Colon Definitions Tutorial::  
                   1226: * Decompilation Tutorial::      
                   1227: * Stack-Effect Comments Tutorial::  
                   1228: * Types Tutorial::              
                   1229: * Factoring Tutorial::          
                   1230: * Designing the stack effect Tutorial::  
                   1231: * Local Variables Tutorial::    
                   1232: * Conditional execution Tutorial::  
                   1233: * Flags and Comparisons Tutorial::  
                   1234: * General Loops Tutorial::      
                   1235: * Counted loops Tutorial::      
                   1236: * Recursion Tutorial::          
                   1237: * Leaving definitions or loops Tutorial::  
                   1238: * Return Stack Tutorial::       
                   1239: * Memory Tutorial::             
                   1240: * Characters and Strings Tutorial::  
                   1241: * Alignment Tutorial::          
1.87      anton    1242: * Files Tutorial::              
1.48      anton    1243: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                   1244: * Execution Tokens Tutorial::   
                   1245: * Exceptions Tutorial::         
                   1246: * Defining Words Tutorial::     
                   1247: * Arrays and Records Tutorial::  
                   1248: * POSTPONE Tutorial::           
                   1249: * Literal Tutorial::            
                   1250: * Advanced macros Tutorial::    
                   1251: * Compilation Tokens Tutorial::  
                   1252: * Wordlists and Search Order Tutorial::  
                   1253: @end menu
                   1254: 
                   1255: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
                   1256: @section Starting Gforth
1.66      anton    1257: @cindex starting Gforth tutorial
1.48      anton    1258: You can start Gforth by typing its name:
                   1259: 
                   1260: @example
                   1261: gforth
                   1262: @end example
                   1263: 
                   1264: That puts you into interactive mode; you can leave Gforth by typing
                   1265: @code{bye}.  While in Gforth, you can edit the command line and access
                   1266: the command line history with cursor keys, similar to bash.
                   1267: 
                   1268: 
                   1269: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
                   1270: @section Syntax
1.66      anton    1271: @cindex syntax tutorial
1.48      anton    1272: 
1.171     anton    1273: A @dfn{word} is a sequence of arbitrary characters (except white
1.48      anton    1274: space).  Words are separated by white space.  E.g., each of the
                   1275: following lines contains exactly one word:
                   1276: 
                   1277: @example
                   1278: word
                   1279: !@@#$%^&*()
                   1280: 1234567890
                   1281: 5!a
                   1282: @end example
                   1283: 
                   1284: A frequent beginner's error is to leave away necessary white space,
                   1285: resulting in an error like @samp{Undefined word}; so if you see such an
                   1286: error, check if you have put spaces wherever necessary.
                   1287: 
                   1288: @example
                   1289: ." hello, world" \ correct
                   1290: ."hello, world"  \ gives an "Undefined word" error
                   1291: @end example
                   1292: 
1.65      anton    1293: Gforth and most other Forth systems ignore differences in case (they are
1.48      anton    1294: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
                   1295: your system is case-sensitive, you may have to type all the examples
                   1296: given here in upper case.
                   1297: 
                   1298: 
                   1299: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
                   1300: @section Crash Course
                   1301: 
                   1302: Type
                   1303: 
                   1304: @example
                   1305: 0 0 !
                   1306: here execute
                   1307: ' catch >body 20 erase abort
                   1308: ' (quit) >body 20 erase
                   1309: @end example
                   1310: 
                   1311: The last two examples are guaranteed to destroy parts of Gforth (and
                   1312: most other systems), so you better leave Gforth afterwards (if it has
                   1313: not finished by itself).  On some systems you may have to kill gforth
                   1314: from outside (e.g., in Unix with @code{kill}).
                   1315: 
                   1316: Now that you know how to produce crashes (and that there's not much to
                   1317: them), let's learn how to produce meaningful programs.
                   1318: 
                   1319: 
                   1320: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
                   1321: @section Stack
1.66      anton    1322: @cindex stack tutorial
1.48      anton    1323: 
                   1324: The most obvious feature of Forth is the stack.  When you type in a
                   1325: number, it is pushed on the stack.  You can display the content of the
                   1326: stack with @code{.s}.
                   1327: 
                   1328: @example
                   1329: 1 2 .s
                   1330: 3 .s
                   1331: @end example
                   1332: 
                   1333: @code{.s} displays the top-of-stack to the right, i.e., the numbers
                   1334: appear in @code{.s} output as they appeared in the input.
                   1335: 
                   1336: You can print the top of stack element with @code{.}.
                   1337: 
                   1338: @example
                   1339: 1 2 3 . . .
                   1340: @end example
                   1341: 
                   1342: In general, words consume their stack arguments (@code{.s} is an
                   1343: exception).
                   1344: 
1.141     anton    1345: @quotation Assignment
1.48      anton    1346: What does the stack contain after @code{5 6 7 .}?
1.141     anton    1347: @end quotation
1.48      anton    1348: 
                   1349: 
                   1350: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
                   1351: @section Arithmetics
1.66      anton    1352: @cindex arithmetics tutorial
1.48      anton    1353: 
                   1354: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
                   1355: operate on the top two stack items:
                   1356: 
                   1357: @example
1.67      anton    1358: 2 2 .s
                   1359: + .s
                   1360: .
1.48      anton    1361: 2 1 - .
                   1362: 7 3 mod .
                   1363: @end example
                   1364: 
                   1365: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
                   1366: as in the corresponding infix expression (this is generally the case in
                   1367: Forth).
                   1368: 
                   1369: Parentheses are superfluous (and not available), because the order of
                   1370: the words unambiguously determines the order of evaluation and the
                   1371: operands:
                   1372: 
                   1373: @example
                   1374: 3 4 + 5 * .
                   1375: 3 4 5 * + .
                   1376: @end example
                   1377: 
1.141     anton    1378: @quotation Assignment
1.48      anton    1379: What are the infix expressions corresponding to the Forth code above?
                   1380: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
                   1381: known as Postfix or RPN (Reverse Polish Notation).}.
1.141     anton    1382: @end quotation
1.48      anton    1383: 
                   1384: To change the sign, use @code{negate}:
                   1385: 
                   1386: @example
                   1387: 2 negate .
                   1388: @end example
                   1389: 
1.141     anton    1390: @quotation Assignment
1.48      anton    1391: Convert -(-3)*4-5 to Forth.
1.141     anton    1392: @end quotation
1.48      anton    1393: 
                   1394: @code{/mod} performs both @code{/} and @code{mod}.
                   1395: 
                   1396: @example
                   1397: 7 3 /mod . .
                   1398: @end example
                   1399: 
1.66      anton    1400: Reference: @ref{Arithmetic}.
                   1401: 
                   1402: 
1.48      anton    1403: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
                   1404: @section Stack Manipulation
1.66      anton    1405: @cindex stack manipulation tutorial
1.48      anton    1406: 
                   1407: Stack manipulation words rearrange the data on the stack.
                   1408: 
                   1409: @example
                   1410: 1 .s drop .s
                   1411: 1 .s dup .s drop drop .s
                   1412: 1 2 .s over .s drop drop drop
                   1413: 1 2 .s swap .s drop drop
                   1414: 1 2 3 .s rot .s drop drop drop
                   1415: @end example
                   1416: 
                   1417: These are the most important stack manipulation words.  There are also
                   1418: variants that manipulate twice as many stack items:
                   1419: 
                   1420: @example
                   1421: 1 2 3 4 .s 2swap .s 2drop 2drop
                   1422: @end example
                   1423: 
                   1424: Two more stack manipulation words are:
                   1425: 
                   1426: @example
                   1427: 1 2 .s nip .s drop
                   1428: 1 2 .s tuck .s 2drop drop
                   1429: @end example
                   1430: 
1.141     anton    1431: @quotation Assignment
1.48      anton    1432: Replace @code{nip} and @code{tuck} with combinations of other stack
                   1433: manipulation words.
                   1434: 
                   1435: @example
                   1436: Given:          How do you get:
                   1437: 1 2 3           3 2 1           
                   1438: 1 2 3           1 2 3 2                 
                   1439: 1 2 3           1 2 3 3                 
                   1440: 1 2 3           1 3 3           
                   1441: 1 2 3           2 1 3           
                   1442: 1 2 3 4         4 3 2 1         
                   1443: 1 2 3           1 2 3 1 2 3             
                   1444: 1 2 3 4         1 2 3 4 1 2             
                   1445: 1 2 3
                   1446: 1 2 3           1 2 3 4                 
                   1447: 1 2 3           1 3             
                   1448: @end example
1.141     anton    1449: @end quotation
1.48      anton    1450: 
                   1451: @example
                   1452: 5 dup * .
                   1453: @end example
                   1454: 
1.141     anton    1455: @quotation Assignment
1.48      anton    1456: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
                   1457: Write a piece of Forth code that expects two numbers on the stack
                   1458: (@var{a} and @var{b}, with @var{b} on top) and computes
                   1459: @code{(a-b)(a+1)}.
1.141     anton    1460: @end quotation
1.48      anton    1461: 
1.66      anton    1462: Reference: @ref{Stack Manipulation}.
                   1463: 
                   1464: 
1.48      anton    1465: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
                   1466: @section Using files for Forth code
1.66      anton    1467: @cindex loading Forth code, tutorial
                   1468: @cindex files containing Forth code, tutorial
1.48      anton    1469: 
                   1470: While working at the Forth command line is convenient for one-line
                   1471: examples and short one-off code, you probably want to store your source
                   1472: code in files for convenient editing and persistence.  You can use your
                   1473: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102     anton    1474: Gforth}) to create @var{file.fs} and use
1.48      anton    1475: 
                   1476: @example
1.102     anton    1477: s" @var{file.fs}" included
1.48      anton    1478: @end example
                   1479: 
                   1480: to load it into your Forth system.  The file name extension I use for
                   1481: Forth files is @samp{.fs}.
                   1482: 
                   1483: You can easily start Gforth with some files loaded like this:
                   1484: 
                   1485: @example
1.102     anton    1486: gforth @var{file1.fs} @var{file2.fs}
1.48      anton    1487: @end example
                   1488: 
                   1489: If an error occurs during loading these files, Gforth terminates,
                   1490: whereas an error during @code{INCLUDED} within Gforth usually gives you
                   1491: a Gforth command line.  Starting the Forth system every time gives you a
                   1492: clean start every time, without interference from the results of earlier
                   1493: tries.
                   1494: 
                   1495: I often put all the tests in a file, then load the code and run the
                   1496: tests with
                   1497: 
                   1498: @example
1.102     anton    1499: gforth @var{code.fs} @var{tests.fs} -e bye
1.48      anton    1500: @end example
                   1501: 
                   1502: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
                   1503: @code{-e bye} ensures that Gforth terminates afterwards so that I can
                   1504: restart this command without ado.
                   1505: 
                   1506: The advantage of this approach is that the tests can be repeated easily
                   1507: every time the program ist changed, making it easy to catch bugs
                   1508: introduced by the change.
                   1509: 
1.66      anton    1510: Reference: @ref{Forth source files}.
                   1511: 
1.48      anton    1512: 
                   1513: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
                   1514: @section Comments
1.66      anton    1515: @cindex comments tutorial
1.48      anton    1516: 
                   1517: @example
                   1518: \ That's a comment; it ends at the end of the line
                   1519: ( Another comment; it ends here: )  .s
                   1520: @end example
                   1521: 
                   1522: @code{\} and @code{(} are ordinary Forth words and therefore have to be
                   1523: separated with white space from the following text.
                   1524: 
                   1525: @example
                   1526: \This gives an "Undefined word" error
                   1527: @end example
                   1528: 
                   1529: The first @code{)} ends a comment started with @code{(}, so you cannot
                   1530: nest @code{(}-comments; and you cannot comment out text containing a
                   1531: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
                   1532: avoid @code{)} in word names.}.
                   1533: 
                   1534: I use @code{\}-comments for descriptive text and for commenting out code
                   1535: of one or more line; I use @code{(}-comments for describing the stack
                   1536: effect, the stack contents, or for commenting out sub-line pieces of
                   1537: code.
                   1538: 
                   1539: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
                   1540: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
                   1541: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
                   1542: with @kbd{M-q}.
                   1543: 
1.66      anton    1544: Reference: @ref{Comments}.
                   1545: 
1.48      anton    1546: 
                   1547: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
                   1548: @section Colon Definitions
1.66      anton    1549: @cindex colon definitions, tutorial
                   1550: @cindex definitions, tutorial
                   1551: @cindex procedures, tutorial
                   1552: @cindex functions, tutorial
1.48      anton    1553: 
                   1554: are similar to procedures and functions in other programming languages.
                   1555: 
                   1556: @example
                   1557: : squared ( n -- n^2 )
                   1558:    dup * ;
                   1559: 5 squared .
                   1560: 7 squared .
                   1561: @end example
                   1562: 
                   1563: @code{:} starts the colon definition; its name is @code{squared}.  The
                   1564: following comment describes its stack effect.  The words @code{dup *}
                   1565: are not executed, but compiled into the definition.  @code{;} ends the
                   1566: colon definition.
                   1567: 
                   1568: The newly-defined word can be used like any other word, including using
                   1569: it in other definitions:
                   1570: 
                   1571: @example
                   1572: : cubed ( n -- n^3 )
                   1573:    dup squared * ;
                   1574: -5 cubed .
                   1575: : fourth-power ( n -- n^4 )
                   1576:    squared squared ;
                   1577: 3 fourth-power .
                   1578: @end example
                   1579: 
1.141     anton    1580: @quotation Assignment
1.48      anton    1581: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
                   1582: @code{/mod} in terms of other Forth words, and check if they work (hint:
                   1583: test your tests on the originals first).  Don't let the
                   1584: @samp{redefined}-Messages spook you, they are just warnings.
1.141     anton    1585: @end quotation
1.48      anton    1586: 
1.66      anton    1587: Reference: @ref{Colon Definitions}.
                   1588: 
1.48      anton    1589: 
                   1590: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
                   1591: @section Decompilation
1.66      anton    1592: @cindex decompilation tutorial
                   1593: @cindex see tutorial
1.48      anton    1594: 
                   1595: You can decompile colon definitions with @code{see}:
                   1596: 
                   1597: @example
                   1598: see squared
                   1599: see cubed
                   1600: @end example
                   1601: 
                   1602: In Gforth @code{see} shows you a reconstruction of the source code from
                   1603: the executable code.  Informations that were present in the source, but
                   1604: not in the executable code, are lost (e.g., comments).
                   1605: 
1.65      anton    1606: You can also decompile the predefined words:
                   1607: 
                   1608: @example
                   1609: see .
                   1610: see +
                   1611: @end example
                   1612: 
                   1613: 
1.48      anton    1614: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
                   1615: @section Stack-Effect Comments
1.66      anton    1616: @cindex stack-effect comments, tutorial
                   1617: @cindex --, tutorial
1.48      anton    1618: By convention the comment after the name of a definition describes the
1.171     anton    1619: stack effect: The part in front of the @samp{--} describes the state of
1.48      anton    1620: the stack before the execution of the definition, i.e., the parameters
                   1621: that are passed into the colon definition; the part behind the @samp{--}
                   1622: is the state of the stack after the execution of the definition, i.e.,
                   1623: the results of the definition.  The stack comment only shows the top
                   1624: stack items that the definition accesses and/or changes.
                   1625: 
                   1626: You should put a correct stack effect on every definition, even if it is
                   1627: just @code{( -- )}.  You should also add some descriptive comment to
                   1628: more complicated words (I usually do this in the lines following
                   1629: @code{:}).  If you don't do this, your code becomes unreadable (because
1.117     anton    1630: you have to work through every definition before you can understand
1.48      anton    1631: any).
                   1632: 
1.141     anton    1633: @quotation Assignment
1.48      anton    1634: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
                   1635: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
                   1636: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
1.65      anton    1637: are done, you can compare your stack effects to those in this manual
1.48      anton    1638: (@pxref{Word Index}).
1.141     anton    1639: @end quotation
1.48      anton    1640: 
                   1641: Sometimes programmers put comments at various places in colon
                   1642: definitions that describe the contents of the stack at that place (stack
                   1643: comments); i.e., they are like the first part of a stack-effect
                   1644: comment. E.g.,
                   1645: 
                   1646: @example
                   1647: : cubed ( n -- n^3 )
                   1648:    dup squared  ( n n^2 ) * ;
                   1649: @end example
                   1650: 
                   1651: In this case the stack comment is pretty superfluous, because the word
                   1652: is simple enough.  If you think it would be a good idea to add such a
                   1653: comment to increase readability, you should also consider factoring the
                   1654: word into several simpler words (@pxref{Factoring Tutorial,,
1.60      anton    1655: Factoring}), which typically eliminates the need for the stack comment;
1.48      anton    1656: however, if you decide not to refactor it, then having such a comment is
                   1657: better than not having it.
                   1658: 
                   1659: The names of the stack items in stack-effect and stack comments in the
                   1660: standard, in this manual, and in many programs specify the type through
                   1661: a type prefix, similar to Fortran and Hungarian notation.  The most
                   1662: frequent prefixes are:
                   1663: 
                   1664: @table @code
                   1665: @item n
                   1666: signed integer
                   1667: @item u
                   1668: unsigned integer
                   1669: @item c
                   1670: character
                   1671: @item f
                   1672: Boolean flags, i.e. @code{false} or @code{true}.
                   1673: @item a-addr,a-
                   1674: Cell-aligned address
                   1675: @item c-addr,c-
                   1676: Char-aligned address (note that a Char may have two bytes in Windows NT)
                   1677: @item xt
                   1678: Execution token, same size as Cell
                   1679: @item w,x
                   1680: Cell, can contain an integer or an address.  It usually takes 32, 64 or
                   1681: 16 bits (depending on your platform and Forth system). A cell is more
                   1682: commonly known as machine word, but the term @emph{word} already means
                   1683: something different in Forth.
                   1684: @item d
                   1685: signed double-cell integer
                   1686: @item ud
                   1687: unsigned double-cell integer
                   1688: @item r
                   1689: Float (on the FP stack)
                   1690: @end table
                   1691: 
                   1692: You can find a more complete list in @ref{Notation}.
                   1693: 
1.141     anton    1694: @quotation Assignment
1.48      anton    1695: Write stack-effect comments for all definitions you have written up to
                   1696: now.
1.141     anton    1697: @end quotation
1.48      anton    1698: 
                   1699: 
                   1700: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
                   1701: @section Types
1.66      anton    1702: @cindex types tutorial
1.48      anton    1703: 
                   1704: In Forth the names of the operations are not overloaded; so similar
                   1705: operations on different types need different names; e.g., @code{+} adds
                   1706: integers, and you have to use @code{f+} to add floating-point numbers.
                   1707: The following prefixes are often used for related operations on
                   1708: different types:
                   1709: 
                   1710: @table @code
                   1711: @item (none)
                   1712: signed integer
                   1713: @item u
                   1714: unsigned integer
                   1715: @item c
                   1716: character
                   1717: @item d
                   1718: signed double-cell integer
                   1719: @item ud, du
                   1720: unsigned double-cell integer
                   1721: @item 2
                   1722: two cells (not-necessarily double-cell numbers)
                   1723: @item m, um
                   1724: mixed single-cell and double-cell operations
                   1725: @item f
                   1726: floating-point (note that in stack comments @samp{f} represents flags,
1.66      anton    1727: and @samp{r} represents FP numbers).
1.48      anton    1728: @end table
                   1729: 
                   1730: If there are no differences between the signed and the unsigned variant
                   1731: (e.g., for @code{+}), there is only the prefix-less variant.
                   1732: 
                   1733: Forth does not perform type checking, neither at compile time, nor at
                   1734: run time.  If you use the wrong oeration, the data are interpreted
                   1735: incorrectly:
                   1736: 
                   1737: @example
                   1738: -1 u.
                   1739: @end example
                   1740: 
                   1741: If you have only experience with type-checked languages until now, and
                   1742: have heard how important type-checking is, don't panic!  In my
                   1743: experience (and that of other Forthers), type errors in Forth code are
                   1744: usually easy to find (once you get used to it), the increased vigilance
                   1745: of the programmer tends to catch some harder errors in addition to most
                   1746: type errors, and you never have to work around the type system, so in
                   1747: most situations the lack of type-checking seems to be a win (projects to
                   1748: add type checking to Forth have not caught on).
                   1749: 
                   1750: 
                   1751: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
                   1752: @section Factoring
1.66      anton    1753: @cindex factoring tutorial
1.48      anton    1754: 
                   1755: If you try to write longer definitions, you will soon find it hard to
                   1756: keep track of the stack contents.  Therefore, good Forth programmers
                   1757: tend to write only short definitions (e.g., three lines).  The art of
                   1758: finding meaningful short definitions is known as factoring (as in
                   1759: factoring polynomials).
                   1760: 
                   1761: Well-factored programs offer additional advantages: smaller, more
                   1762: general words, are easier to test and debug and can be reused more and
                   1763: better than larger, specialized words.
                   1764: 
                   1765: So, if you run into difficulties with stack management, when writing
                   1766: code, try to define meaningful factors for the word, and define the word
                   1767: in terms of those.  Even if a factor contains only two words, it is
                   1768: often helpful.
                   1769: 
1.65      anton    1770: Good factoring is not easy, and it takes some practice to get the knack
                   1771: for it; but even experienced Forth programmers often don't find the
                   1772: right solution right away, but only when rewriting the program.  So, if
                   1773: you don't come up with a good solution immediately, keep trying, don't
                   1774: despair.
1.48      anton    1775: 
                   1776: @c example !!
                   1777: 
                   1778: 
                   1779: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
                   1780: @section Designing the stack effect
1.66      anton    1781: @cindex Stack effect design, tutorial
                   1782: @cindex design of stack effects, tutorial
1.48      anton    1783: 
                   1784: In other languages you can use an arbitrary order of parameters for a
1.65      anton    1785: function; and since there is only one result, you don't have to deal with
1.48      anton    1786: the order of results, either.
                   1787: 
1.117     anton    1788: In Forth (and other stack-based languages, e.g., PostScript) the
1.48      anton    1789: parameter and result order of a definition is important and should be
                   1790: designed well.  The general guideline is to design the stack effect such
                   1791: that the word is simple to use in most cases, even if that complicates
                   1792: the implementation of the word.  Some concrete rules are:
                   1793: 
                   1794: @itemize @bullet
                   1795: 
                   1796: @item
                   1797: Words consume all of their parameters (e.g., @code{.}).
                   1798: 
                   1799: @item
                   1800: If there is a convention on the order of parameters (e.g., from
                   1801: mathematics or another programming language), stick with it (e.g.,
                   1802: @code{-}).
                   1803: 
                   1804: @item
                   1805: If one parameter usually requires only a short computation (e.g., it is
                   1806: a constant), pass it on the top of the stack.  Conversely, parameters
                   1807: that usually require a long sequence of code to compute should be passed
                   1808: as the bottom (i.e., first) parameter.  This makes the code easier to
1.171     anton    1809: read, because the reader does not need to keep track of the bottom item
1.48      anton    1810: through a long sequence of code (or, alternatively, through stack
1.49      anton    1811: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48      anton    1812: address on top of the stack because it is usually simpler to compute
                   1813: than the stored value (often the address is just a variable).
                   1814: 
                   1815: @item
                   1816: Similarly, results that are usually consumed quickly should be returned
                   1817: on the top of stack, whereas a result that is often used in long
                   1818: computations should be passed as bottom result.  E.g., the file words
                   1819: like @code{open-file} return the error code on the top of stack, because
                   1820: it is usually consumed quickly by @code{throw}; moreover, the error code
                   1821: has to be checked before doing anything with the other results.
                   1822: 
                   1823: @end itemize
                   1824: 
                   1825: These rules are just general guidelines, don't lose sight of the overall
                   1826: goal to make the words easy to use.  E.g., if the convention rule
                   1827: conflicts with the computation-length rule, you might decide in favour
                   1828: of the convention if the word will be used rarely, and in favour of the
                   1829: computation-length rule if the word will be used frequently (because
                   1830: with frequent use the cost of breaking the computation-length rule would
                   1831: be quite high, and frequent use makes it easier to remember an
                   1832: unconventional order).
                   1833: 
                   1834: @c example !! structure package
                   1835: 
1.65      anton    1836: 
1.48      anton    1837: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
                   1838: @section Local Variables
1.66      anton    1839: @cindex local variables, tutorial
1.48      anton    1840: 
                   1841: You can define local variables (@emph{locals}) in a colon definition:
                   1842: 
                   1843: @example
                   1844: : swap @{ a b -- b a @}
                   1845:   b a ;
                   1846: 1 2 swap .s 2drop
                   1847: @end example
                   1848: 
                   1849: (If your Forth system does not support this syntax, include
                   1850: @file{compat/anslocals.fs} first).
                   1851: 
                   1852: In this example @code{@{ a b -- b a @}} is the locals definition; it
                   1853: takes two cells from the stack, puts the top of stack in @code{b} and
                   1854: the next stack element in @code{a}.  @code{--} starts a comment ending
                   1855: with @code{@}}.  After the locals definition, using the name of the
                   1856: local will push its value on the stack.  You can leave the comment
                   1857: part (@code{-- b a}) away:
                   1858: 
                   1859: @example
                   1860: : swap ( x1 x2 -- x2 x1 )
                   1861:   @{ a b @} b a ;
                   1862: @end example
                   1863: 
                   1864: In Gforth you can have several locals definitions, anywhere in a colon
                   1865: definition; in contrast, in a standard program you can have only one
                   1866: locals definition per colon definition, and that locals definition must
1.163     anton    1867: be outside any control structure.
1.48      anton    1868: 
                   1869: With locals you can write slightly longer definitions without running
                   1870: into stack trouble.  However, I recommend trying to write colon
                   1871: definitions without locals for exercise purposes to help you gain the
                   1872: essential factoring skills.
                   1873: 
1.141     anton    1874: @quotation Assignment
1.48      anton    1875: Rewrite your definitions until now with locals
1.141     anton    1876: @end quotation
1.48      anton    1877: 
1.66      anton    1878: Reference: @ref{Locals}.
                   1879: 
1.48      anton    1880: 
                   1881: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
                   1882: @section Conditional execution
1.66      anton    1883: @cindex conditionals, tutorial
                   1884: @cindex if, tutorial
1.48      anton    1885: 
                   1886: In Forth you can use control structures only inside colon definitions.
                   1887: An @code{if}-structure looks like this:
                   1888: 
                   1889: @example
                   1890: : abs ( n1 -- +n2 )
                   1891:     dup 0 < if
                   1892:         negate
                   1893:     endif ;
                   1894: 5 abs .
                   1895: -5 abs .
                   1896: @end example
                   1897: 
                   1898: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
                   1899: the following code is performed, otherwise execution continues after the
1.51      pazsan   1900: @code{endif} (or @code{else}).  @code{<} compares the top two stack
1.171     anton    1901: elements and produces a flag:
1.48      anton    1902: 
                   1903: @example
                   1904: 1 2 < .
                   1905: 2 1 < .
                   1906: 1 1 < .
                   1907: @end example
                   1908: 
                   1909: Actually the standard name for @code{endif} is @code{then}.  This
                   1910: tutorial presents the examples using @code{endif}, because this is often
                   1911: less confusing for people familiar with other programming languages
                   1912: where @code{then} has a different meaning.  If your system does not have
                   1913: @code{endif}, define it with
                   1914: 
                   1915: @example
                   1916: : endif postpone then ; immediate
                   1917: @end example
                   1918: 
                   1919: You can optionally use an @code{else}-part:
                   1920: 
                   1921: @example
                   1922: : min ( n1 n2 -- n )
                   1923:   2dup < if
                   1924:     drop
                   1925:   else
                   1926:     nip
                   1927:   endif ;
                   1928: 2 3 min .
                   1929: 3 2 min .
                   1930: @end example
                   1931: 
1.141     anton    1932: @quotation Assignment
1.48      anton    1933: Write @code{min} without @code{else}-part (hint: what's the definition
                   1934: of @code{nip}?).
1.141     anton    1935: @end quotation
1.48      anton    1936: 
1.66      anton    1937: Reference: @ref{Selection}.
                   1938: 
1.48      anton    1939: 
                   1940: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
                   1941: @section Flags and Comparisons
1.66      anton    1942: @cindex flags tutorial
                   1943: @cindex comparison tutorial
1.48      anton    1944: 
                   1945: In a false-flag all bits are clear (0 when interpreted as integer).  In
                   1946: a canonical true-flag all bits are set (-1 as a twos-complement signed
                   1947: integer); in many contexts (e.g., @code{if}) any non-zero value is
                   1948: treated as true flag.
                   1949: 
                   1950: @example
                   1951: false .
                   1952: true .
                   1953: true hex u. decimal
                   1954: @end example
                   1955: 
                   1956: Comparison words produce canonical flags:
                   1957: 
                   1958: @example
                   1959: 1 1 = .
                   1960: 1 0= .
                   1961: 0 1 < .
                   1962: 0 0 < .
                   1963: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
                   1964: -1 1 < .
                   1965: @end example
                   1966: 
1.66      anton    1967: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
                   1968: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
                   1969: these combinations are standard (for details see the standard,
                   1970: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48      anton    1971: 
1.171     anton    1972: You can use @code{and or xor invert} as operations on canonical flags.
                   1973: Actually they are bitwise operations:
1.48      anton    1974: 
                   1975: @example
                   1976: 1 2 and .
                   1977: 1 2 or .
                   1978: 1 3 xor .
                   1979: 1 invert .
                   1980: @end example
                   1981: 
                   1982: You can convert a zero/non-zero flag into a canonical flag with
                   1983: @code{0<>} (and complement it on the way with @code{0=}).
                   1984: 
                   1985: @example
                   1986: 1 0= .
                   1987: 1 0<> .
                   1988: @end example
                   1989: 
1.65      anton    1990: You can use the all-bits-set feature of canonical flags and the bitwise
1.48      anton    1991: operation of the Boolean operations to avoid @code{if}s:
                   1992: 
                   1993: @example
                   1994: : foo ( n1 -- n2 )
                   1995:   0= if
                   1996:     14
                   1997:   else
                   1998:     0
                   1999:   endif ;
                   2000: 0 foo .
                   2001: 1 foo .
                   2002: 
                   2003: : foo ( n1 -- n2 )
                   2004:   0= 14 and ;
                   2005: 0 foo .
                   2006: 1 foo .
                   2007: @end example
                   2008: 
1.141     anton    2009: @quotation Assignment
1.48      anton    2010: Write @code{min} without @code{if}.
1.141     anton    2011: @end quotation
1.48      anton    2012: 
1.66      anton    2013: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
                   2014: @ref{Bitwise operations}.
                   2015: 
1.48      anton    2016: 
                   2017: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
                   2018: @section General Loops
1.66      anton    2019: @cindex loops, indefinite, tutorial
1.48      anton    2020: 
                   2021: The endless loop is the most simple one:
                   2022: 
                   2023: @example
                   2024: : endless ( -- )
                   2025:   0 begin
                   2026:     dup . 1+
                   2027:   again ;
                   2028: endless
                   2029: @end example
                   2030: 
                   2031: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
                   2032: does nothing at run-time, @code{again} jumps back to @code{begin}.
                   2033: 
                   2034: A loop with one exit at any place looks like this:
                   2035: 
                   2036: @example
                   2037: : log2 ( +n1 -- n2 )
                   2038: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2039:   assert( dup 0> )
                   2040:   2/ 0 begin
                   2041:     over 0> while
                   2042:       1+ swap 2/ swap
                   2043:   repeat
                   2044:   nip ;
                   2045: 7 log2 .
                   2046: 8 log2 .
                   2047: @end example
                   2048: 
                   2049: At run-time @code{while} consumes a flag; if it is 0, execution
1.51      pazsan   2050: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48      anton    2051: continues behind the @code{while}.  @code{Repeat} jumps back to
                   2052: @code{begin}, just like @code{again}.
                   2053: 
                   2054: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90      anton    2055: However, @code{2/} is not one of them; it shifts its argument right by
1.48      anton    2056: one bit (arithmetic shift right):
                   2057: 
                   2058: @example
                   2059: -5 2 / .
                   2060: -5 2/ .
                   2061: @end example
                   2062: 
                   2063: @code{assert(} is no standard word, but you can get it on systems other
                   2064: then Gforth by including @file{compat/assert.fs}.  You can see what it
                   2065: does by trying
                   2066: 
                   2067: @example
                   2068: 0 log2 .
                   2069: @end example
                   2070: 
                   2071: Here's a loop with an exit at the end:
                   2072: 
                   2073: @example
                   2074: : log2 ( +n1 -- n2 )
                   2075: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2076:   assert( dup 0 > )
                   2077:   -1 begin
                   2078:     1+ swap 2/ swap
                   2079:     over 0 <=
                   2080:   until
                   2081:   nip ;
                   2082: @end example
                   2083: 
                   2084: @code{Until} consumes a flag; if it is non-zero, execution continues at
                   2085: the @code{begin}, otherwise after the @code{until}.
                   2086: 
1.141     anton    2087: @quotation Assignment
1.48      anton    2088: Write a definition for computing the greatest common divisor.
1.141     anton    2089: @end quotation
1.48      anton    2090: 
1.66      anton    2091: Reference: @ref{Simple Loops}.
                   2092: 
1.48      anton    2093: 
                   2094: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
                   2095: @section Counted loops
1.66      anton    2096: @cindex loops, counted, tutorial
1.48      anton    2097: 
                   2098: @example
                   2099: : ^ ( n1 u -- n )
1.171     anton    2100: \ n = the uth power of n1
1.48      anton    2101:   1 swap 0 u+do
                   2102:     over *
                   2103:   loop
                   2104:   nip ;
                   2105: 3 2 ^ .
                   2106: 4 3 ^ .
                   2107: @end example
                   2108: 
                   2109: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
                   2110: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
                   2111: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
                   2112: times (or not at all, if @code{u3-u4<0}).
                   2113: 
                   2114: You can see the stack effect design rules at work in the stack effect of
                   2115: the loop start words: Since the start value of the loop is more
                   2116: frequently constant than the end value, the start value is passed on
                   2117: the top-of-stack.
                   2118: 
                   2119: You can access the counter of a counted loop with @code{i}:
                   2120: 
                   2121: @example
                   2122: : fac ( u -- u! )
                   2123:   1 swap 1+ 1 u+do
                   2124:     i *
                   2125:   loop ;
                   2126: 5 fac .
                   2127: 7 fac .
                   2128: @end example
                   2129: 
                   2130: There is also @code{+do}, which expects signed numbers (important for
                   2131: deciding whether to enter the loop).
                   2132: 
1.141     anton    2133: @quotation Assignment
1.48      anton    2134: Write a definition for computing the nth Fibonacci number.
1.141     anton    2135: @end quotation
1.48      anton    2136: 
1.65      anton    2137: You can also use increments other than 1:
                   2138: 
                   2139: @example
                   2140: : up2 ( n1 n2 -- )
                   2141:   +do
                   2142:     i .
                   2143:   2 +loop ;
                   2144: 10 0 up2
                   2145: 
                   2146: : down2 ( n1 n2 -- )
                   2147:   -do
                   2148:     i .
                   2149:   2 -loop ;
                   2150: 0 10 down2
                   2151: @end example
1.48      anton    2152: 
1.66      anton    2153: Reference: @ref{Counted Loops}.
                   2154: 
1.48      anton    2155: 
                   2156: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
                   2157: @section Recursion
1.66      anton    2158: @cindex recursion tutorial
1.48      anton    2159: 
                   2160: Usually the name of a definition is not visible in the definition; but
                   2161: earlier definitions are usually visible:
                   2162: 
                   2163: @example
1.166     anton    2164: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
1.48      anton    2165: : / ( n1 n2 -- n )
                   2166:   dup 0= if
                   2167:     -10 throw \ report division by zero
                   2168:   endif
                   2169:   /           \ old version
                   2170: ;
                   2171: 1 0 /
                   2172: @end example
                   2173: 
                   2174: For recursive definitions you can use @code{recursive} (non-standard) or
                   2175: @code{recurse}:
                   2176: 
                   2177: @example
                   2178: : fac1 ( n -- n! ) recursive
                   2179:  dup 0> if
                   2180:    dup 1- fac1 *
                   2181:  else
                   2182:    drop 1
                   2183:  endif ;
                   2184: 7 fac1 .
                   2185: 
                   2186: : fac2 ( n -- n! )
                   2187:  dup 0> if
                   2188:    dup 1- recurse *
                   2189:  else
                   2190:    drop 1
                   2191:  endif ;
                   2192: 8 fac2 .
                   2193: @end example
                   2194: 
1.141     anton    2195: @quotation Assignment
1.48      anton    2196: Write a recursive definition for computing the nth Fibonacci number.
1.141     anton    2197: @end quotation
1.48      anton    2198: 
1.66      anton    2199: Reference (including indirect recursion): @xref{Calls and returns}.
                   2200: 
1.48      anton    2201: 
                   2202: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
                   2203: @section Leaving definitions or loops
1.66      anton    2204: @cindex leaving definitions, tutorial
                   2205: @cindex leaving loops, tutorial
1.48      anton    2206: 
                   2207: @code{EXIT} exits the current definition right away.  For every counted
                   2208: loop that is left in this way, an @code{UNLOOP} has to be performed
                   2209: before the @code{EXIT}:
                   2210: 
                   2211: @c !! real examples
                   2212: @example
                   2213: : ...
                   2214:  ... u+do
                   2215:    ... if
                   2216:      ... unloop exit
                   2217:    endif
                   2218:    ...
                   2219:  loop
                   2220:  ... ;
                   2221: @end example
                   2222: 
                   2223: @code{LEAVE} leaves the innermost counted loop right away:
                   2224: 
                   2225: @example
                   2226: : ...
                   2227:  ... u+do
                   2228:    ... if
                   2229:      ... leave
                   2230:    endif
                   2231:    ...
                   2232:  loop
                   2233:  ... ;
                   2234: @end example
                   2235: 
1.65      anton    2236: @c !! example
1.48      anton    2237: 
1.66      anton    2238: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
                   2239: 
                   2240: 
1.48      anton    2241: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
                   2242: @section Return Stack
1.66      anton    2243: @cindex return stack tutorial
1.48      anton    2244: 
                   2245: In addition to the data stack Forth also has a second stack, the return
                   2246: stack; most Forth systems store the return addresses of procedure calls
                   2247: there (thus its name).  Programmers can also use this stack:
                   2248: 
                   2249: @example
                   2250: : foo ( n1 n2 -- )
                   2251:  .s
                   2252:  >r .s
1.50      anton    2253:  r@@ .
1.48      anton    2254:  >r .s
1.50      anton    2255:  r@@ .
1.48      anton    2256:  r> .
1.50      anton    2257:  r@@ .
1.48      anton    2258:  r> . ;
                   2259: 1 2 foo
                   2260: @end example
                   2261: 
                   2262: @code{>r} takes an element from the data stack and pushes it onto the
                   2263: return stack; conversely, @code{r>} moves an elementm from the return to
                   2264: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148     anton    2265: on the data stack.
1.48      anton    2266: 
                   2267: Forth programmers usually use the return stack for storing data
                   2268: temporarily, if using the data stack alone would be too complex, and
                   2269: factoring and locals are not an option:
                   2270: 
                   2271: @example
                   2272: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
                   2273:  rot >r rot r> ;
                   2274: @end example
                   2275: 
                   2276: The return address of the definition and the loop control parameters of
                   2277: counted loops usually reside on the return stack, so you have to take
                   2278: all items, that you have pushed on the return stack in a colon
                   2279: definition or counted loop, from the return stack before the definition
                   2280: or loop ends.  You cannot access items that you pushed on the return
                   2281: stack outside some definition or loop within the definition of loop.
                   2282: 
                   2283: If you miscount the return stack items, this usually ends in a crash:
                   2284: 
                   2285: @example
                   2286: : crash ( n -- )
                   2287:   >r ;
                   2288: 5 crash
                   2289: @end example
                   2290: 
                   2291: You cannot mix using locals and using the return stack (according to the
                   2292: standard; Gforth has no problem).  However, they solve the same
                   2293: problems, so this shouldn't be an issue.
                   2294: 
1.141     anton    2295: @quotation Assignment
1.48      anton    2296: Can you rewrite any of the definitions you wrote until now in a better
                   2297: way using the return stack?
1.141     anton    2298: @end quotation
1.48      anton    2299: 
1.66      anton    2300: Reference: @ref{Return stack}.
                   2301: 
1.48      anton    2302: 
                   2303: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
                   2304: @section Memory
1.66      anton    2305: @cindex memory access/allocation tutorial
1.48      anton    2306: 
                   2307: You can create a global variable @code{v} with
                   2308: 
                   2309: @example
                   2310: variable v ( -- addr )
                   2311: @end example
                   2312: 
                   2313: @code{v} pushes the address of a cell in memory on the stack.  This cell
                   2314: was reserved by @code{variable}.  You can use @code{!} (store) to store
                   2315: values into this cell and @code{@@} (fetch) to load the value from the
                   2316: stack into memory:
                   2317: 
                   2318: @example
                   2319: v .
                   2320: 5 v ! .s
1.50      anton    2321: v @@ .
1.48      anton    2322: @end example
                   2323: 
1.65      anton    2324: You can see a raw dump of memory with @code{dump}:
                   2325: 
                   2326: @example
                   2327: v 1 cells .s dump
                   2328: @end example
                   2329: 
                   2330: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
                   2331: generally, address units (aus)) that @code{n1 cells} occupy.  You can
                   2332: also reserve more memory:
1.48      anton    2333: 
                   2334: @example
                   2335: create v2 20 cells allot
1.65      anton    2336: v2 20 cells dump
1.48      anton    2337: @end example
                   2338: 
1.65      anton    2339: creates a word @code{v2} and reserves 20 uninitialized cells; the
                   2340: address pushed by @code{v2} points to the start of these 20 cells.  You
                   2341: can use address arithmetic to access these cells:
1.48      anton    2342: 
                   2343: @example
                   2344: 3 v2 5 cells + !
1.65      anton    2345: v2 20 cells dump
1.48      anton    2346: @end example
                   2347: 
                   2348: You can reserve and initialize memory with @code{,}:
                   2349: 
                   2350: @example
                   2351: create v3
                   2352:   5 , 4 , 3 , 2 , 1 ,
1.50      anton    2353: v3 @@ .
                   2354: v3 cell+ @@ .
                   2355: v3 2 cells + @@ .
1.65      anton    2356: v3 5 cells dump
1.48      anton    2357: @end example
                   2358: 
1.141     anton    2359: @quotation Assignment
1.48      anton    2360: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
                   2361: @code{u} cells, with the first of these cells at @code{addr}, the next
                   2362: one at @code{addr cell+} etc.
1.141     anton    2363: @end quotation
1.48      anton    2364: 
                   2365: You can also reserve memory without creating a new word:
                   2366: 
                   2367: @example
1.60      anton    2368: here 10 cells allot .
                   2369: here .
1.48      anton    2370: @end example
                   2371: 
                   2372: @code{Here} pushes the start address of the memory area.  You should
                   2373: store it somewhere, or you will have a hard time finding the memory area
                   2374: again.
                   2375: 
                   2376: @code{Allot} manages dictionary memory.  The dictionary memory contains
                   2377: the system's data structures for words etc. on Gforth and most other
                   2378: Forth systems.  It is managed like a stack: You can free the memory that
                   2379: you have just @code{allot}ed with
                   2380: 
                   2381: @example
                   2382: -10 cells allot
1.60      anton    2383: here .
1.48      anton    2384: @end example
                   2385: 
                   2386: Note that you cannot do this if you have created a new word in the
                   2387: meantime (because then your @code{allot}ed memory is no longer on the
                   2388: top of the dictionary ``stack'').
                   2389: 
                   2390: Alternatively, you can use @code{allocate} and @code{free} which allow
                   2391: freeing memory in any order:
                   2392: 
                   2393: @example
                   2394: 10 cells allocate throw .s
                   2395: 20 cells allocate throw .s
                   2396: swap
                   2397: free throw
                   2398: free throw
                   2399: @end example
                   2400: 
                   2401: The @code{throw}s deal with errors (e.g., out of memory).
                   2402: 
1.65      anton    2403: And there is also a
                   2404: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   2405: garbage collector}, which eliminates the need to @code{free} memory
                   2406: explicitly.
1.48      anton    2407: 
1.66      anton    2408: Reference: @ref{Memory}.
                   2409: 
1.48      anton    2410: 
                   2411: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
                   2412: @section Characters and Strings
1.66      anton    2413: @cindex strings tutorial
                   2414: @cindex characters tutorial
1.48      anton    2415: 
                   2416: On the stack characters take up a cell, like numbers.  In memory they
                   2417: have their own size (one 8-bit byte on most systems), and therefore
                   2418: require their own words for memory access:
                   2419: 
                   2420: @example
                   2421: create v4 
                   2422:   104 c, 97 c, 108 c, 108 c, 111 c,
1.50      anton    2423: v4 4 chars + c@@ .
1.65      anton    2424: v4 5 chars dump
1.48      anton    2425: @end example
                   2426: 
                   2427: The preferred representation of strings on the stack is @code{addr
                   2428: u-count}, where @code{addr} is the address of the first character and
                   2429: @code{u-count} is the number of characters in the string.
                   2430: 
                   2431: @example
                   2432: v4 5 type
                   2433: @end example
                   2434: 
                   2435: You get a string constant with
                   2436: 
                   2437: @example
                   2438: s" hello, world" .s
                   2439: type
                   2440: @end example
                   2441: 
                   2442: Make sure you have a space between @code{s"} and the string; @code{s"}
                   2443: is a normal Forth word and must be delimited with white space (try what
                   2444: happens when you remove the space).
                   2445: 
                   2446: However, this interpretive use of @code{s"} is quite restricted: the
                   2447: string exists only until the next call of @code{s"} (some Forth systems
                   2448: keep more than one of these strings, but usually they still have a
1.62      crook    2449: limited lifetime).
1.48      anton    2450: 
                   2451: @example
                   2452: s" hello," s" world" .s
                   2453: type
                   2454: type
                   2455: @end example
                   2456: 
1.62      crook    2457: You can also use @code{s"} in a definition, and the resulting
                   2458: strings then live forever (well, for as long as the definition):
1.48      anton    2459: 
                   2460: @example
                   2461: : foo s" hello," s" world" ;
                   2462: foo .s
                   2463: type
                   2464: type
                   2465: @end example
                   2466: 
1.141     anton    2467: @quotation Assignment
1.48      anton    2468: @code{Emit ( c -- )} types @code{c} as character (not a number).
                   2469: Implement @code{type ( addr u -- )}.
1.141     anton    2470: @end quotation
1.48      anton    2471: 
1.66      anton    2472: Reference: @ref{Memory Blocks}.
                   2473: 
                   2474: 
1.84      pazsan   2475: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48      anton    2476: @section Alignment
1.66      anton    2477: @cindex alignment tutorial
                   2478: @cindex memory alignment tutorial
1.48      anton    2479: 
                   2480: On many processors cells have to be aligned in memory, if you want to
                   2481: access them with @code{@@} and @code{!} (and even if the processor does
1.62      crook    2482: not require alignment, access to aligned cells is faster).
1.48      anton    2483: 
                   2484: @code{Create} aligns @code{here} (i.e., the place where the next
                   2485: allocation will occur, and that the @code{create}d word points to).
                   2486: Likewise, the memory produced by @code{allocate} starts at an aligned
                   2487: address.  Adding a number of @code{cells} to an aligned address produces
                   2488: another aligned address.
                   2489: 
                   2490: However, address arithmetic involving @code{char+} and @code{chars} can
                   2491: create an address that is not cell-aligned.  @code{Aligned ( addr --
                   2492: a-addr )} produces the next aligned address:
                   2493: 
                   2494: @example
1.50      anton    2495: v3 char+ aligned .s @@ .
                   2496: v3 char+ .s @@ .
1.48      anton    2497: @end example
                   2498: 
                   2499: Similarly, @code{align} advances @code{here} to the next aligned
                   2500: address:
                   2501: 
                   2502: @example
                   2503: create v5 97 c,
                   2504: here .
                   2505: align here .
                   2506: 1000 ,
                   2507: @end example
                   2508: 
                   2509: Note that you should use aligned addresses even if your processor does
                   2510: not require them, if you want your program to be portable.
                   2511: 
1.66      anton    2512: Reference: @ref{Address arithmetic}.
                   2513: 
1.48      anton    2514: 
1.84      pazsan   2515: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
                   2516: @section Files
                   2517: @cindex files tutorial
                   2518: 
                   2519: This section gives a short introduction into how to use files inside
                   2520: Forth. It's broken up into five easy steps:
                   2521: 
                   2522: @enumerate 1
                   2523: @item Opened an ASCII text file for input
                   2524: @item Opened a file for output
                   2525: @item Read input file until string matched (or some other condition matched)
                   2526: @item Wrote some lines from input ( modified or not) to output
                   2527: @item Closed the files.
                   2528: @end enumerate
                   2529: 
1.153     anton    2530: Reference: @ref{General files}.
                   2531: 
1.84      pazsan   2532: @subsection Open file for input
                   2533: 
                   2534: @example
                   2535: s" foo.in"  r/o open-file throw Value fd-in
                   2536: @end example
                   2537: 
                   2538: @subsection Create file for output
                   2539: 
                   2540: @example
                   2541: s" foo.out" w/o create-file throw Value fd-out
                   2542: @end example
                   2543: 
                   2544: The available file modes are r/o for read-only access, r/w for
                   2545: read-write access, and w/o for write-only access. You could open both
                   2546: files with r/w, too, if you like. All file words return error codes; for
                   2547: most applications, it's best to pass there error codes with @code{throw}
                   2548: to the outer error handler.
                   2549: 
                   2550: If you want words for opening and assigning, define them as follows:
                   2551: 
                   2552: @example
                   2553: 0 Value fd-in
                   2554: 0 Value fd-out
                   2555: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
                   2556: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
                   2557: @end example
                   2558: 
                   2559: Usage example:
                   2560: 
                   2561: @example
                   2562: s" foo.in" open-input
                   2563: s" foo.out" open-output
                   2564: @end example
                   2565: 
                   2566: @subsection Scan file for a particular line
                   2567: 
                   2568: @example
                   2569: 256 Constant max-line
                   2570: Create line-buffer  max-line 2 + allot
                   2571: 
                   2572: : scan-file ( addr u -- )
                   2573:   begin
                   2574:       line-buffer max-line fd-in read-line throw
                   2575:   while
                   2576:          >r 2dup line-buffer r> compare 0=
                   2577:      until
                   2578:   else
                   2579:      drop
                   2580:   then
                   2581:   2drop ;
                   2582: @end example
                   2583: 
                   2584: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94      anton    2585: the buffer at addr, and returns the number of bytes read, a flag that is
                   2586: false when the end of file is reached, and an error code.
1.84      pazsan   2587: 
                   2588: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
                   2589: returns zero if both strings are equal. It returns a positive number if
                   2590: the first string is lexically greater, a negative if the second string
                   2591: is lexically greater.
                   2592: 
                   2593: We haven't seen this loop here; it has two exits. Since the @code{while}
                   2594: exits with the number of bytes read on the stack, we have to clean up
                   2595: that separately; that's after the @code{else}.
                   2596: 
                   2597: Usage example:
                   2598: 
                   2599: @example
                   2600: s" The text I search is here" scan-file
                   2601: @end example
                   2602: 
                   2603: @subsection Copy input to output
                   2604: 
                   2605: @example
                   2606: : copy-file ( -- )
                   2607:   begin
                   2608:       line-buffer max-line fd-in read-line throw
                   2609:   while
                   2610:       line-buffer swap fd-out write-file throw
                   2611:   repeat ;
                   2612: @end example
                   2613: 
                   2614: @subsection Close files
                   2615: 
                   2616: @example
                   2617: fd-in close-file throw
                   2618: fd-out close-file throw
                   2619: @end example
                   2620: 
                   2621: Likewise, you can put that into definitions, too:
                   2622: 
                   2623: @example
                   2624: : close-input ( -- )  fd-in close-file throw ;
                   2625: : close-output ( -- )  fd-out close-file throw ;
                   2626: @end example
                   2627: 
1.141     anton    2628: @quotation Assignment
1.84      pazsan   2629: How could you modify @code{copy-file} so that it copies until a second line is
                   2630: matched? Can you write a program that extracts a section of a text file,
                   2631: given the line that starts and the line that terminates that section?
1.141     anton    2632: @end quotation
1.84      pazsan   2633: 
                   2634: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48      anton    2635: @section Interpretation and Compilation Semantics and Immediacy
1.66      anton    2636: @cindex semantics tutorial
                   2637: @cindex interpretation semantics tutorial
                   2638: @cindex compilation semantics tutorial
                   2639: @cindex immediate, tutorial
1.48      anton    2640: 
                   2641: When a word is compiled, it behaves differently from being interpreted.
                   2642: E.g., consider @code{+}:
                   2643: 
                   2644: @example
                   2645: 1 2 + .
                   2646: : foo + ;
                   2647: @end example
                   2648: 
                   2649: These two behaviours are known as compilation and interpretation
                   2650: semantics.  For normal words (e.g., @code{+}), the compilation semantics
                   2651: is to append the interpretation semantics to the currently defined word
                   2652: (@code{foo} in the example above).  I.e., when @code{foo} is executed
                   2653: later, the interpretation semantics of @code{+} (i.e., adding two
                   2654: numbers) will be performed.
                   2655: 
                   2656: However, there are words with non-default compilation semantics, e.g.,
                   2657: the control-flow words like @code{if}.  You can use @code{immediate} to
                   2658: change the compilation semantics of the last defined word to be equal to
                   2659: the interpretation semantics:
                   2660: 
                   2661: @example
                   2662: : [FOO] ( -- )
                   2663:  5 . ; immediate
                   2664: 
                   2665: [FOO]
                   2666: : bar ( -- )
                   2667:   [FOO] ;
                   2668: bar
                   2669: see bar
                   2670: @end example
                   2671: 
                   2672: Two conventions to mark words with non-default compilation semnatics are
                   2673: names with brackets (more frequently used) and to write them all in
                   2674: upper case (less frequently used).
                   2675: 
                   2676: In Gforth (and many other systems) you can also remove the
                   2677: interpretation semantics with @code{compile-only} (the compilation
                   2678: semantics is derived from the original interpretation semantics):
                   2679: 
                   2680: @example
                   2681: : flip ( -- )
                   2682:  6 . ; compile-only \ but not immediate
                   2683: flip
                   2684: 
                   2685: : flop ( -- )
                   2686:  flip ;
                   2687: flop
                   2688: @end example
                   2689: 
                   2690: In this example the interpretation semantics of @code{flop} is equal to
                   2691: the original interpretation semantics of @code{flip}.
                   2692: 
                   2693: The text interpreter has two states: in interpret state, it performs the
                   2694: interpretation semantics of words it encounters; in compile state, it
                   2695: performs the compilation semantics of these words.
                   2696: 
                   2697: Among other things, @code{:} switches into compile state, and @code{;}
                   2698: switches back to interpret state.  They contain the factors @code{]}
                   2699: (switch to compile state) and @code{[} (switch to interpret state), that
                   2700: do nothing but switch the state.
                   2701: 
                   2702: @example
                   2703: : xxx ( -- )
                   2704:   [ 5 . ]
                   2705: ;
                   2706: 
                   2707: xxx
                   2708: see xxx
                   2709: @end example
                   2710: 
                   2711: These brackets are also the source of the naming convention mentioned
                   2712: above.
                   2713: 
1.66      anton    2714: Reference: @ref{Interpretation and Compilation Semantics}.
                   2715: 
1.48      anton    2716: 
                   2717: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
                   2718: @section Execution Tokens
1.66      anton    2719: @cindex execution tokens tutorial
                   2720: @cindex XT tutorial
1.48      anton    2721: 
                   2722: @code{' word} gives you the execution token (XT) of a word.  The XT is a
                   2723: cell representing the interpretation semantics of a word.  You can
                   2724: execute this semantics with @code{execute}:
                   2725: 
                   2726: @example
                   2727: ' + .s
                   2728: 1 2 rot execute .
                   2729: @end example
                   2730: 
                   2731: The XT is similar to a function pointer in C.  However, parameter
                   2732: passing through the stack makes it a little more flexible:
                   2733: 
                   2734: @example
                   2735: : map-array ( ... addr u xt -- ... )
1.50      anton    2736: \ executes xt ( ... x -- ... ) for every element of the array starting
                   2737: \ at addr and containing u elements
1.48      anton    2738:   @{ xt @}
                   2739:   cells over + swap ?do
1.50      anton    2740:     i @@ xt execute
1.48      anton    2741:   1 cells +loop ;
                   2742: 
                   2743: create a 3 , 4 , 2 , -1 , 4 ,
                   2744: a 5 ' . map-array .s
                   2745: 0 a 5 ' + map-array .
                   2746: s" max-n" environment? drop .s
                   2747: a 5 ' min map-array .
                   2748: @end example
                   2749: 
                   2750: You can use map-array with the XTs of words that consume one element
                   2751: more than they produce.  In theory you can also use it with other XTs,
                   2752: but the stack effect then depends on the size of the array, which is
                   2753: hard to understand.
                   2754: 
1.51      pazsan   2755: Since XTs are cell-sized, you can store them in memory and manipulate
                   2756: them on the stack like other cells.  You can also compile the XT into a
1.48      anton    2757: word with @code{compile,}:
                   2758: 
                   2759: @example
                   2760: : foo1 ( n1 n2 -- n )
                   2761:    [ ' + compile, ] ;
                   2762: see foo
                   2763: @end example
                   2764: 
                   2765: This is non-standard, because @code{compile,} has no compilation
                   2766: semantics in the standard, but it works in good Forth systems.  For the
                   2767: broken ones, use
                   2768: 
                   2769: @example
                   2770: : [compile,] compile, ; immediate
                   2771: 
                   2772: : foo1 ( n1 n2 -- n )
                   2773:    [ ' + ] [compile,] ;
                   2774: see foo
                   2775: @end example
                   2776: 
                   2777: @code{'} is a word with default compilation semantics; it parses the
                   2778: next word when its interpretation semantics are executed, not during
                   2779: compilation:
                   2780: 
                   2781: @example
                   2782: : foo ( -- xt )
                   2783:   ' ;
                   2784: see foo
                   2785: : bar ( ... "word" -- ... )
                   2786:   ' execute ;
                   2787: see bar
1.60      anton    2788: 1 2 bar + .
1.48      anton    2789: @end example
                   2790: 
                   2791: You often want to parse a word during compilation and compile its XT so
                   2792: it will be pushed on the stack at run-time.  @code{[']} does this:
                   2793: 
                   2794: @example
                   2795: : xt-+ ( -- xt )
                   2796:   ['] + ;
                   2797: see xt-+
                   2798: 1 2 xt-+ execute .
                   2799: @end example
                   2800: 
                   2801: Many programmers tend to see @code{'} and the word it parses as one
                   2802: unit, and expect it to behave like @code{[']} when compiled, and are
                   2803: confused by the actual behaviour.  If you are, just remember that the
                   2804: Forth system just takes @code{'} as one unit and has no idea that it is
                   2805: a parsing word (attempts to convenience programmers in this issue have
                   2806: usually resulted in even worse pitfalls, see
1.66      anton    2807: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
                   2808: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48      anton    2809: 
                   2810: Note that the state of the interpreter does not come into play when
1.51      pazsan   2811: creating and executing XTs.  I.e., even when you execute @code{'} in
1.48      anton    2812: compile state, it still gives you the interpretation semantics.  And
                   2813: whatever that state is, @code{execute} performs the semantics
1.66      anton    2814: represented by the XT (i.e., for XTs produced with @code{'} the
                   2815: interpretation semantics).
                   2816: 
                   2817: Reference: @ref{Tokens for Words}.
1.48      anton    2818: 
                   2819: 
                   2820: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
                   2821: @section Exceptions
1.66      anton    2822: @cindex exceptions tutorial
1.48      anton    2823: 
                   2824: @code{throw ( n -- )} causes an exception unless n is zero.
                   2825: 
                   2826: @example
                   2827: 100 throw .s
                   2828: 0 throw .s
                   2829: @end example
                   2830: 
                   2831: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
                   2832: it catches exceptions and pushes the number of the exception on the
                   2833: stack (or 0, if the xt executed without exception).  If there was an
                   2834: exception, the stacks have the same depth as when entering @code{catch}:
                   2835: 
                   2836: @example
                   2837: .s
                   2838: 3 0 ' / catch .s
                   2839: 3 2 ' / catch .s
                   2840: @end example
                   2841: 
1.141     anton    2842: @quotation Assignment
1.48      anton    2843: Try the same with @code{execute} instead of @code{catch}.
1.141     anton    2844: @end quotation
1.48      anton    2845: 
                   2846: @code{Throw} always jumps to the dynamically next enclosing
                   2847: @code{catch}, even if it has to leave several call levels to achieve
                   2848: this:
                   2849: 
                   2850: @example
                   2851: : foo 100 throw ;
                   2852: : foo1 foo ." after foo" ;
1.51      pazsan   2853: : bar ['] foo1 catch ;
1.60      anton    2854: bar .
1.48      anton    2855: @end example
                   2856: 
                   2857: It is often important to restore a value upon leaving a definition, even
                   2858: if the definition is left through an exception.  You can ensure this
                   2859: like this:
                   2860: 
                   2861: @example
                   2862: : ...
                   2863:    save-x
1.51      pazsan   2864:    ['] word-changing-x catch ( ... n )
1.48      anton    2865:    restore-x
                   2866:    ( ... n ) throw ;
                   2867: @end example
                   2868: 
1.172     anton    2869: However, this is still not safe against, e.g., the user pressing
                   2870: @kbd{Ctrl-C} when execution is between the @code{catch} and
                   2871: @code{restore-x}.
                   2872: 
                   2873: Gforth provides an alternative exception handling syntax that is safe
                   2874: against such cases: @code{try ... restore ... endtry}.  If the code
                   2875: between @code{try} and @code{endtry} has an exception, the stack
                   2876: depths are restored, the exception number is pushed on the stack, and
                   2877: the execution continues right after @code{restore}.
1.48      anton    2878: 
1.172     anton    2879: The safer equivalent to the restoration code above is
1.48      anton    2880: 
                   2881: @example
                   2882: : ...
                   2883:   save-x
                   2884:   try
1.92      anton    2885:     word-changing-x 0
1.172     anton    2886:   restore
                   2887:     restore-x
                   2888:   endtry
1.48      anton    2889:   throw ;
                   2890: @end example
                   2891: 
1.66      anton    2892: Reference: @ref{Exception Handling}.
                   2893: 
1.48      anton    2894: 
                   2895: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
                   2896: @section Defining Words
1.66      anton    2897: @cindex defining words tutorial
                   2898: @cindex does> tutorial
                   2899: @cindex create...does> tutorial
                   2900: 
                   2901: @c before semantics?
1.48      anton    2902: 
                   2903: @code{:}, @code{create}, and @code{variable} are definition words: They
                   2904: define other words.  @code{Constant} is another definition word:
                   2905: 
                   2906: @example
                   2907: 5 constant foo
                   2908: foo .
                   2909: @end example
                   2910: 
                   2911: You can also use the prefixes @code{2} (double-cell) and @code{f}
                   2912: (floating point) with @code{variable} and @code{constant}.
                   2913: 
                   2914: You can also define your own defining words.  E.g.:
                   2915: 
                   2916: @example
                   2917: : variable ( "name" -- )
                   2918:   create 0 , ;
                   2919: @end example
                   2920: 
                   2921: You can also define defining words that create words that do something
                   2922: other than just producing their address:
                   2923: 
                   2924: @example
                   2925: : constant ( n "name" -- )
                   2926:   create ,
                   2927: does> ( -- n )
1.50      anton    2928:   ( addr ) @@ ;
1.48      anton    2929: 
                   2930: 5 constant foo
                   2931: foo .
                   2932: @end example
                   2933: 
                   2934: The definition of @code{constant} above ends at the @code{does>}; i.e.,
                   2935: @code{does>} replaces @code{;}, but it also does something else: It
                   2936: changes the last defined word such that it pushes the address of the
                   2937: body of the word and then performs the code after the @code{does>}
                   2938: whenever it is called.
                   2939: 
                   2940: In the example above, @code{constant} uses @code{,} to store 5 into the
                   2941: body of @code{foo}.  When @code{foo} executes, it pushes the address of
                   2942: the body onto the stack, then (in the code after the @code{does>})
                   2943: fetches the 5 from there.
                   2944: 
                   2945: The stack comment near the @code{does>} reflects the stack effect of the
                   2946: defined word, not the stack effect of the code after the @code{does>}
                   2947: (the difference is that the code expects the address of the body that
                   2948: the stack comment does not show).
                   2949: 
                   2950: You can use these definition words to do factoring in cases that involve
                   2951: (other) definition words.  E.g., a field offset is always added to an
                   2952: address.  Instead of defining
                   2953: 
                   2954: @example
                   2955: 2 cells constant offset-field1
                   2956: @end example
                   2957: 
                   2958: and using this like
                   2959: 
                   2960: @example
                   2961: ( addr ) offset-field1 +
                   2962: @end example
                   2963: 
                   2964: you can define a definition word
                   2965: 
                   2966: @example
                   2967: : simple-field ( n "name" -- )
                   2968:   create ,
                   2969: does> ( n1 -- n1+n )
1.50      anton    2970:   ( addr ) @@ + ;
1.48      anton    2971: @end example
1.21      crook    2972: 
1.48      anton    2973: Definition and use of field offsets now look like this:
1.21      crook    2974: 
1.48      anton    2975: @example
                   2976: 2 cells simple-field field1
1.60      anton    2977: create mystruct 4 cells allot
                   2978: mystruct .s field1 .s drop
1.48      anton    2979: @end example
1.21      crook    2980: 
1.48      anton    2981: If you want to do something with the word without performing the code
                   2982: after the @code{does>}, you can access the body of a @code{create}d word
                   2983: with @code{>body ( xt -- addr )}:
1.21      crook    2984: 
1.48      anton    2985: @example
                   2986: : value ( n "name" -- )
                   2987:   create ,
                   2988: does> ( -- n1 )
1.50      anton    2989:   @@ ;
1.48      anton    2990: : to ( n "name" -- )
                   2991:   ' >body ! ;
1.21      crook    2992: 
1.48      anton    2993: 5 value foo
                   2994: foo .
                   2995: 7 to foo
                   2996: foo .
                   2997: @end example
1.21      crook    2998: 
1.141     anton    2999: @quotation Assignment
1.48      anton    3000: Define @code{defer ( "name" -- )}, which creates a word that stores an
                   3001: XT (at the start the XT of @code{abort}), and upon execution
                   3002: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
                   3003: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
                   3004: recursion is one application of @code{defer}.
1.141     anton    3005: @end quotation
1.29      crook    3006: 
1.66      anton    3007: Reference: @ref{User-defined Defining Words}.
                   3008: 
                   3009: 
1.48      anton    3010: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
                   3011: @section Arrays and Records
1.66      anton    3012: @cindex arrays tutorial
                   3013: @cindex records tutorial
                   3014: @cindex structs tutorial
1.29      crook    3015: 
1.48      anton    3016: Forth has no standard words for defining data structures such as arrays
                   3017: and records (structs in C terminology), but you can build them yourself
                   3018: based on address arithmetic.  You can also define words for defining
                   3019: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29      crook    3020: 
1.48      anton    3021: One of the first projects a Forth newcomer sets out upon when learning
                   3022: about defining words is an array defining word (possibly for
                   3023: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
                   3024: learn something from it.  However, don't be disappointed when you later
                   3025: learn that you have little use for these words (inappropriate use would
                   3026: be even worse).  I have not yet found a set of useful array words yet;
                   3027: the needs are just too diverse, and named, global arrays (the result of
                   3028: naive use of defining words) are often not flexible enough (e.g.,
1.66      anton    3029: consider how to pass them as parameters).  Another such project is a set
                   3030: of words to help dealing with strings.
1.29      crook    3031: 
1.48      anton    3032: On the other hand, there is a useful set of record words, and it has
                   3033: been defined in @file{compat/struct.fs}; these words are predefined in
                   3034: Gforth.  They are explained in depth elsewhere in this manual (see
                   3035: @pxref{Structures}).  The @code{simple-field} example above is
                   3036: simplified variant of fields in this package.
1.21      crook    3037: 
                   3038: 
1.48      anton    3039: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
                   3040: @section @code{POSTPONE}
1.66      anton    3041: @cindex postpone tutorial
1.21      crook    3042: 
1.48      anton    3043: You can compile the compilation semantics (instead of compiling the
                   3044: interpretation semantics) of a word with @code{POSTPONE}:
1.21      crook    3045: 
1.48      anton    3046: @example
                   3047: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51      pazsan   3048:  POSTPONE + ; immediate
1.48      anton    3049: : foo ( n1 n2 -- n )
                   3050:  MY-+ ;
                   3051: 1 2 foo .
                   3052: see foo
                   3053: @end example
1.21      crook    3054: 
1.48      anton    3055: During the definition of @code{foo} the text interpreter performs the
                   3056: compilation semantics of @code{MY-+}, which performs the compilation
                   3057: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
                   3058: 
                   3059: This example also displays separate stack comments for the compilation
                   3060: semantics and for the stack effect of the compiled code.  For words with
                   3061: default compilation semantics these stack effects are usually not
                   3062: displayed; the stack effect of the compilation semantics is always
                   3063: @code{( -- )} for these words, the stack effect for the compiled code is
                   3064: the stack effect of the interpretation semantics.
                   3065: 
                   3066: Note that the state of the interpreter does not come into play when
                   3067: performing the compilation semantics in this way.  You can also perform
                   3068: it interpretively, e.g.:
                   3069: 
                   3070: @example
                   3071: : foo2 ( n1 n2 -- n )
                   3072:  [ MY-+ ] ;
                   3073: 1 2 foo .
                   3074: see foo
                   3075: @end example
1.21      crook    3076: 
1.48      anton    3077: However, there are some broken Forth systems where this does not always
1.62      crook    3078: work, and therefore this practice was been declared non-standard in
1.48      anton    3079: 1999.
                   3080: @c !! repair.fs
                   3081: 
                   3082: Here is another example for using @code{POSTPONE}:
1.44      crook    3083: 
1.48      anton    3084: @example
                   3085: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
                   3086:  POSTPONE negate POSTPONE + ; immediate compile-only
                   3087: : bar ( n1 n2 -- n )
                   3088:   MY-- ;
                   3089: 2 1 bar .
                   3090: see bar
                   3091: @end example
1.21      crook    3092: 
1.48      anton    3093: You can define @code{ENDIF} in this way:
1.21      crook    3094: 
1.48      anton    3095: @example
                   3096: : ENDIF ( Compilation: orig -- )
                   3097:   POSTPONE then ; immediate
                   3098: @end example
1.21      crook    3099: 
1.141     anton    3100: @quotation Assignment
1.48      anton    3101: Write @code{MY-2DUP} that has compilation semantics equivalent to
                   3102: @code{2dup}, but compiles @code{over over}.
1.141     anton    3103: @end quotation
1.29      crook    3104: 
1.66      anton    3105: @c !! @xref{Macros} for reference
                   3106: 
                   3107: 
1.48      anton    3108: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
                   3109: @section @code{Literal}
1.66      anton    3110: @cindex literal tutorial
1.29      crook    3111: 
1.48      anton    3112: You cannot @code{POSTPONE} numbers:
1.21      crook    3113: 
1.48      anton    3114: @example
                   3115: : [FOO] POSTPONE 500 ; immediate
1.21      crook    3116: @end example
                   3117: 
1.48      anton    3118: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29      crook    3119: 
1.48      anton    3120: @example
                   3121: : [FOO] ( compilation: --; run-time: -- n )
                   3122:   500 POSTPONE literal ; immediate
1.29      crook    3123: 
1.60      anton    3124: : flip [FOO] ;
1.48      anton    3125: flip .
                   3126: see flip
                   3127: @end example
1.29      crook    3128: 
1.48      anton    3129: @code{LITERAL} consumes a number at compile-time (when it's compilation
                   3130: semantics are executed) and pushes it at run-time (when the code it
                   3131: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
                   3132: number computed at compile time into the current word:
1.29      crook    3133: 
1.48      anton    3134: @example
                   3135: : bar ( -- n )
                   3136:   [ 2 2 + ] literal ;
                   3137: see bar
                   3138: @end example
1.29      crook    3139: 
1.141     anton    3140: @quotation Assignment
1.48      anton    3141: Write @code{]L} which allows writing the example above as @code{: bar (
                   3142: -- n ) [ 2 2 + ]L ;}
1.141     anton    3143: @end quotation
1.48      anton    3144: 
1.66      anton    3145: @c !! @xref{Macros} for reference
                   3146: 
1.48      anton    3147: 
                   3148: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
                   3149: @section Advanced macros
1.66      anton    3150: @cindex macros, advanced tutorial
                   3151: @cindex run-time code generation, tutorial
1.48      anton    3152: 
1.66      anton    3153: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
                   3154: Execution Tokens}.  It frequently performs @code{execute}, a relatively
                   3155: expensive operation in some Forth implementations.  You can use
1.48      anton    3156: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
                   3157: and produce a word that contains the word to be performed directly:
                   3158: 
                   3159: @c use ]] ... [[
                   3160: @example
                   3161: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
                   3162: \ at run-time, execute xt ( ... x -- ... ) for each element of the
                   3163: \ array beginning at addr and containing u elements
                   3164:   @{ xt @}
                   3165:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50      anton    3166:     POSTPONE i POSTPONE @@ xt compile,
1.48      anton    3167:   1 cells POSTPONE literal POSTPONE +loop ;
                   3168: 
                   3169: : sum-array ( addr u -- n )
                   3170:  0 rot rot [ ' + compile-map-array ] ;
                   3171: see sum-array
                   3172: a 5 sum-array .
                   3173: @end example
                   3174: 
                   3175: You can use the full power of Forth for generating the code; here's an
                   3176: example where the code is generated in a loop:
                   3177: 
                   3178: @example
                   3179: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
                   3180: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50      anton    3181:   POSTPONE tuck POSTPONE @@
1.48      anton    3182:   POSTPONE literal POSTPONE * POSTPONE +
                   3183:   POSTPONE swap POSTPONE cell+ ;
                   3184: 
                   3185: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51      pazsan   3186: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48      anton    3187:   0 postpone literal postpone swap
                   3188:   [ ' compile-vmul-step compile-map-array ]
                   3189:   postpone drop ;
                   3190: see compile-vmul
                   3191: 
                   3192: : a-vmul ( addr -- n )
1.51      pazsan   3193: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48      anton    3194:  [ a 5 compile-vmul ] ;
                   3195: see a-vmul
                   3196: a a-vmul .
                   3197: @end example
                   3198: 
                   3199: This example uses @code{compile-map-array} to show off, but you could
1.66      anton    3200: also use @code{map-array} instead (try it now!).
1.48      anton    3201: 
                   3202: You can use this technique for efficient multiplication of large
                   3203: matrices.  In matrix multiplication, you multiply every line of one
                   3204: matrix with every column of the other matrix.  You can generate the code
                   3205: for one line once, and use it for every column.  The only downside of
                   3206: this technique is that it is cumbersome to recover the memory consumed
                   3207: by the generated code when you are done (and in more complicated cases
                   3208: it is not possible portably).
                   3209: 
1.66      anton    3210: @c !! @xref{Macros} for reference
                   3211: 
                   3212: 
1.48      anton    3213: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
                   3214: @section Compilation Tokens
1.66      anton    3215: @cindex compilation tokens, tutorial
                   3216: @cindex CT, tutorial
1.48      anton    3217: 
                   3218: This section is Gforth-specific.  You can skip it.
                   3219: 
                   3220: @code{' word compile,} compiles the interpretation semantics.  For words
                   3221: with default compilation semantics this is the same as performing the
                   3222: compilation semantics.  To represent the compilation semantics of other
                   3223: words (e.g., words like @code{if} that have no interpretation
                   3224: semantics), Gforth has the concept of a compilation token (CT,
                   3225: consisting of two cells), and words @code{comp'} and @code{[comp']}.
                   3226: You can perform the compilation semantics represented by a CT with
                   3227: @code{execute}:
1.29      crook    3228: 
1.48      anton    3229: @example
                   3230: : foo2 ( n1 n2 -- n )
                   3231:    [ comp' + execute ] ;
                   3232: see foo
                   3233: @end example
1.29      crook    3234: 
1.48      anton    3235: You can compile the compilation semantics represented by a CT with
                   3236: @code{postpone,}:
1.30      anton    3237: 
1.48      anton    3238: @example
                   3239: : foo3 ( -- )
                   3240:   [ comp' + postpone, ] ;
                   3241: see foo3
                   3242: @end example
1.30      anton    3243: 
1.51      pazsan   3244: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48      anton    3245: @code{comp'} is particularly useful for words that have no
                   3246: interpretation semantics:
1.29      crook    3247: 
1.30      anton    3248: @example
1.48      anton    3249: ' if
1.60      anton    3250: comp' if .s 2drop
1.30      anton    3251: @end example
                   3252: 
1.66      anton    3253: Reference: @ref{Tokens for Words}.
                   3254: 
1.29      crook    3255: 
1.48      anton    3256: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
                   3257: @section Wordlists and Search Order
1.66      anton    3258: @cindex wordlists tutorial
                   3259: @cindex search order, tutorial
1.48      anton    3260: 
                   3261: The dictionary is not just a memory area that allows you to allocate
                   3262: memory with @code{allot}, it also contains the Forth words, arranged in
                   3263: several wordlists.  When searching for a word in a wordlist,
                   3264: conceptually you start searching at the youngest and proceed towards
                   3265: older words (in reality most systems nowadays use hash-tables); i.e., if
                   3266: you define a word with the same name as an older word, the new word
                   3267: shadows the older word.
                   3268: 
                   3269: Which wordlists are searched in which order is determined by the search
                   3270: order.  You can display the search order with @code{order}.  It displays
                   3271: first the search order, starting with the wordlist searched first, then
                   3272: it displays the wordlist that will contain newly defined words.
1.21      crook    3273: 
1.48      anton    3274: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21      crook    3275: 
1.48      anton    3276: @example
                   3277: wordlist constant mywords
                   3278: @end example
1.21      crook    3279: 
1.48      anton    3280: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
                   3281: defined words (the @emph{current} wordlist):
1.21      crook    3282: 
1.48      anton    3283: @example
                   3284: mywords set-current
                   3285: order
                   3286: @end example
1.26      crook    3287: 
1.48      anton    3288: Gforth does not display a name for the wordlist in @code{mywords}
                   3289: because this wordlist was created anonymously with @code{wordlist}.
1.21      crook    3290: 
1.48      anton    3291: You can get the current wordlist with @code{get-current ( -- wid)}.  If
                   3292: you want to put something into a specific wordlist without overall
                   3293: effect on the current wordlist, this typically looks like this:
1.21      crook    3294: 
1.48      anton    3295: @example
                   3296: get-current mywords set-current ( wid )
                   3297: create someword
                   3298: ( wid ) set-current
                   3299: @end example
1.21      crook    3300: 
1.48      anton    3301: You can write the search order with @code{set-order ( wid1 .. widn n --
                   3302: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
                   3303: searched wordlist is topmost.
1.21      crook    3304: 
1.48      anton    3305: @example
                   3306: get-order mywords swap 1+ set-order
                   3307: order
                   3308: @end example
1.21      crook    3309: 
1.48      anton    3310: Yes, the order of wordlists in the output of @code{order} is reversed
                   3311: from stack comments and the output of @code{.s} and thus unintuitive.
1.21      crook    3312: 
1.141     anton    3313: @quotation Assignment
1.48      anton    3314: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
                   3315: wordlist to the search order.  Define @code{previous ( -- )}, which
                   3316: removes the first searched wordlist from the search order.  Experiment
                   3317: with boundary conditions (you will see some crashes or situations that
                   3318: are hard or impossible to leave).
1.141     anton    3319: @end quotation
1.21      crook    3320: 
1.48      anton    3321: The search order is a powerful foundation for providing features similar
                   3322: to Modula-2 modules and C++ namespaces.  However, trying to modularize
                   3323: programs in this way has disadvantages for debugging and reuse/factoring
                   3324: that overcome the advantages in my experience (I don't do huge projects,
1.55      anton    3325: though).  These disadvantages are not so clear in other
1.82      anton    3326: languages/programming environments, because these languages are not so
1.48      anton    3327: strong in debugging and reuse.
1.21      crook    3328: 
1.66      anton    3329: @c !! example
                   3330: 
                   3331: Reference: @ref{Word Lists}.
1.21      crook    3332: 
1.29      crook    3333: @c ******************************************************************
1.48      anton    3334: @node Introduction, Words, Tutorial, Top
1.29      crook    3335: @comment node-name,     next,           previous, up
                   3336: @chapter An Introduction to ANS Forth
                   3337: @cindex Forth - an introduction
1.21      crook    3338: 
1.83      anton    3339: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
                   3340: that it is slower-paced in its examples, but uses them to dive deep into
                   3341: explaining Forth internals (not covered by the Tutorial).  Apart from
                   3342: that, this chapter covers far less material.  It is suitable for reading
                   3343: without using a computer.
                   3344: 
1.29      crook    3345: The primary purpose of this manual is to document Gforth. However, since
                   3346: Forth is not a widely-known language and there is a lack of up-to-date
                   3347: teaching material, it seems worthwhile to provide some introductory
1.49      anton    3348: material.  For other sources of Forth-related
                   3349: information, see @ref{Forth-related information}.
1.21      crook    3350: 
1.29      crook    3351: The examples in this section should work on any ANS Forth; the
                   3352: output shown was produced using Gforth. Each example attempts to
                   3353: reproduce the exact output that Gforth produces. If you try out the
                   3354: examples (and you should), what you should type is shown @kbd{like this}
                   3355: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    3356: that, where the example shows @key{RET} it means that you should
1.29      crook    3357: press the ``carriage return'' key. Unfortunately, some output formats for
                   3358: this manual cannot show the difference between @kbd{this} and
                   3359: @code{this} which will make trying out the examples harder (but not
                   3360: impossible).
1.21      crook    3361: 
1.29      crook    3362: Forth is an unusual language. It provides an interactive development
                   3363: environment which includes both an interpreter and compiler. Forth
                   3364: programming style encourages you to break a problem down into many
                   3365: @cindex factoring
                   3366: small fragments (@dfn{factoring}), and then to develop and test each
                   3367: fragment interactively. Forth advocates assert that breaking the
                   3368: edit-compile-test cycle used by conventional programming languages can
                   3369: lead to great productivity improvements.
1.21      crook    3370: 
1.29      crook    3371: @menu
1.67      anton    3372: * Introducing the Text Interpreter::  
                   3373: * Stacks and Postfix notation::  
                   3374: * Your first definition::       
                   3375: * How does that work?::         
                   3376: * Forth is written in Forth::   
                   3377: * Review - elements of a Forth system::  
                   3378: * Where to go next::            
                   3379: * Exercises::                   
1.29      crook    3380: @end menu
1.21      crook    3381: 
1.29      crook    3382: @comment ----------------------------------------------
                   3383: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   3384: @section Introducing the Text Interpreter
                   3385: @cindex text interpreter
                   3386: @cindex outer interpreter
1.21      crook    3387: 
1.30      anton    3388: @c IMO this is too detailed and the pace is too slow for
                   3389: @c an introduction.  If you know German, take a look at
                   3390: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   3391: @c to see how I do it - anton 
                   3392: 
1.44      crook    3393: @c nac-> Where I have accepted your comments 100% and modified the text
                   3394: @c accordingly, I have deleted your comments. Elsewhere I have added a
                   3395: @c response like this to attempt to rationalise what I have done. Of
                   3396: @c course, this is a very clumsy mechanism for something that would be
                   3397: @c done far more efficiently over a beer. Please delete any dialogue
                   3398: @c you consider closed.
                   3399: 
1.29      crook    3400: When you invoke the Forth image, you will see a startup banner printed
                   3401: and nothing else (if you have Gforth installed on your system, try
1.30      anton    3402: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    3403: its command line interpreter, which is called the @dfn{Text Interpreter}
                   3404: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.49      anton    3405: about the text interpreter as you read through this chapter, for more
                   3406: detail @pxref{The Text Interpreter}).
1.21      crook    3407: 
1.29      crook    3408: Although it's not obvious, Forth is actually waiting for your
1.30      anton    3409: input. Type a number and press the @key{RET} key:
1.21      crook    3410: 
1.26      crook    3411: @example
1.30      anton    3412: @kbd{45@key{RET}}  ok
1.26      crook    3413: @end example
1.21      crook    3414: 
1.29      crook    3415: Rather than give you a prompt to invite you to input something, the text
                   3416: interpreter prints a status message @i{after} it has processed a line
                   3417: of input. The status message in this case (``@code{ ok}'' followed by
                   3418: carriage-return) indicates that the text interpreter was able to process
                   3419: all of your input successfully. Now type something illegal:
                   3420: 
                   3421: @example
1.30      anton    3422: @kbd{qwer341@key{RET}}
1.134     anton    3423: *the terminal*:2: Undefined word
                   3424: >>>qwer341<<<
                   3425: Backtrace:
                   3426: $2A95B42A20 throw 
                   3427: $2A95B57FB8 no.extensions 
1.29      crook    3428: @end example
1.23      crook    3429: 
1.134     anton    3430: The exact text, other than the ``Undefined word'' may differ slightly
                   3431: on your system, but the effect is the same; when the text interpreter
1.29      crook    3432: detects an error, it discards any remaining text on a line, resets
1.134     anton    3433: certain internal state and prints an error message. For a detailed
                   3434: description of error messages see @ref{Error messages}.
1.23      crook    3435: 
1.29      crook    3436: The text interpreter waits for you to press carriage-return, and then
                   3437: processes your input line. Starting at the beginning of the line, it
                   3438: breaks the line into groups of characters separated by spaces. For each
                   3439: group of characters in turn, it makes two attempts to do something:
1.23      crook    3440: 
1.29      crook    3441: @itemize @bullet
                   3442: @item
1.44      crook    3443: @cindex name dictionary
1.29      crook    3444: It tries to treat it as a command. It does this by searching a @dfn{name
                   3445: dictionary}. If the group of characters matches an entry in the name
                   3446: dictionary, the name dictionary provides the text interpreter with
                   3447: information that allows the text interpreter perform some actions. In
                   3448: Forth jargon, we say that the group
                   3449: @cindex word
                   3450: @cindex definition
                   3451: @cindex execution token
                   3452: @cindex xt
                   3453: of characters names a @dfn{word}, that the dictionary search returns an
                   3454: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   3455: word, and that the text interpreter executes the xt. Often, the terms
                   3456: @dfn{word} and @dfn{definition} are used interchangeably.
                   3457: @item
                   3458: If the text interpreter fails to find a match in the name dictionary, it
                   3459: tries to treat the group of characters as a number in the current number
                   3460: base (when you start up Forth, the current number base is base 10). If
                   3461: the group of characters legitimately represents a number, the text
                   3462: interpreter pushes the number onto a stack (we'll learn more about that
                   3463: in the next section).
                   3464: @end itemize
1.23      crook    3465: 
1.29      crook    3466: If the text interpreter is unable to do either of these things with any
                   3467: group of characters, it discards the group of characters and the rest of
                   3468: the line, then prints an error message. If the text interpreter reaches
                   3469: the end of the line without error, it prints the status message ``@code{ ok}''
                   3470: followed by carriage-return.
1.21      crook    3471: 
1.29      crook    3472: This is the simplest command we can give to the text interpreter:
1.23      crook    3473: 
                   3474: @example
1.30      anton    3475: @key{RET}  ok
1.23      crook    3476: @end example
1.21      crook    3477: 
1.29      crook    3478: The text interpreter did everything we asked it to do (nothing) without
                   3479: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   3480: command:
1.21      crook    3481: 
1.23      crook    3482: @example
1.30      anton    3483: @kbd{12 dup fred dup@key{RET}}
1.134     anton    3484: *the terminal*:3: Undefined word
                   3485: 12 dup >>>fred<<< dup
                   3486: Backtrace:
                   3487: $2A95B42A20 throw 
                   3488: $2A95B57FB8 no.extensions 
1.23      crook    3489: @end example
1.21      crook    3490: 
1.29      crook    3491: When you press the carriage-return key, the text interpreter starts to
                   3492: work its way along the line:
1.21      crook    3493: 
1.29      crook    3494: @itemize @bullet
                   3495: @item
                   3496: When it gets to the space after the @code{2}, it takes the group of
                   3497: characters @code{12} and looks them up in the name
                   3498: dictionary@footnote{We can't tell if it found them or not, but assume
                   3499: for now that it did not}. There is no match for this group of characters
                   3500: in the name dictionary, so it tries to treat them as a number. It is
                   3501: able to do this successfully, so it puts the number, 12, ``on the stack''
                   3502: (whatever that means).
                   3503: @item
                   3504: The text interpreter resumes scanning the line and gets the next group
                   3505: of characters, @code{dup}. It looks it up in the name dictionary and
                   3506: (you'll have to take my word for this) finds it, and executes the word
                   3507: @code{dup} (whatever that means).
                   3508: @item
                   3509: Once again, the text interpreter resumes scanning the line and gets the
                   3510: group of characters @code{fred}. It looks them up in the name
                   3511: dictionary, but can't find them. It tries to treat them as a number, but
                   3512: they don't represent any legal number.
                   3513: @end itemize
1.21      crook    3514: 
1.29      crook    3515: At this point, the text interpreter gives up and prints an error
                   3516: message. The error message shows exactly how far the text interpreter
                   3517: got in processing the line. In particular, it shows that the text
                   3518: interpreter made no attempt to do anything with the final character
                   3519: group, @code{dup}, even though we have good reason to believe that the
                   3520: text interpreter would have no problem looking that word up and
                   3521: executing it a second time.
1.21      crook    3522: 
                   3523: 
1.29      crook    3524: @comment ----------------------------------------------
                   3525: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   3526: @section Stacks, postfix notation and parameter passing
                   3527: @cindex text interpreter
                   3528: @cindex outer interpreter
1.21      crook    3529: 
1.29      crook    3530: In procedural programming languages (like C and Pascal), the
                   3531: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   3532: functions or procedures are called with @dfn{explicit parameters}. For
                   3533: example, in C we might write:
1.21      crook    3534: 
1.23      crook    3535: @example
1.29      crook    3536: total = total + new_volume(length,height,depth);
1.23      crook    3537: @end example
1.21      crook    3538: 
1.23      crook    3539: @noindent
1.29      crook    3540: where new_volume is a function-call to another piece of code, and total,
                   3541: length, height and depth are all variables. length, height and depth are
                   3542: parameters to the function-call.
1.21      crook    3543: 
1.29      crook    3544: In Forth, the equivalent of the function or procedure is the
                   3545: @dfn{definition} and parameters are implicitly passed between
                   3546: definitions using a shared stack that is visible to the
                   3547: programmer. Although Forth does support variables, the existence of the
                   3548: stack means that they are used far less often than in most other
                   3549: programming languages. When the text interpreter encounters a number, it
                   3550: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    3551: actual number is implementation-dependent ...) and the particular stack
1.29      crook    3552: used for any operation is implied unambiguously by the operation being
                   3553: performed. The stack used for all integer operations is called the @dfn{data
                   3554: stack} and, since this is the stack used most commonly, references to
                   3555: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    3556: 
1.29      crook    3557: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    3558: 
1.23      crook    3559: @example
1.30      anton    3560: @kbd{1 2 3@key{RET}}  ok
1.23      crook    3561: @end example
1.21      crook    3562: 
1.29      crook    3563: Then this instructs the text interpreter to placed three numbers on the
                   3564: (data) stack. An analogy for the behaviour of the stack is to take a
                   3565: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   3566: the table. The 3 was the last card onto the pile (``last-in'') and if
                   3567: you take a card off the pile then, unless you're prepared to fiddle a
                   3568: bit, the card that you take off will be the 3 (``first-out''). The
                   3569: number that will be first-out of the stack is called the @dfn{top of
                   3570: stack}, which
                   3571: @cindex TOS definition
                   3572: is often abbreviated to @dfn{TOS}.
1.21      crook    3573: 
1.29      crook    3574: To understand how parameters are passed in Forth, consider the
                   3575: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   3576: be surprised to learn that this definition performs addition. More
                   3577: precisely, it adds two number together and produces a result. Where does
                   3578: it get the two numbers from? It takes the top two numbers off the
                   3579: stack. Where does it place the result? On the stack. You can act-out the
                   3580: behaviour of @code{+} with your playing cards like this:
1.21      crook    3581: 
                   3582: @itemize @bullet
                   3583: @item
1.29      crook    3584: Pick up two cards from the stack on the table
1.21      crook    3585: @item
1.29      crook    3586: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   3587: numbers''
1.21      crook    3588: @item
1.29      crook    3589: Decide that the answer is 5
1.21      crook    3590: @item
1.29      crook    3591: Shuffle the two cards back into the pack and find a 5
1.21      crook    3592: @item
1.29      crook    3593: Put a 5 on the remaining ace that's on the table.
1.21      crook    3594: @end itemize
                   3595: 
1.29      crook    3596: If you don't have a pack of cards handy but you do have Forth running,
                   3597: you can use the definition @code{.s} to show the current state of the stack,
                   3598: without affecting the stack. Type:
1.21      crook    3599: 
                   3600: @example
1.124     anton    3601: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30      anton    3602: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    3603: @end example
                   3604: 
1.124     anton    3605: The text interpreter looks up the word @code{clearstacks} and executes
                   3606: it; it tidies up the stacks and removes any entries that may have been
1.29      crook    3607: left on it by earlier examples. The text interpreter pushes each of the
                   3608: three numbers in turn onto the stack. Finally, the text interpreter
                   3609: looks up the word @code{.s} and executes it. The effect of executing
                   3610: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   3611: followed by a list of all the items on the stack; the item on the far
                   3612: right-hand side is the TOS.
1.21      crook    3613: 
1.29      crook    3614: You can now type:
1.21      crook    3615: 
1.29      crook    3616: @example
1.30      anton    3617: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    3618: @end example
1.21      crook    3619: 
1.29      crook    3620: @noindent
                   3621: which is correct; there are now 2 items on the stack and the result of
                   3622: the addition is 5.
1.23      crook    3623: 
1.29      crook    3624: If you're playing with cards, try doing a second addition: pick up the
                   3625: two cards, work out that their sum is 6, shuffle them into the pack,
                   3626: look for a 6 and place that on the table. You now have just one item on
                   3627: the stack. What happens if you try to do a third addition? Pick up the
                   3628: first card, pick up the second card -- ah! There is no second card. This
                   3629: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95      anton    3630: do the same thing with Forth it often reports an error (probably a Stack
1.29      crook    3631: Underflow or an Invalid Memory Address error).
1.23      crook    3632: 
1.29      crook    3633: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   3634: which simply accepts that there is a finite amount of storage space
                   3635: reserved for the stack. To stretch the playing card analogy, if you had
                   3636: enough packs of cards and you piled the cards up on the table, you would
                   3637: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   3638: allows you to set the maximum size of the stacks. In general, the only
                   3639: time that you will get a stack overflow is because a definition has a
                   3640: bug in it and is generating data on the stack uncontrollably.
1.23      crook    3641: 
1.29      crook    3642: There's one final use for the playing card analogy. If you model your
                   3643: stack using a pack of playing cards, the maximum number of items on
                   3644: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   3645: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   3646: possible numbers are positive integer numbers 1 through 13; you can't
                   3647: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   3648: think about some of the cards, you can accommodate different
                   3649: numbers. For example, you could think of the Jack as representing 0,
                   3650: the Queen as representing -1 and the King as representing -2. Your
1.45      crook    3651: @i{range} remains unchanged (you can still only represent a total of 13
1.29      crook    3652: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    3653: 
1.29      crook    3654: In that analogy, the limit was the amount of information that a single
                   3655: stack entry could hold, and Forth has a similar limit. In Forth, the
                   3656: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   3657: implementation dependent and affects the maximum value that a stack
                   3658: entry can hold. A Standard Forth provides a cell size of at least
                   3659: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    3660: 
1.29      crook    3661: Forth does not do any type checking for you, so you are free to
                   3662: manipulate and combine stack items in any way you wish. A convenient way
                   3663: of treating stack items is as 2's complement signed integers, and that
                   3664: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    3665: 
1.29      crook    3666: @example
1.30      anton    3667: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    3668: @end example
1.21      crook    3669: 
1.29      crook    3670: If you use numbers and definitions like @code{+} in order to turn Forth
                   3671: into a great big pocket calculator, you will realise that it's rather
                   3672: different from a normal calculator. Rather than typing 2 + 3 = you had
                   3673: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   3674: result). The terminology used to describe this difference is to say that
                   3675: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   3676: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   3677: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    3678: 
1.29      crook    3679: Whilst postfix notation might look confusing to begin with, it has
                   3680: several important advantages:
1.21      crook    3681: 
1.23      crook    3682: @itemize @bullet
                   3683: @item
1.29      crook    3684: it is unambiguous
1.23      crook    3685: @item
1.29      crook    3686: it is more concise
1.23      crook    3687: @item
1.29      crook    3688: it fits naturally with a stack-based system
1.23      crook    3689: @end itemize
1.21      crook    3690: 
1.29      crook    3691: To examine these claims in more detail, consider these sums:
1.21      crook    3692: 
1.29      crook    3693: @example
                   3694: 6 + 5 * 4 =
                   3695: 4 * 5 + 6 =
                   3696: @end example
1.21      crook    3697: 
1.29      crook    3698: If you're just learning maths or your maths is very rusty, you will
                   3699: probably come up with the answer 44 for the first and 26 for the
                   3700: second. If you are a bit of a whizz at maths you will remember the
                   3701: @i{convention} that multiplication takes precendence over addition, and
                   3702: you'd come up with the answer 26 both times. To explain the answer 26
                   3703: to someone who got the answer 44, you'd probably rewrite the first sum
                   3704: like this:
1.21      crook    3705: 
1.29      crook    3706: @example
                   3707: 6 + (5 * 4) =
                   3708: @end example
1.21      crook    3709: 
1.29      crook    3710: If what you really wanted was to perform the addition before the
                   3711: multiplication, you would have to use parentheses to force it.
1.21      crook    3712: 
1.29      crook    3713: If you did the first two sums on a pocket calculator you would probably
                   3714: get the right answers, unless you were very cautious and entered them using
                   3715: these keystroke sequences:
1.21      crook    3716: 
1.29      crook    3717: 6 + 5 = * 4 =
                   3718: 4 * 5 = + 6 =
1.21      crook    3719: 
1.29      crook    3720: Postfix notation is unambiguous because the order that the operators
                   3721: are applied is always explicit; that also means that parentheses are
                   3722: never required. The operators are @i{active} (the act of quoting the
                   3723: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    3724: 
1.29      crook    3725: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   3726: equivalent ways:
1.26      crook    3727: 
                   3728: @example
1.29      crook    3729: 6 5 4 * +      or:
                   3730: 5 4 * 6 +
1.26      crook    3731: @end example
1.23      crook    3732: 
1.29      crook    3733: An important thing that you should notice about this notation is that
                   3734: the @i{order} of the numbers does not change; if you want to subtract
                   3735: 2 from 10 you type @code{10 2 -}.
1.1       anton    3736: 
1.29      crook    3737: The reason that Forth uses postfix notation is very simple to explain: it
                   3738: makes the implementation extremely simple, and it follows naturally from
                   3739: using the stack as a mechanism for passing parameters. Another way of
                   3740: thinking about this is to realise that all Forth definitions are
                   3741: @i{active}; they execute as they are encountered by the text
                   3742: interpreter. The result of this is that the syntax of Forth is trivially
                   3743: simple.
1.1       anton    3744: 
                   3745: 
                   3746: 
1.29      crook    3747: @comment ----------------------------------------------
                   3748: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   3749: @section Your first Forth definition
                   3750: @cindex first definition
1.1       anton    3751: 
1.29      crook    3752: Until now, the examples we've seen have been trivial; we've just been
                   3753: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   3754: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   3755: again@footnote{That's not quite true. If you press the up-arrow key on
                   3756: your keyboard you should be able to scroll back to any earlier command,
                   3757: edit it and re-enter it.} In this section we'll see how to add new
                   3758: words to Forth's vocabulary.
1.1       anton    3759: 
1.29      crook    3760: The easiest way to create a new word is to use a @dfn{colon
                   3761: definition}. We'll define a few and try them out before worrying too
                   3762: much about how they work. Try typing in these examples; be careful to
                   3763: copy the spaces accurately:
1.1       anton    3764: 
1.29      crook    3765: @example
                   3766: : add-two 2 + . ;
                   3767: : greet ." Hello and welcome" ;
                   3768: : demo 5 add-two ;
                   3769: @end example
1.1       anton    3770: 
1.29      crook    3771: @noindent
                   3772: Now try them out:
1.1       anton    3773: 
1.29      crook    3774: @example
1.30      anton    3775: @kbd{greet@key{RET}} Hello and welcome  ok
                   3776: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   3777: @kbd{4 add-two@key{RET}} 6  ok
                   3778: @kbd{demo@key{RET}} 7  ok
                   3779: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    3780: @end example
1.1       anton    3781: 
1.29      crook    3782: The first new thing that we've introduced here is the pair of words
                   3783: @code{:} and @code{;}. These are used to start and terminate a new
                   3784: definition, respectively. The first word after the @code{:} is the name
                   3785: for the new definition.
1.1       anton    3786: 
1.29      crook    3787: As you can see from the examples, a definition is built up of words that
                   3788: have already been defined; Forth makes no distinction between
                   3789: definitions that existed when you started the system up, and those that
                   3790: you define yourself.
1.1       anton    3791: 
1.29      crook    3792: The examples also introduce the words @code{.} (dot), @code{."}
                   3793: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   3794: the stack and displays it. It's like @code{.s} except that it only
                   3795: displays the top item of the stack and it is destructive; after it has
                   3796: executed, the number is no longer on the stack. There is always one
                   3797: space printed after the number, and no spaces before it. Dot-quote
                   3798: defines a string (a sequence of characters) that will be printed when
                   3799: the word is executed. The string can contain any printable characters
                   3800: except @code{"}. A @code{"} has a special function; it is not a Forth
                   3801: word but it acts as a delimiter (the way that delimiters work is
                   3802: described in the next section). Finally, @code{dup} duplicates the value
                   3803: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    3804: 
1.29      crook    3805: We already know that the text interpreter searches through the
                   3806: dictionary to locate names. If you've followed the examples earlier, you
                   3807: will already have a definition called @code{add-two}. Lets try modifying
                   3808: it by typing in a new definition:
1.1       anton    3809: 
1.29      crook    3810: @example
1.30      anton    3811: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    3812: @end example
1.5       anton    3813: 
1.29      crook    3814: Forth recognised that we were defining a word that already exists, and
                   3815: printed a message to warn us of that fact. Let's try out the new
                   3816: definition:
1.5       anton    3817: 
1.29      crook    3818: @example
1.30      anton    3819: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    3820: @end example
1.1       anton    3821: 
1.29      crook    3822: @noindent
                   3823: All that we've actually done here, though, is to create a new
                   3824: definition, with a particular name. The fact that there was already a
                   3825: definition with the same name did not make any difference to the way
                   3826: that the new definition was created (except that Forth printed a warning
                   3827: message). The old definition of add-two still exists (try @code{demo}
                   3828: again to see that this is true). Any new definition will use the new
                   3829: definition of @code{add-two}, but old definitions continue to use the
                   3830: version that already existed at the time that they were @code{compiled}.
1.1       anton    3831: 
1.29      crook    3832: Before you go on to the next section, try defining and redefining some
                   3833: words of your own.
1.1       anton    3834: 
1.29      crook    3835: @comment ----------------------------------------------
                   3836: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   3837: @section How does that work?
                   3838: @cindex parsing words
1.1       anton    3839: 
1.30      anton    3840: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   3841: 
                   3842: @c Is it a good idea to talk about the interpretation semantics of a
                   3843: @c number? We don't have an xt to go along with it. - anton
                   3844: 
                   3845: @c Now that I have eliminated execution semantics, I wonder if it would not
                   3846: @c be better to keep them (or add run-time semantics), to make it easier to
                   3847: @c explain what compilation semantics usually does. - anton
                   3848: 
1.44      crook    3849: @c nac-> I removed the term ``default compilation sematics'' from the
                   3850: @c introductory chapter. Removing ``execution semantics'' was making
                   3851: @c everything simpler to explain, then I think the use of this term made
                   3852: @c everything more complex again. I replaced it with ``default
                   3853: @c semantics'' (which is used elsewhere in the manual) by which I mean
                   3854: @c ``a definition that has neither the immediate nor the compile-only
1.83      anton    3855: @c flag set''.
                   3856: 
                   3857: @c anton: I have eliminated default semantics (except in one place where it
                   3858: @c means "default interpretation and compilation semantics"), because it
                   3859: @c makes no sense in the presence of combined words.  I reverted to
                   3860: @c "execution semantics" where necessary.
                   3861: 
                   3862: @c nac-> I reworded big chunks of the ``how does that work''
1.44      crook    3863: @c section (and, unusually for me, I think I even made it shorter!).  See
                   3864: @c what you think -- I know I have not addressed your primary concern
                   3865: @c that it is too heavy-going for an introduction. From what I understood
                   3866: @c of your course notes it looks as though they might be a good framework. 
                   3867: @c Things that I've tried to capture here are some things that came as a
                   3868: @c great revelation here when I first understood them. Also, I like the
                   3869: @c fact that a very simple code example shows up almost all of the issues
                   3870: @c that you need to understand to see how Forth works. That's unique and
                   3871: @c worthwhile to emphasise.
                   3872: 
1.83      anton    3873: @c anton: I think it's a good idea to present the details, especially those
                   3874: @c that you found to be a revelation, and probably the tutorial tries to be
                   3875: @c too superficial and does not get some of the things across that make
                   3876: @c Forth special.  I do believe that most of the time these things should
                   3877: @c be discussed at the end of a section or in separate sections instead of
                   3878: @c in the middle of a section (e.g., the stuff you added in "User-defined
                   3879: @c defining words" leads in a completely different direction from the rest
                   3880: @c of the section).
                   3881: 
1.29      crook    3882: Now we're going to take another look at the definition of @code{add-two}
                   3883: from the previous section. From our knowledge of the way that the text
                   3884: interpreter works, we would have expected this result when we tried to
                   3885: define @code{add-two}:
1.21      crook    3886: 
1.29      crook    3887: @example
1.44      crook    3888: @kbd{: add-two 2 + . ;@key{RET}}
1.134     anton    3889: *the terminal*:4: Undefined word
                   3890: : >>>add-two<<< 2 + . ;
1.29      crook    3891: @end example
1.28      crook    3892: 
1.29      crook    3893: The reason that this didn't happen is bound up in the way that @code{:}
                   3894: works. The word @code{:} does two special things. The first special
                   3895: thing that it does prevents the text interpreter from ever seeing the
                   3896: characters @code{add-two}. The text interpreter uses a variable called
                   3897: @cindex modifying >IN
1.44      crook    3898: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29      crook    3899: input line. When it encounters the word @code{:} it behaves in exactly
                   3900: the same way as it does for any other word; it looks it up in the name
                   3901: dictionary, finds its xt and executes it. When @code{:} executes, it
                   3902: looks at the input buffer, finds the word @code{add-two} and advances the
                   3903: value of @code{>IN} to point past it. It then does some other stuff
                   3904: associated with creating the new definition (including creating an entry
                   3905: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   3906: completes, control returns to the text interpreter, which is oblivious
                   3907: to the fact that it has been tricked into ignoring part of the input
                   3908: line.
1.21      crook    3909: 
1.29      crook    3910: @cindex parsing words
                   3911: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   3912: prevent the text interpreter from acting on the whole of the input line
                   3913: -- are called @dfn{parsing words}.
1.21      crook    3914: 
1.29      crook    3915: @cindex @code{state} - effect on the text interpreter
                   3916: @cindex text interpreter - effect of state
                   3917: The second special thing that @code{:} does is change the value of a
                   3918: variable called @code{state}, which affects the way that the text
                   3919: interpreter behaves. When Gforth starts up, @code{state} has the value
                   3920: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   3921: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44      crook    3922: the text interpreter is said to be @dfn{compiling}.
                   3923: 
                   3924: In this example, the text interpreter is compiling when it processes the
                   3925: string ``@code{2 + . ;}''. It still breaks the string down into
                   3926: character sequences in the same way. However, instead of pushing the
                   3927: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
                   3928: into the definition of @code{add-two} that will make the number @code{2} get
                   3929: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
                   3930: the behaviours of @code{+} and @code{.} are also compiled into the
                   3931: definition.
                   3932: 
                   3933: One category of words don't get compiled. These so-called @dfn{immediate
                   3934: words} get executed (performed @i{now}) regardless of whether the text
                   3935: interpreter is interpreting or compiling. The word @code{;} is an
                   3936: immediate word. Rather than being compiled into the definition, it
                   3937: executes. Its effect is to terminate the current definition, which
                   3938: includes changing the value of @code{state} back to 0.
                   3939: 
                   3940: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
                   3941: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
                   3942: definition.
1.28      crook    3943: 
1.30      anton    3944: In Forth, every word or number can be described in terms of two
1.29      crook    3945: properties:
1.28      crook    3946: 
                   3947: @itemize @bullet
                   3948: @item
1.29      crook    3949: @cindex interpretation semantics
1.44      crook    3950: Its @dfn{interpretation semantics} describe how it will behave when the
                   3951: text interpreter encounters it in @dfn{interpret} state. The
                   3952: interpretation semantics of a word are represented by an @dfn{execution
                   3953: token}.
1.28      crook    3954: @item
1.29      crook    3955: @cindex compilation semantics
1.44      crook    3956: Its @dfn{compilation semantics} describe how it will behave when the
                   3957: text interpreter encounters it in @dfn{compile} state. The compilation
                   3958: semantics of a word are represented in an implementation-dependent way;
                   3959: Gforth uses a @dfn{compilation token}.
1.29      crook    3960: @end itemize
                   3961: 
                   3962: @noindent
                   3963: Numbers are always treated in a fixed way:
                   3964: 
                   3965: @itemize @bullet
1.28      crook    3966: @item
1.44      crook    3967: When the number is @dfn{interpreted}, its behaviour is to push the
                   3968: number onto the stack.
1.28      crook    3969: @item
1.30      anton    3970: When the number is @dfn{compiled}, a piece of code is appended to the
                   3971: current definition that pushes the number when it runs. (In other words,
                   3972: the compilation semantics of a number are to postpone its interpretation
                   3973: semantics until the run-time of the definition that it is being compiled
                   3974: into.)
1.29      crook    3975: @end itemize
                   3976: 
1.44      crook    3977: Words don't behave in such a regular way, but most have @i{default
                   3978: semantics} which means that they behave like this:
1.29      crook    3979: 
                   3980: @itemize @bullet
1.28      crook    3981: @item
1.30      anton    3982: The @dfn{interpretation semantics} of the word are to do something useful.
                   3983: @item
1.29      crook    3984: The @dfn{compilation semantics} of the word are to append its
1.30      anton    3985: @dfn{interpretation semantics} to the current definition (so that its
                   3986: run-time behaviour is to do something useful).
1.28      crook    3987: @end itemize
                   3988: 
1.30      anton    3989: @cindex immediate words
1.44      crook    3990: The actual behaviour of any particular word can be controlled by using
                   3991: the words @code{immediate} and @code{compile-only} when the word is
                   3992: defined. These words set flags in the name dictionary entry of the most
                   3993: recently defined word, and these flags are retrieved by the text
                   3994: interpreter when it finds the word in the name dictionary.
                   3995: 
                   3996: A word that is marked as @dfn{immediate} has compilation semantics that
                   3997: are identical to its interpretation semantics. In other words, it
                   3998: behaves like this:
1.29      crook    3999: 
                   4000: @itemize @bullet
                   4001: @item
1.30      anton    4002: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    4003: @item
1.30      anton    4004: The @dfn{compilation semantics} of the word are to do something useful
                   4005: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    4006: @end itemize
1.28      crook    4007: 
1.44      crook    4008: Marking a word as @dfn{compile-only} prohibits the text interpreter from
                   4009: performing the interpretation semantics of the word directly; an attempt
                   4010: to do so will generate an error. It is never necessary to use
                   4011: @code{compile-only} (and it is not even part of ANS Forth, though it is
                   4012: provided by many implementations) but it is good etiquette to apply it
                   4013: to a word that will not behave correctly (and might have unexpected
                   4014: side-effects) in interpret state. For example, it is only legal to use
                   4015: the conditional word @code{IF} within a definition. If you forget this
                   4016: and try to use it elsewhere, the fact that (in Gforth) it is marked as
                   4017: @code{compile-only} allows the text interpreter to generate a helpful
                   4018: error message rather than subjecting you to the consequences of your
                   4019: folly.
                   4020: 
1.29      crook    4021: This example shows the difference between an immediate and a
                   4022: non-immediate word:
1.28      crook    4023: 
1.29      crook    4024: @example
                   4025: : show-state state @@ . ;
                   4026: : show-state-now show-state ; immediate
                   4027: : word1 show-state ;
                   4028: : word2 show-state-now ;
1.28      crook    4029: @end example
1.23      crook    4030: 
1.29      crook    4031: The word @code{immediate} after the definition of @code{show-state-now}
                   4032: makes that word an immediate word. These definitions introduce a new
                   4033: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   4034: variable, and leaves it on the stack. Therefore, the behaviour of
                   4035: @code{show-state} is to print a number that represents the current value
                   4036: of @code{state}.
1.28      crook    4037: 
1.29      crook    4038: When you execute @code{word1}, it prints the number 0, indicating that
                   4039: the system is interpreting. When the text interpreter compiled the
                   4040: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    4041: compilation semantics are to append its interpretation semantics to the
1.29      crook    4042: current definition. When you execute @code{word1}, it performs the
1.30      anton    4043: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    4044: (and therefore @code{show-state}) are executed, the system is
                   4045: interpreting.
1.28      crook    4046: 
1.30      anton    4047: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    4048: you should have seen the number -1 printed, followed by ``@code{
                   4049: ok}''. When the text interpreter compiled the definition of
                   4050: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    4051: whose compilation semantics are therefore to perform its interpretation
1.29      crook    4052: semantics. It is executed straight away (even before the text
                   4053: interpreter has moved on to process another group of characters; the
                   4054: @code{;} in this example). The effect of executing it are to display the
                   4055: value of @code{state} @i{at the time that the definition of}
                   4056: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   4057: system is compiling at this time. If you execute @code{word2} it does
                   4058: nothing at all.
1.28      crook    4059: 
1.29      crook    4060: @cindex @code{."}, how it works
                   4061: Before leaving the subject of immediate words, consider the behaviour of
                   4062: @code{."} in the definition of @code{greet}, in the previous
                   4063: section. This word is both a parsing word and an immediate word. Notice
                   4064: that there is a space between @code{."} and the start of the text
                   4065: @code{Hello and welcome}, but that there is no space between the last
                   4066: letter of @code{welcome} and the @code{"} character. The reason for this
                   4067: is that @code{."} is a Forth word; it must have a space after it so that
                   4068: the text interpreter can identify it. The @code{"} is not a Forth word;
                   4069: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   4070: is displayed, there is neither a space before the @code{H} nor after the
                   4071: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   4072: that @code{greet} is defined. When it executes, its behaviour is to
                   4073: search forward in the input line looking for the delimiter. When it
                   4074: finds the delimiter, it updates @code{>IN} to point past the
                   4075: delimiter. It also compiles some magic code into the definition of
                   4076: @code{greet}; the xt of a run-time routine that prints a text string. It
                   4077: compiles the string @code{Hello and welcome} into memory so that it is
                   4078: available to be printed later. When the text interpreter gains control,
                   4079: the next word it finds in the input stream is @code{;} and so it
                   4080: terminates the definition of @code{greet}.
1.28      crook    4081: 
                   4082: 
                   4083: @comment ----------------------------------------------
1.29      crook    4084: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   4085: @section Forth is written in Forth
                   4086: @cindex structure of Forth programs
                   4087: 
                   4088: When you start up a Forth compiler, a large number of definitions
                   4089: already exist. In Forth, you develop a new application using bottom-up
                   4090: programming techniques to create new definitions that are defined in
                   4091: terms of existing definitions. As you create each definition you can
                   4092: test and debug it interactively.
                   4093: 
                   4094: If you have tried out the examples in this section, you will probably
                   4095: have typed them in by hand; when you leave Gforth, your definitions will
                   4096: be lost. You can avoid this by using a text editor to enter Forth source
                   4097: code into a file, and then loading code from the file using
1.49      anton    4098: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29      crook    4099: processed by the text interpreter, just as though you had typed it in by
                   4100: hand@footnote{Actually, there are some subtle differences -- see
                   4101: @ref{The Text Interpreter}.}.
                   4102: 
                   4103: Gforth also supports the traditional Forth alternative to using text
1.49      anton    4104: files for program entry (@pxref{Blocks}).
1.28      crook    4105: 
1.29      crook    4106: In common with many, if not most, Forth compilers, most of Gforth is
                   4107: actually written in Forth. All of the @file{.fs} files in the
                   4108: installation directory@footnote{For example,
1.30      anton    4109: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    4110: study to see examples of Forth programming.
1.28      crook    4111: 
1.29      crook    4112: Gforth maintains a history file that records every line that you type to
                   4113: the text interpreter. This file is preserved between sessions, and is
                   4114: used to provide a command-line recall facility. If you enter long
                   4115: definitions by hand, you can use a text editor to paste them out of the
                   4116: history file into a Forth source file for reuse at a later time
1.49      anton    4117: (for more information @pxref{Command-line editing}).
1.28      crook    4118: 
                   4119: 
                   4120: @comment ----------------------------------------------
1.29      crook    4121: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   4122: @section Review - elements of a Forth system
                   4123: @cindex elements of a Forth system
1.28      crook    4124: 
1.29      crook    4125: To summarise this chapter:
1.28      crook    4126: 
                   4127: @itemize @bullet
                   4128: @item
1.29      crook    4129: Forth programs use @dfn{factoring} to break a problem down into small
                   4130: fragments called @dfn{words} or @dfn{definitions}.
                   4131: @item
                   4132: Forth program development is an interactive process.
                   4133: @item
                   4134: The main command loop that accepts input, and controls both
                   4135: interpretation and compilation, is called the @dfn{text interpreter}
                   4136: (also known as the @dfn{outer interpreter}).
                   4137: @item
                   4138: Forth has a very simple syntax, consisting of words and numbers
                   4139: separated by spaces or carriage-return characters. Any additional syntax
                   4140: is imposed by @dfn{parsing words}.
                   4141: @item
                   4142: Forth uses a stack to pass parameters between words. As a result, it
                   4143: uses postfix notation.
                   4144: @item
                   4145: To use a word that has previously been defined, the text interpreter
                   4146: searches for the word in the @dfn{name dictionary}.
                   4147: @item
1.30      anton    4148: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    4149: @item
1.29      crook    4150: The text interpreter uses the value of @code{state} to select between
                   4151: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   4152: semantics} of a word that it encounters.
1.28      crook    4153: @item
1.30      anton    4154: The relationship between the @dfn{interpretation semantics} and
                   4155: @dfn{compilation semantics} for a word
1.29      crook    4156: depend upon the way in which the word was defined (for example, whether
                   4157: it is an @dfn{immediate} word).
1.28      crook    4158: @item
1.29      crook    4159: Forth definitions can be implemented in Forth (called @dfn{high-level
                   4160: definitions}) or in some other way (usually a lower-level language and
                   4161: as a result often called @dfn{low-level definitions}, @dfn{code
                   4162: definitions} or @dfn{primitives}).
1.28      crook    4163: @item
1.29      crook    4164: Many Forth systems are implemented mainly in Forth.
1.28      crook    4165: @end itemize
                   4166: 
                   4167: 
1.29      crook    4168: @comment ----------------------------------------------
1.48      anton    4169: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29      crook    4170: @section Where To Go Next
                   4171: @cindex where to go next
1.28      crook    4172: 
1.29      crook    4173: Amazing as it may seem, if you have read (and understood) this far, you
                   4174: know almost all the fundamentals about the inner workings of a Forth
                   4175: system. You certainly know enough to be able to read and understand the
                   4176: rest of this manual and the ANS Forth document, to learn more about the
                   4177: facilities that Forth in general and Gforth in particular provide. Even
                   4178: scarier, you know almost enough to implement your own Forth system.
1.30      anton    4179: However, that's not a good idea just yet... better to try writing some
1.29      crook    4180: programs in Gforth.
1.28      crook    4181: 
1.29      crook    4182: Forth has such a rich vocabulary that it can be hard to know where to
                   4183: start in learning it. This section suggests a few sets of words that are
                   4184: enough to write small but useful programs. Use the word index in this
                   4185: document to learn more about each word, then try it out and try to write
                   4186: small definitions using it. Start by experimenting with these words:
1.28      crook    4187: 
                   4188: @itemize @bullet
                   4189: @item
1.29      crook    4190: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   4191: @item
                   4192: Comparison: @code{MIN MAX =}
                   4193: @item
                   4194: Logic: @code{AND OR XOR NOT}
                   4195: @item
                   4196: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    4197: @item
1.29      crook    4198: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    4199: @item
1.29      crook    4200: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    4201: @item
1.29      crook    4202: Defining words: @code{: ; CREATE}
1.28      crook    4203: @item
1.29      crook    4204: Memory allocation words: @code{ALLOT ,}
1.28      crook    4205: @item
1.29      crook    4206: Tools: @code{SEE WORDS .S MARKER}
                   4207: @end itemize
                   4208: 
                   4209: When you have mastered those, go on to:
                   4210: 
                   4211: @itemize @bullet
1.28      crook    4212: @item
1.29      crook    4213: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    4214: @item
1.29      crook    4215: Memory access: @code{@@ !}
1.28      crook    4216: @end itemize
1.23      crook    4217: 
1.29      crook    4218: When you have mastered these, there's nothing for it but to read through
                   4219: the whole of this manual and find out what you've missed.
                   4220: 
                   4221: @comment ----------------------------------------------
1.48      anton    4222: @node Exercises,  , Where to go next, Introduction
1.29      crook    4223: @section Exercises
                   4224: @cindex exercises
                   4225: 
                   4226: TODO: provide a set of programming excercises linked into the stuff done
                   4227: already and into other sections of the manual. Provide solutions to all
                   4228: the exercises in a .fs file in the distribution.
                   4229: 
                   4230: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   4231: 
                   4232: @c excercises:
                   4233: @c 1. take inches and convert to feet and inches.
                   4234: @c 2. take temperature and convert from fahrenheight to celcius;
                   4235: @c    may need to care about symmetric vs floored??
                   4236: @c 3. take input line and do character substitution
                   4237: @c    to encipher or decipher
                   4238: @c 4. as above but work on a file for in and out
                   4239: @c 5. take input line and convert to pig-latin 
                   4240: @c
                   4241: @c thing of sets of things to exercise then come up with
                   4242: @c problems that need those things.
                   4243: 
                   4244: 
1.26      crook    4245: @c ******************************************************************
1.29      crook    4246: @node Words, Error messages, Introduction, Top
1.1       anton    4247: @chapter Forth Words
1.26      crook    4248: @cindex words
1.1       anton    4249: 
                   4250: @menu
                   4251: * Notation::                    
1.65      anton    4252: * Case insensitivity::          
                   4253: * Comments::                    
                   4254: * Boolean Flags::               
1.1       anton    4255: * Arithmetic::                  
                   4256: * Stack Manipulation::          
1.5       anton    4257: * Memory::                      
1.1       anton    4258: * Control Structures::          
                   4259: * Defining Words::              
1.65      anton    4260: * Interpretation and Compilation Semantics::  
1.47      crook    4261: * Tokens for Words::            
1.81      anton    4262: * Compiling words::             
1.65      anton    4263: * The Text Interpreter::        
1.111     anton    4264: * The Input Stream::            
1.65      anton    4265: * Word Lists::                  
                   4266: * Environmental Queries::       
1.12      anton    4267: * Files::                       
                   4268: * Blocks::                      
                   4269: * Other I/O::                   
1.121     anton    4270: * OS command line arguments::   
1.78      anton    4271: * Locals::                      
                   4272: * Structures::                  
                   4273: * Object-oriented Forth::       
1.12      anton    4274: * Programming Tools::           
1.150     anton    4275: * C Interface::                 
1.12      anton    4276: * Assembler and Code Words::    
                   4277: * Threading Words::             
1.65      anton    4278: * Passing Commands to the OS::  
                   4279: * Keeping track of Time::       
                   4280: * Miscellaneous Words::         
1.1       anton    4281: @end menu
                   4282: 
1.65      anton    4283: @node Notation, Case insensitivity, Words, Words
1.1       anton    4284: @section Notation
                   4285: @cindex notation of glossary entries
                   4286: @cindex format of glossary entries
                   4287: @cindex glossary notation format
                   4288: @cindex word glossary entry format
                   4289: 
                   4290: The Forth words are described in this section in the glossary notation
1.67      anton    4291: that has become a de-facto standard for Forth texts:
1.1       anton    4292: 
                   4293: @format
1.29      crook    4294: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    4295: @end format
1.29      crook    4296: @i{Description}
1.1       anton    4297: 
                   4298: @table @var
                   4299: @item word
1.28      crook    4300: The name of the word.
1.1       anton    4301: 
                   4302: @item Stack effect
                   4303: @cindex stack effect
1.29      crook    4304: The stack effect is written in the notation @code{@i{before} --
                   4305: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    4306: stack entries before and after the execution of the word. The rest of
                   4307: the stack is not touched by the word. The top of stack is rightmost,
                   4308: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   4309: uses a separate floating point stack, but a unified stack
1.29      crook    4310: notation. Also, return stack effects are not shown in @i{stack
                   4311: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    4312: the type and/or the function of the item. See below for a discussion of
                   4313: the types.
                   4314: 
                   4315: All words have two stack effects: A compile-time stack effect and a
                   4316: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    4317: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    4318: this standard behaviour, or the word does other unusual things at
                   4319: compile time, both stack effects are shown; otherwise only the run-time
                   4320: stack effect is shown.
                   4321: 
                   4322: @cindex pronounciation of words
                   4323: @item pronunciation
                   4324: How the word is pronounced.
                   4325: 
                   4326: @cindex wordset
1.67      anton    4327: @cindex environment wordset
1.1       anton    4328: @item wordset
1.21      crook    4329: The ANS Forth standard is divided into several word sets. A standard
                   4330: system need not support all of them. Therefore, in theory, the fewer
                   4331: word sets your program uses the more portable it will be. However, we
                   4332: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    4333: all word sets. Words that are not defined in ANS Forth have
1.21      crook    4334: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    4335: describes words that will work in future releases of Gforth;
                   4336: @code{gforth-internal} words are more volatile. Environmental query
                   4337: strings are also displayed like words; you can recognize them by the
1.21      crook    4338: @code{environment} in the word set field.
1.1       anton    4339: 
                   4340: @item Description
                   4341: A description of the behaviour of the word.
                   4342: @end table
                   4343: 
                   4344: @cindex types of stack items
                   4345: @cindex stack item types
                   4346: The type of a stack item is specified by the character(s) the name
                   4347: starts with:
                   4348: 
                   4349: @table @code
                   4350: @item f
                   4351: @cindex @code{f}, stack item type
                   4352: Boolean flags, i.e. @code{false} or @code{true}.
                   4353: @item c
                   4354: @cindex @code{c}, stack item type
                   4355: Char
                   4356: @item w
                   4357: @cindex @code{w}, stack item type
                   4358: Cell, can contain an integer or an address
                   4359: @item n
                   4360: @cindex @code{n}, stack item type
                   4361: signed integer
                   4362: @item u
                   4363: @cindex @code{u}, stack item type
                   4364: unsigned integer
                   4365: @item d
                   4366: @cindex @code{d}, stack item type
                   4367: double sized signed integer
                   4368: @item ud
                   4369: @cindex @code{ud}, stack item type
                   4370: double sized unsigned integer
                   4371: @item r
                   4372: @cindex @code{r}, stack item type
                   4373: Float (on the FP stack)
1.21      crook    4374: @item a-
1.1       anton    4375: @cindex @code{a_}, stack item type
                   4376: Cell-aligned address
1.21      crook    4377: @item c-
1.1       anton    4378: @cindex @code{c_}, stack item type
                   4379: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    4380: @item f-
1.1       anton    4381: @cindex @code{f_}, stack item type
                   4382: Float-aligned address
1.21      crook    4383: @item df-
1.1       anton    4384: @cindex @code{df_}, stack item type
                   4385: Address aligned for IEEE double precision float
1.21      crook    4386: @item sf-
1.1       anton    4387: @cindex @code{sf_}, stack item type
                   4388: Address aligned for IEEE single precision float
                   4389: @item xt
                   4390: @cindex @code{xt}, stack item type
                   4391: Execution token, same size as Cell
                   4392: @item wid
                   4393: @cindex @code{wid}, stack item type
1.21      crook    4394: Word list ID, same size as Cell
1.68      anton    4395: @item ior, wior
                   4396: @cindex ior type description
                   4397: @cindex wior type description
                   4398: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
1.1       anton    4399: @item f83name
                   4400: @cindex @code{f83name}, stack item type
                   4401: Pointer to a name structure
                   4402: @item "
                   4403: @cindex @code{"}, stack item type
1.12      anton    4404: string in the input stream (not on the stack). The terminating character
                   4405: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    4406: quotes.
                   4407: @end table
                   4408: 
1.65      anton    4409: @comment ----------------------------------------------
                   4410: @node Case insensitivity, Comments, Notation, Words
                   4411: @section Case insensitivity
                   4412: @cindex case sensitivity
                   4413: @cindex upper and lower case
                   4414: 
                   4415: Gforth is case-insensitive; you can enter definitions and invoke
                   4416: Standard words using upper, lower or mixed case (however,
                   4417: @pxref{core-idef, Implementation-defined options, Implementation-defined
                   4418: options}).
                   4419: 
                   4420: ANS Forth only @i{requires} implementations to recognise Standard words
                   4421: when they are typed entirely in upper case. Therefore, a Standard
                   4422: program must use upper case for all Standard words. You can use whatever
                   4423: case you like for words that you define, but in a Standard program you
                   4424: have to use the words in the same case that you defined them.
                   4425: 
                   4426: Gforth supports case sensitivity through @code{table}s (case-sensitive
                   4427: wordlists, @pxref{Word Lists}).
                   4428: 
                   4429: Two people have asked how to convert Gforth to be case-sensitive; while
                   4430: we think this is a bad idea, you can change all wordlists into tables
                   4431: like this:
                   4432: 
                   4433: @example
                   4434: ' table-find forth-wordlist wordlist-map @ !
                   4435: @end example
                   4436: 
                   4437: Note that you now have to type the predefined words in the same case
                   4438: that we defined them, which are varying.  You may want to convert them
                   4439: to your favourite case before doing this operation (I won't explain how,
                   4440: because if you are even contemplating doing this, you'd better have
                   4441: enough knowledge of Forth systems to know this already).
                   4442: 
                   4443: @node Comments, Boolean Flags, Case insensitivity, Words
1.21      crook    4444: @section Comments
1.26      crook    4445: @cindex comments
1.21      crook    4446: 
1.29      crook    4447: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   4448: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    4449: 
1.44      crook    4450: 
1.23      crook    4451: doc-(
1.21      crook    4452: doc-\
1.23      crook    4453: doc-\G
1.21      crook    4454: 
1.44      crook    4455: 
1.21      crook    4456: @node Boolean Flags, Arithmetic, Comments, Words
                   4457: @section Boolean Flags
1.26      crook    4458: @cindex Boolean flags
1.21      crook    4459: 
                   4460: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   4461: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    4462: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    4463: a cell that has @i{any} bit set as @code{true}.
1.67      anton    4464: @c on and off to Memory? 
                   4465: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44      crook    4466: 
1.21      crook    4467: doc-true
                   4468: doc-false
1.29      crook    4469: doc-on
                   4470: doc-off
1.21      crook    4471: 
1.44      crook    4472: 
1.21      crook    4473: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    4474: @section Arithmetic
                   4475: @cindex arithmetic words
                   4476: 
                   4477: @cindex division with potentially negative operands
                   4478: Forth arithmetic is not checked, i.e., you will not hear about integer
                   4479: overflow on addition or multiplication, you may hear about division by
                   4480: zero if you are lucky. The operator is written after the operands, but
                   4481: the operands are still in the original order. I.e., the infix @code{2-1}
                   4482: corresponds to @code{2 1 -}. Forth offers a variety of division
                   4483: operators. If you perform division with potentially negative operands,
                   4484: you do not want to use @code{/} or @code{/mod} with its undefined
                   4485: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   4486: former, @pxref{Mixed precision}).
1.26      crook    4487: @comment TODO discuss the different division forms and the std approach
1.1       anton    4488: 
                   4489: @menu
                   4490: * Single precision::            
1.67      anton    4491: * Double precision::            Double-cell integer arithmetic
1.1       anton    4492: * Bitwise operations::          
1.67      anton    4493: * Numeric comparison::          
1.29      crook    4494: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    4495: * Floating Point::              
                   4496: @end menu
                   4497: 
1.67      anton    4498: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1       anton    4499: @subsection Single precision
                   4500: @cindex single precision arithmetic words
                   4501: 
1.67      anton    4502: @c !! cell undefined
                   4503: 
                   4504: By default, numbers in Forth are single-precision integers that are one
1.26      crook    4505: cell in size. They can be signed or unsigned, depending upon how you
1.49      anton    4506: treat them. For the rules used by the text interpreter for recognising
                   4507: single-precision integers see @ref{Number Conversion}.
1.21      crook    4508: 
1.67      anton    4509: These words are all defined for signed operands, but some of them also
                   4510: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
                   4511: @code{*}.
1.44      crook    4512: 
1.1       anton    4513: doc-+
1.21      crook    4514: doc-1+
1.128     anton    4515: doc-under+
1.1       anton    4516: doc--
1.21      crook    4517: doc-1-
1.1       anton    4518: doc-*
                   4519: doc-/
                   4520: doc-mod
                   4521: doc-/mod
                   4522: doc-negate
                   4523: doc-abs
                   4524: doc-min
                   4525: doc-max
1.27      crook    4526: doc-floored
1.1       anton    4527: 
1.44      crook    4528: 
1.67      anton    4529: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21      crook    4530: @subsection Double precision
                   4531: @cindex double precision arithmetic words
                   4532: 
1.49      anton    4533: For the rules used by the text interpreter for
                   4534: recognising double-precision integers, see @ref{Number Conversion}.
1.21      crook    4535: 
                   4536: A double precision number is represented by a cell pair, with the most
1.67      anton    4537: significant cell at the TOS. It is trivial to convert an unsigned single
                   4538: to a double: simply push a @code{0} onto the TOS. Since numbers are
                   4539: represented by Gforth using 2's complement arithmetic, converting a
                   4540: signed single to a (signed) double requires sign-extension across the
                   4541: most significant cell. This can be achieved using @code{s>d}. The moral
                   4542: of the story is that you cannot convert a number without knowing whether
                   4543: it represents an unsigned or a signed number.
1.21      crook    4544: 
1.67      anton    4545: These words are all defined for signed operands, but some of them also
                   4546: work for unsigned numbers: @code{d+}, @code{d-}.
1.44      crook    4547: 
1.21      crook    4548: doc-s>d
1.67      anton    4549: doc-d>s
1.21      crook    4550: doc-d+
                   4551: doc-d-
                   4552: doc-dnegate
                   4553: doc-dabs
                   4554: doc-dmin
                   4555: doc-dmax
                   4556: 
1.44      crook    4557: 
1.67      anton    4558: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
                   4559: @subsection Bitwise operations
                   4560: @cindex bitwise operation words
                   4561: 
                   4562: 
                   4563: doc-and
                   4564: doc-or
                   4565: doc-xor
                   4566: doc-invert
                   4567: doc-lshift
                   4568: doc-rshift
                   4569: doc-2*
                   4570: doc-d2*
                   4571: doc-2/
                   4572: doc-d2/
                   4573: 
                   4574: 
                   4575: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21      crook    4576: @subsection Numeric comparison
                   4577: @cindex numeric comparison words
                   4578: 
1.67      anton    4579: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
                   4580: d0= d0<>}) work for for both signed and unsigned numbers.
1.44      crook    4581: 
1.28      crook    4582: doc-<
                   4583: doc-<=
                   4584: doc-<>
                   4585: doc-=
                   4586: doc->
                   4587: doc->=
                   4588: 
1.21      crook    4589: doc-0<
1.23      crook    4590: doc-0<=
1.21      crook    4591: doc-0<>
                   4592: doc-0=
1.23      crook    4593: doc-0>
                   4594: doc-0>=
1.28      crook    4595: 
                   4596: doc-u<
                   4597: doc-u<=
1.44      crook    4598: @c u<> and u= exist but are the same as <> and =
1.31      anton    4599: @c doc-u<>
                   4600: @c doc-u=
1.28      crook    4601: doc-u>
                   4602: doc-u>=
                   4603: 
                   4604: doc-within
                   4605: 
                   4606: doc-d<
                   4607: doc-d<=
                   4608: doc-d<>
                   4609: doc-d=
                   4610: doc-d>
                   4611: doc-d>=
1.23      crook    4612: 
1.21      crook    4613: doc-d0<
1.23      crook    4614: doc-d0<=
                   4615: doc-d0<>
1.21      crook    4616: doc-d0=
1.23      crook    4617: doc-d0>
                   4618: doc-d0>=
                   4619: 
1.21      crook    4620: doc-du<
1.28      crook    4621: doc-du<=
1.44      crook    4622: @c du<> and du= exist but are the same as d<> and d=
1.31      anton    4623: @c doc-du<>
                   4624: @c doc-du=
1.28      crook    4625: doc-du>
                   4626: doc-du>=
1.1       anton    4627: 
1.44      crook    4628: 
1.21      crook    4629: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    4630: @subsection Mixed precision
                   4631: @cindex mixed precision arithmetic words
                   4632: 
1.44      crook    4633: 
1.1       anton    4634: doc-m+
                   4635: doc-*/
                   4636: doc-*/mod
                   4637: doc-m*
                   4638: doc-um*
                   4639: doc-m*/
                   4640: doc-um/mod
                   4641: doc-fm/mod
                   4642: doc-sm/rem
                   4643: 
1.44      crook    4644: 
1.21      crook    4645: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    4646: @subsection Floating Point
                   4647: @cindex floating point arithmetic words
                   4648: 
1.49      anton    4649: For the rules used by the text interpreter for
                   4650: recognising floating-point numbers see @ref{Number Conversion}.
1.1       anton    4651: 
1.67      anton    4652: Gforth has a separate floating point stack, but the documentation uses
                   4653: the unified notation.@footnote{It's easy to generate the separate
                   4654: notation from that by just separating the floating-point numbers out:
                   4655: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
                   4656: r3 )}.}
1.1       anton    4657: 
                   4658: @cindex floating-point arithmetic, pitfalls
                   4659: Floating point numbers have a number of unpleasant surprises for the
                   4660: unwary (e.g., floating point addition is not associative) and even a few
                   4661: for the wary. You should not use them unless you know what you are doing
                   4662: or you don't care that the results you get are totally bogus. If you
                   4663: want to learn about the problems of floating point numbers (and how to
1.66      anton    4664: avoid them), you might start with @cite{David Goldberg,
                   4665: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
                   4666: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
                   4667: Surveys 23(1):5@minus{}48, March 1991}.
1.1       anton    4668: 
1.44      crook    4669: 
1.21      crook    4670: doc-d>f
                   4671: doc-f>d
1.1       anton    4672: doc-f+
                   4673: doc-f-
                   4674: doc-f*
                   4675: doc-f/
                   4676: doc-fnegate
                   4677: doc-fabs
                   4678: doc-fmax
                   4679: doc-fmin
                   4680: doc-floor
                   4681: doc-fround
                   4682: doc-f**
                   4683: doc-fsqrt
                   4684: doc-fexp
                   4685: doc-fexpm1
                   4686: doc-fln
                   4687: doc-flnp1
                   4688: doc-flog
                   4689: doc-falog
1.32      anton    4690: doc-f2*
                   4691: doc-f2/
                   4692: doc-1/f
                   4693: doc-precision
                   4694: doc-set-precision
                   4695: 
                   4696: @cindex angles in trigonometric operations
                   4697: @cindex trigonometric operations
                   4698: Angles in floating point operations are given in radians (a full circle
                   4699: has 2 pi radians).
                   4700: 
1.1       anton    4701: doc-fsin
                   4702: doc-fcos
                   4703: doc-fsincos
                   4704: doc-ftan
                   4705: doc-fasin
                   4706: doc-facos
                   4707: doc-fatan
                   4708: doc-fatan2
                   4709: doc-fsinh
                   4710: doc-fcosh
                   4711: doc-ftanh
                   4712: doc-fasinh
                   4713: doc-facosh
                   4714: doc-fatanh
1.21      crook    4715: doc-pi
1.28      crook    4716: 
1.32      anton    4717: @cindex equality of floats
                   4718: @cindex floating-point comparisons
1.31      anton    4719: One particular problem with floating-point arithmetic is that comparison
                   4720: for equality often fails when you would expect it to succeed.  For this
                   4721: reason approximate equality is often preferred (but you still have to
1.67      anton    4722: know what you are doing).  Also note that IEEE NaNs may compare
1.68      anton    4723: differently from what you might expect.  The comparison words are:
1.31      anton    4724: 
                   4725: doc-f~rel
                   4726: doc-f~abs
1.68      anton    4727: doc-f~
1.31      anton    4728: doc-f=
                   4729: doc-f<>
                   4730: 
                   4731: doc-f<
                   4732: doc-f<=
                   4733: doc-f>
                   4734: doc-f>=
                   4735: 
1.21      crook    4736: doc-f0<
1.28      crook    4737: doc-f0<=
                   4738: doc-f0<>
1.21      crook    4739: doc-f0=
1.28      crook    4740: doc-f0>
                   4741: doc-f0>=
                   4742: 
1.1       anton    4743: 
                   4744: @node Stack Manipulation, Memory, Arithmetic, Words
                   4745: @section Stack Manipulation
                   4746: @cindex stack manipulation words
                   4747: 
                   4748: @cindex floating-point stack in the standard
1.21      crook    4749: Gforth maintains a number of separate stacks:
                   4750: 
1.29      crook    4751: @cindex data stack
                   4752: @cindex parameter stack
1.21      crook    4753: @itemize @bullet
                   4754: @item
1.29      crook    4755: A data stack (also known as the @dfn{parameter stack}) -- for
                   4756: characters, cells, addresses, and double cells.
1.21      crook    4757: 
1.29      crook    4758: @cindex floating-point stack
1.21      crook    4759: @item
1.44      crook    4760: A floating point stack -- for holding floating point (FP) numbers.
1.21      crook    4761: 
1.29      crook    4762: @cindex return stack
1.21      crook    4763: @item
1.44      crook    4764: A return stack -- for holding the return addresses of colon
1.32      anton    4765: definitions and other (non-FP) data.
1.21      crook    4766: 
1.29      crook    4767: @cindex locals stack
1.21      crook    4768: @item
1.44      crook    4769: A locals stack -- for holding local variables.
1.21      crook    4770: @end itemize
                   4771: 
1.1       anton    4772: @menu
                   4773: * Data stack::                  
                   4774: * Floating point stack::        
                   4775: * Return stack::                
                   4776: * Locals stack::                
                   4777: * Stack pointer manipulation::  
                   4778: @end menu
                   4779: 
                   4780: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   4781: @subsection Data stack
                   4782: @cindex data stack manipulation words
                   4783: @cindex stack manipulations words, data stack
                   4784: 
1.44      crook    4785: 
1.1       anton    4786: doc-drop
                   4787: doc-nip
                   4788: doc-dup
                   4789: doc-over
                   4790: doc-tuck
                   4791: doc-swap
1.21      crook    4792: doc-pick
1.1       anton    4793: doc-rot
                   4794: doc--rot
                   4795: doc-?dup
                   4796: doc-roll
                   4797: doc-2drop
                   4798: doc-2nip
                   4799: doc-2dup
                   4800: doc-2over
                   4801: doc-2tuck
                   4802: doc-2swap
                   4803: doc-2rot
                   4804: 
1.44      crook    4805: 
1.1       anton    4806: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   4807: @subsection Floating point stack
                   4808: @cindex floating-point stack manipulation words
                   4809: @cindex stack manipulation words, floating-point stack
                   4810: 
1.32      anton    4811: Whilst every sane Forth has a separate floating-point stack, it is not
                   4812: strictly required; an ANS Forth system could theoretically keep
                   4813: floating-point numbers on the data stack. As an additional difficulty,
                   4814: you don't know how many cells a floating-point number takes. It is
                   4815: reportedly possible to write words in a way that they work also for a
                   4816: unified stack model, but we do not recommend trying it. Instead, just
                   4817: say that your program has an environmental dependency on a separate
                   4818: floating-point stack.
                   4819: 
                   4820: doc-floating-stack
                   4821: 
1.1       anton    4822: doc-fdrop
                   4823: doc-fnip
                   4824: doc-fdup
                   4825: doc-fover
                   4826: doc-ftuck
                   4827: doc-fswap
1.21      crook    4828: doc-fpick
1.1       anton    4829: doc-frot
                   4830: 
1.44      crook    4831: 
1.1       anton    4832: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   4833: @subsection Return stack
                   4834: @cindex return stack manipulation words
                   4835: @cindex stack manipulation words, return stack
                   4836: 
1.32      anton    4837: @cindex return stack and locals
                   4838: @cindex locals and return stack
                   4839: A Forth system is allowed to keep local variables on the
                   4840: return stack. This is reasonable, as local variables usually eliminate
                   4841: the need to use the return stack explicitly. So, if you want to produce
                   4842: a standard compliant program and you are using local variables in a
                   4843: word, forget about return stack manipulations in that word (refer to the
                   4844: standard document for the exact rules).
                   4845: 
1.1       anton    4846: doc->r
                   4847: doc-r>
                   4848: doc-r@
                   4849: doc-rdrop
                   4850: doc-2>r
                   4851: doc-2r>
                   4852: doc-2r@
                   4853: doc-2rdrop
                   4854: 
1.44      crook    4855: 
1.1       anton    4856: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   4857: @subsection Locals stack
                   4858: 
1.78      anton    4859: Gforth uses an extra locals stack.  It is described, along with the
                   4860: reasons for its existence, in @ref{Locals implementation}.
1.21      crook    4861: 
1.1       anton    4862: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   4863: @subsection Stack pointer manipulation
                   4864: @cindex stack pointer manipulation words
                   4865: 
1.44      crook    4866: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21      crook    4867: doc-sp0
1.1       anton    4868: doc-sp@
                   4869: doc-sp!
1.21      crook    4870: doc-fp0
1.1       anton    4871: doc-fp@
                   4872: doc-fp!
1.21      crook    4873: doc-rp0
1.1       anton    4874: doc-rp@
                   4875: doc-rp!
1.21      crook    4876: doc-lp0
1.1       anton    4877: doc-lp@
                   4878: doc-lp!
                   4879: 
1.44      crook    4880: 
1.1       anton    4881: @node Memory, Control Structures, Stack Manipulation, Words
                   4882: @section Memory
1.26      crook    4883: @cindex memory words
1.1       anton    4884: 
1.32      anton    4885: @menu
                   4886: * Memory model::                
                   4887: * Dictionary allocation::       
                   4888: * Heap Allocation::             
                   4889: * Memory Access::               
                   4890: * Address arithmetic::          
                   4891: * Memory Blocks::               
                   4892: @end menu
                   4893: 
1.67      anton    4894: In addition to the standard Forth memory allocation words, there is also
                   4895: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   4896: garbage collector}.
                   4897: 
1.32      anton    4898: @node Memory model, Dictionary allocation, Memory, Memory
                   4899: @subsection ANS Forth and Gforth memory models
                   4900: 
                   4901: @c The ANS Forth description is a mess (e.g., is the heap part of
                   4902: @c the dictionary?), so let's not stick to closely with it.
                   4903: 
1.67      anton    4904: ANS Forth considers a Forth system as consisting of several address
                   4905: spaces, of which only @dfn{data space} is managed and accessible with
                   4906: the memory words.  Memory not necessarily in data space includes the
                   4907: stacks, the code (called code space) and the headers (called name
                   4908: space). In Gforth everything is in data space, but the code for the
                   4909: primitives is usually read-only.
1.32      anton    4910: 
                   4911: Data space is divided into a number of areas: The (data space portion of
                   4912: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
                   4913: refer to the search data structure embodied in word lists and headers,
                   4914: because it is used for looking up names, just as you would in a
                   4915: conventional dictionary.}, the heap, and a number of system-allocated
                   4916: buffers.
                   4917: 
1.68      anton    4918: @cindex address arithmetic restrictions, ANS vs. Gforth
                   4919: @cindex contiguous regions, ANS vs. Gforth
1.32      anton    4920: In ANS Forth data space is also divided into contiguous regions.  You
                   4921: can only use address arithmetic within a contiguous region, not between
                   4922: them.  Usually each allocation gives you one contiguous region, but the
1.33      anton    4923: dictionary allocation words have additional rules (@pxref{Dictionary
1.32      anton    4924: allocation}).
                   4925: 
                   4926: Gforth provides one big address space, and address arithmetic can be
                   4927: performed between any addresses. However, in the dictionary headers or
                   4928: code are interleaved with data, so almost the only contiguous data space
                   4929: regions there are those described by ANS Forth as contiguous; but you
                   4930: can be sure that the dictionary is allocated towards increasing
                   4931: addresses even between contiguous regions.  The memory order of
                   4932: allocations in the heap is platform-dependent (and possibly different
                   4933: from one run to the next).
                   4934: 
1.27      crook    4935: 
1.32      anton    4936: @node Dictionary allocation, Heap Allocation, Memory model, Memory
                   4937: @subsection Dictionary allocation
1.27      crook    4938: @cindex reserving data space
                   4939: @cindex data space - reserving some
                   4940: 
1.32      anton    4941: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
                   4942: you want to deallocate X, you also deallocate everything
                   4943: allocated after X.
                   4944: 
1.68      anton    4945: @cindex contiguous regions in dictionary allocation
1.32      anton    4946: The allocations using the words below are contiguous and grow the region
                   4947: towards increasing addresses.  Other words that allocate dictionary
                   4948: memory of any kind (i.e., defining words including @code{:noname}) end
                   4949: the contiguous region and start a new one.
                   4950: 
                   4951: In ANS Forth only @code{create}d words are guaranteed to produce an
                   4952: address that is the start of the following contiguous region.  In
                   4953: particular, the cell allocated by @code{variable} is not guaranteed to
                   4954: be contiguous with following @code{allot}ed memory.
                   4955: 
                   4956: You can deallocate memory by using @code{allot} with a negative argument
                   4957: (with some restrictions, see @code{allot}). For larger deallocations use
                   4958: @code{marker}.
1.27      crook    4959: 
1.29      crook    4960: 
1.27      crook    4961: doc-here
                   4962: doc-unused
                   4963: doc-allot
                   4964: doc-c,
1.29      crook    4965: doc-f,
1.27      crook    4966: doc-,
                   4967: doc-2,
                   4968: 
1.32      anton    4969: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
                   4970: course you should allocate memory in an aligned way, too. I.e., before
                   4971: allocating allocating a cell, @code{here} must be cell-aligned, etc.
                   4972: The words below align @code{here} if it is not already.  Basically it is
                   4973: only already aligned for a type, if the last allocation was a multiple
                   4974: of the size of this type and if @code{here} was aligned for this type
                   4975: before.
                   4976: 
                   4977: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
                   4978: ANS Forth (@code{maxalign}ed in Gforth).
                   4979: 
                   4980: doc-align
                   4981: doc-falign
                   4982: doc-sfalign
                   4983: doc-dfalign
                   4984: doc-maxalign
                   4985: doc-cfalign
                   4986: 
                   4987: 
                   4988: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
                   4989: @subsection Heap allocation
                   4990: @cindex heap allocation
                   4991: @cindex dynamic allocation of memory
                   4992: @cindex memory-allocation word set
                   4993: 
1.68      anton    4994: @cindex contiguous regions and heap allocation
1.32      anton    4995: Heap allocation supports deallocation of allocated memory in any
                   4996: order. Dictionary allocation is not affected by it (i.e., it does not
                   4997: end a contiguous region). In Gforth, these words are implemented using
                   4998: the standard C library calls malloc(), free() and resize().
                   4999: 
1.68      anton    5000: The memory region produced by one invocation of @code{allocate} or
                   5001: @code{resize} is internally contiguous.  There is no contiguity between
                   5002: such a region and any other region (including others allocated from the
                   5003: heap).
                   5004: 
1.32      anton    5005: doc-allocate
                   5006: doc-free
                   5007: doc-resize
                   5008: 
1.27      crook    5009: 
1.32      anton    5010: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1       anton    5011: @subsection Memory Access
                   5012: @cindex memory access words
                   5013: 
                   5014: doc-@
                   5015: doc-!
                   5016: doc-+!
                   5017: doc-c@
                   5018: doc-c!
                   5019: doc-2@
                   5020: doc-2!
                   5021: doc-f@
                   5022: doc-f!
                   5023: doc-sf@
                   5024: doc-sf!
                   5025: doc-df@
                   5026: doc-df!
1.144     anton    5027: doc-sw@
                   5028: doc-uw@
                   5029: doc-w!
                   5030: doc-sl@
                   5031: doc-ul@
                   5032: doc-l!
1.68      anton    5033: 
1.32      anton    5034: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   5035: @subsection Address arithmetic
1.1       anton    5036: @cindex address arithmetic words
                   5037: 
1.67      anton    5038: Address arithmetic is the foundation on which you can build data
                   5039: structures like arrays, records (@pxref{Structures}) and objects
                   5040: (@pxref{Object-oriented Forth}).
1.32      anton    5041: 
1.68      anton    5042: @cindex address unit
                   5043: @cindex au (address unit)
1.1       anton    5044: ANS Forth does not specify the sizes of the data types. Instead, it
                   5045: offers a number of words for computing sizes and doing address
1.29      crook    5046: arithmetic. Address arithmetic is performed in terms of address units
                   5047: (aus); on most systems the address unit is one byte. Note that a
                   5048: character may have more than one au, so @code{chars} is no noop (on
1.68      anton    5049: platforms where it is a noop, it compiles to nothing).
1.1       anton    5050: 
1.67      anton    5051: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
                   5052: you have the address of a cell, perform @code{1 cells +}, and you will
                   5053: have the address of the next cell.
                   5054: 
1.68      anton    5055: @cindex contiguous regions and address arithmetic
1.67      anton    5056: In ANS Forth you can perform address arithmetic only within a contiguous
                   5057: region, i.e., if you have an address into one region, you can only add
                   5058: and subtract such that the result is still within the region; you can
                   5059: only subtract or compare addresses from within the same contiguous
                   5060: region.  Reasons: several contiguous regions can be arranged in memory
                   5061: in any way; on segmented systems addresses may have unusual
                   5062: representations, such that address arithmetic only works within a
                   5063: region.  Gforth provides a few more guarantees (linear address space,
                   5064: dictionary grows upwards), but in general I have found it easy to stay
                   5065: within contiguous regions (exception: computing and comparing to the
                   5066: address just beyond the end of an array).
                   5067: 
1.1       anton    5068: @cindex alignment of addresses for types
                   5069: ANS Forth also defines words for aligning addresses for specific
                   5070: types. Many computers require that accesses to specific data types
                   5071: must only occur at specific addresses; e.g., that cells may only be
                   5072: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   5073: accesses, it can usually perform aligned accesses faster. 
                   5074: 
                   5075: For the performance-conscious: alignment operations are usually only
                   5076: necessary during the definition of a data structure, not during the
                   5077: (more frequent) accesses to it.
                   5078: 
                   5079: ANS Forth defines no words for character-aligning addresses. This is not
                   5080: an oversight, but reflects the fact that addresses that are not
                   5081: char-aligned have no use in the standard and therefore will not be
                   5082: created.
                   5083: 
                   5084: @cindex @code{CREATE} and alignment
1.29      crook    5085: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    5086: are cell-aligned; in addition, Gforth guarantees that these addresses
                   5087: are aligned for all purposes.
                   5088: 
1.26      crook    5089: Note that the ANS Forth word @code{char} has nothing to do with address
                   5090: arithmetic.
1.1       anton    5091: 
1.44      crook    5092: 
1.1       anton    5093: doc-chars
                   5094: doc-char+
                   5095: doc-cells
                   5096: doc-cell+
                   5097: doc-cell
                   5098: doc-aligned
                   5099: doc-floats
                   5100: doc-float+
                   5101: doc-float
                   5102: doc-faligned
                   5103: doc-sfloats
                   5104: doc-sfloat+
                   5105: doc-sfaligned
                   5106: doc-dfloats
                   5107: doc-dfloat+
                   5108: doc-dfaligned
                   5109: doc-maxaligned
                   5110: doc-cfaligned
                   5111: doc-address-unit-bits
1.145     anton    5112: doc-/w
                   5113: doc-/l
1.44      crook    5114: 
1.32      anton    5115: @node Memory Blocks,  , Address arithmetic, Memory
1.1       anton    5116: @subsection Memory Blocks
                   5117: @cindex memory block words
1.27      crook    5118: @cindex character strings - moving and copying
                   5119: 
1.49      anton    5120: Memory blocks often represent character strings; For ways of storing
                   5121: character strings in memory see @ref{String Formats}.  For other
                   5122: string-processing words see @ref{Displaying characters and strings}.
1.1       anton    5123: 
1.67      anton    5124: A few of these words work on address unit blocks.  In that case, you
                   5125: usually have to insert @code{CHARS} before the word when working on
                   5126: character strings.  Most words work on character blocks, and expect a
                   5127: char-aligned address.
                   5128: 
                   5129: When copying characters between overlapping memory regions, use
                   5130: @code{chars move} or choose carefully between @code{cmove} and
                   5131: @code{cmove>}.
1.44      crook    5132: 
1.1       anton    5133: doc-move
                   5134: doc-erase
                   5135: doc-cmove
                   5136: doc-cmove>
                   5137: doc-fill
                   5138: doc-blank
1.21      crook    5139: doc-compare
1.111     anton    5140: doc-str=
                   5141: doc-str<
                   5142: doc-string-prefix?
1.21      crook    5143: doc-search
1.27      crook    5144: doc--trailing
                   5145: doc-/string
1.82      anton    5146: doc-bounds
1.141     anton    5147: doc-pad
1.111     anton    5148: 
1.27      crook    5149: @comment TODO examples
                   5150: 
1.1       anton    5151: 
1.26      crook    5152: @node Control Structures, Defining Words, Memory, Words
1.1       anton    5153: @section Control Structures
                   5154: @cindex control structures
                   5155: 
1.33      anton    5156: Control structures in Forth cannot be used interpretively, only in a
                   5157: colon definition@footnote{To be precise, they have no interpretation
                   5158: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
                   5159: not like this limitation, but have not seen a satisfying way around it
                   5160: yet, although many schemes have been proposed.
1.1       anton    5161: 
                   5162: @menu
1.33      anton    5163: * Selection::                   IF ... ELSE ... ENDIF
                   5164: * Simple Loops::                BEGIN ...
1.29      crook    5165: * Counted Loops::               DO
1.67      anton    5166: * Arbitrary control structures::  
                   5167: * Calls and returns::           
1.1       anton    5168: * Exception Handling::          
                   5169: @end menu
                   5170: 
                   5171: @node Selection, Simple Loops, Control Structures, Control Structures
                   5172: @subsection Selection
                   5173: @cindex selection control structures
                   5174: @cindex control structures for selection
                   5175: 
                   5176: @cindex @code{IF} control structure
                   5177: @example
1.29      crook    5178: @i{flag}
1.1       anton    5179: IF
1.29      crook    5180:   @i{code}
1.1       anton    5181: ENDIF
                   5182: @end example
1.21      crook    5183: @noindent
1.33      anton    5184: 
1.44      crook    5185: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
                   5186: with any bit set represents truth) @i{code} is executed.
1.33      anton    5187: 
1.1       anton    5188: @example
1.29      crook    5189: @i{flag}
1.1       anton    5190: IF
1.29      crook    5191:   @i{code1}
1.1       anton    5192: ELSE
1.29      crook    5193:   @i{code2}
1.1       anton    5194: ENDIF
                   5195: @end example
                   5196: 
1.44      crook    5197: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
                   5198: executed.
1.33      anton    5199: 
1.1       anton    5200: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   5201: standard, and @code{ENDIF} is not, although it is quite popular. We
                   5202: recommend using @code{ENDIF}, because it is less confusing for people
                   5203: who also know other languages (and is not prone to reinforcing negative
                   5204: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   5205: system that only supplies @code{THEN} is simple:
                   5206: @example
1.82      anton    5207: : ENDIF   POSTPONE then ; immediate
1.1       anton    5208: @end example
                   5209: 
                   5210: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   5211: (adv.)}  has the following meanings:
                   5212: @quotation
                   5213: ... 2b: following next after in order ... 3d: as a necessary consequence
                   5214: (if you were there, then you saw them).
                   5215: @end quotation
                   5216: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   5217: and many other programming languages has the meaning 3d.]
                   5218: 
1.21      crook    5219: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    5220: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    5221: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    5222: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   5223: @file{compat/control.fs}.
                   5224: 
                   5225: @cindex @code{CASE} control structure
                   5226: @example
1.29      crook    5227: @i{n}
1.1       anton    5228: CASE
1.29      crook    5229:   @i{n1} OF @i{code1} ENDOF
                   5230:   @i{n2} OF @i{code2} ENDOF
1.1       anton    5231:   @dots{}
1.68      anton    5232:   ( n ) @i{default-code} ( n )
1.131     anton    5233: ENDCASE ( )
1.1       anton    5234: @end example
                   5235: 
1.131     anton    5236: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If
                   5237: no @i{ni} matches, the optional @i{default-code} is executed. The
                   5238: optional default case can be added by simply writing the code after
                   5239: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
                   5240: but must not consume it.  The value @i{n} is consumed by this
                   5241: construction (either by a OF that matches, or by the ENDCASE, if no OF
                   5242: matches).
1.1       anton    5243: 
1.69      anton    5244: @progstyle
1.131     anton    5245: To keep the code understandable, you should ensure that you change the
                   5246: stack in the same way (wrt. number and types of stack items consumed
                   5247: and pushed) on all paths through a selection construct.
1.69      anton    5248: 
1.1       anton    5249: @node Simple Loops, Counted Loops, Selection, Control Structures
                   5250: @subsection Simple Loops
                   5251: @cindex simple loops
                   5252: @cindex loops without count 
                   5253: 
                   5254: @cindex @code{WHILE} loop
                   5255: @example
                   5256: BEGIN
1.29      crook    5257:   @i{code1}
                   5258:   @i{flag}
1.1       anton    5259: WHILE
1.29      crook    5260:   @i{code2}
1.1       anton    5261: REPEAT
                   5262: @end example
                   5263: 
1.29      crook    5264: @i{code1} is executed and @i{flag} is computed. If it is true,
                   5265: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    5266: false, execution continues after the @code{REPEAT}.
                   5267: 
                   5268: @cindex @code{UNTIL} loop
                   5269: @example
                   5270: BEGIN
1.29      crook    5271:   @i{code}
                   5272:   @i{flag}
1.1       anton    5273: UNTIL
                   5274: @end example
                   5275: 
1.29      crook    5276: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    5277: 
1.69      anton    5278: @progstyle
                   5279: To keep the code understandable, a complete iteration of the loop should
                   5280: not change the number and types of the items on the stacks.
                   5281: 
1.1       anton    5282: @cindex endless loop
                   5283: @cindex loops, endless
                   5284: @example
                   5285: BEGIN
1.29      crook    5286:   @i{code}
1.1       anton    5287: AGAIN
                   5288: @end example
                   5289: 
                   5290: This is an endless loop.
                   5291: 
                   5292: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   5293: @subsection Counted Loops
                   5294: @cindex counted loops
                   5295: @cindex loops, counted
                   5296: @cindex @code{DO} loops
                   5297: 
                   5298: The basic counted loop is:
                   5299: @example
1.29      crook    5300: @i{limit} @i{start}
1.1       anton    5301: ?DO
1.29      crook    5302:   @i{body}
1.1       anton    5303: LOOP
                   5304: @end example
                   5305: 
1.29      crook    5306: This performs one iteration for every integer, starting from @i{start}
                   5307: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    5308: accessed with @code{i}. For example, the loop:
1.1       anton    5309: @example
                   5310: 10 0 ?DO
                   5311:   i .
                   5312: LOOP
                   5313: @end example
1.21      crook    5314: @noindent
                   5315: prints @code{0 1 2 3 4 5 6 7 8 9}
                   5316: 
1.1       anton    5317: The index of the innermost loop can be accessed with @code{i}, the index
                   5318: of the next loop with @code{j}, and the index of the third loop with
                   5319: @code{k}.
                   5320: 
1.44      crook    5321: 
1.1       anton    5322: doc-i
                   5323: doc-j
                   5324: doc-k
                   5325: 
1.44      crook    5326: 
1.1       anton    5327: The loop control data are kept on the return stack, so there are some
1.21      crook    5328: restrictions on mixing return stack accesses and counted loop words. In
                   5329: particuler, if you put values on the return stack outside the loop, you
                   5330: cannot read them inside the loop@footnote{well, not in a way that is
                   5331: portable.}. If you put values on the return stack within a loop, you
                   5332: have to remove them before the end of the loop and before accessing the
                   5333: index of the loop.
1.1       anton    5334: 
                   5335: There are several variations on the counted loop:
                   5336: 
1.21      crook    5337: @itemize @bullet
                   5338: @item
                   5339: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   5340: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   5341: 
                   5342: @example
                   5343: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   5344: @end example
                   5345: prints @code{0 1 2 3}
                   5346: 
1.1       anton    5347: 
1.21      crook    5348: @item
                   5349: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   5350: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   5351: return stack so @code{EXIT} can get to its return address. For example:
                   5352: 
                   5353: @example
                   5354: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   5355: @end example
                   5356: prints @code{0 1 2 3}
                   5357: 
                   5358: 
                   5359: @item
1.29      crook    5360: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    5361: (and @code{LOOP} iterates until they become equal by wrap-around
                   5362: arithmetic). This behaviour is usually not what you want. Therefore,
                   5363: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    5364: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   5365: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    5366: unsigned loop parameters.
                   5367: 
1.21      crook    5368: @item
                   5369: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   5370: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   5371: if you know that the loop is entered in any case. Such knowledge tends
                   5372: to become invalid during maintenance of a program, and then the
                   5373: @code{DO} will make trouble.
                   5374: 
                   5375: @item
1.29      crook    5376: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   5377: index by @i{n} instead of by 1. The loop is terminated when the border
                   5378: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    5379: 
1.21      crook    5380: @example
                   5381: 4 0 +DO  i .  2 +LOOP
                   5382: @end example
                   5383: @noindent
                   5384: prints @code{0 2}
                   5385: 
                   5386: @example
                   5387: 4 1 +DO  i .  2 +LOOP
                   5388: @end example
                   5389: @noindent
                   5390: prints @code{1 3}
1.1       anton    5391: 
1.68      anton    5392: @item
1.1       anton    5393: @cindex negative increment for counted loops
                   5394: @cindex counted loops with negative increment
1.29      crook    5395: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    5396: 
1.21      crook    5397: @example
                   5398: -1 0 ?DO  i .  -1 +LOOP
                   5399: @end example
                   5400: @noindent
                   5401: prints @code{0 -1}
1.1       anton    5402: 
1.21      crook    5403: @example
                   5404: 0 0 ?DO  i .  -1 +LOOP
                   5405: @end example
                   5406: prints nothing.
1.1       anton    5407: 
1.29      crook    5408: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   5409: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   5410: index by @i{u} each iteration. The loop is terminated when the border
                   5411: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    5412: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   5413: 
1.21      crook    5414: @example
                   5415: -2 0 -DO  i .  1 -LOOP
                   5416: @end example
                   5417: @noindent
                   5418: prints @code{0 -1}
1.1       anton    5419: 
1.21      crook    5420: @example
                   5421: -1 0 -DO  i .  1 -LOOP
                   5422: @end example
                   5423: @noindent
                   5424: prints @code{0}
                   5425: 
                   5426: @example
                   5427: 0 0 -DO  i .  1 -LOOP
                   5428: @end example
                   5429: @noindent
                   5430: prints nothing.
1.1       anton    5431: 
1.21      crook    5432: @end itemize
1.1       anton    5433: 
                   5434: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    5435: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   5436: for these words that uses only standard words is provided in
                   5437: @file{compat/loops.fs}.
1.1       anton    5438: 
                   5439: 
                   5440: @cindex @code{FOR} loops
1.26      crook    5441: Another counted loop is:
1.1       anton    5442: @example
1.29      crook    5443: @i{n}
1.1       anton    5444: FOR
1.29      crook    5445:   @i{body}
1.1       anton    5446: NEXT
                   5447: @end example
                   5448: This is the preferred loop of native code compiler writers who are too
1.26      crook    5449: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    5450: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   5451: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    5452: Forth systems may behave differently, even if they support @code{FOR}
                   5453: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    5454: 
                   5455: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   5456: @subsection Arbitrary control structures
                   5457: @cindex control structures, user-defined
                   5458: 
                   5459: @cindex control-flow stack
                   5460: ANS Forth permits and supports using control structures in a non-nested
                   5461: way. Information about incomplete control structures is stored on the
                   5462: control-flow stack. This stack may be implemented on the Forth data
                   5463: stack, and this is what we have done in Gforth.
                   5464: 
                   5465: @cindex @code{orig}, control-flow stack item
                   5466: @cindex @code{dest}, control-flow stack item
                   5467: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   5468: entry represents a backward branch target. A few words are the basis for
                   5469: building any control structure possible (except control structures that
                   5470: need storage, like calls, coroutines, and backtracking).
                   5471: 
1.44      crook    5472: 
1.1       anton    5473: doc-if
                   5474: doc-ahead
                   5475: doc-then
                   5476: doc-begin
                   5477: doc-until
                   5478: doc-again
                   5479: doc-cs-pick
                   5480: doc-cs-roll
                   5481: 
1.44      crook    5482: 
1.21      crook    5483: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   5484: manipulate the control-flow stack in a portable way. Without them, you
                   5485: would need to know how many stack items are occupied by a control-flow
                   5486: entry (many systems use one cell. In Gforth they currently take three,
                   5487: but this may change in the future).
                   5488: 
1.1       anton    5489: Some standard control structure words are built from these words:
                   5490: 
1.44      crook    5491: 
1.1       anton    5492: doc-else
                   5493: doc-while
                   5494: doc-repeat
                   5495: 
1.44      crook    5496: 
                   5497: @noindent
1.1       anton    5498: Gforth adds some more control-structure words:
                   5499: 
1.44      crook    5500: 
1.1       anton    5501: doc-endif
                   5502: doc-?dup-if
                   5503: doc-?dup-0=-if
                   5504: 
1.44      crook    5505: 
                   5506: @noindent
1.1       anton    5507: Counted loop words constitute a separate group of words:
                   5508: 
1.44      crook    5509: 
1.1       anton    5510: doc-?do
                   5511: doc-+do
                   5512: doc-u+do
                   5513: doc--do
                   5514: doc-u-do
                   5515: doc-do
                   5516: doc-for
                   5517: doc-loop
                   5518: doc-+loop
                   5519: doc--loop
                   5520: doc-next
                   5521: doc-leave
                   5522: doc-?leave
                   5523: doc-unloop
                   5524: doc-done
                   5525: 
1.44      crook    5526: 
1.21      crook    5527: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   5528: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    5529: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   5530: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   5531: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   5532: resolved (by using one of the loop-ending words or @code{DONE}).
                   5533: 
1.44      crook    5534: @noindent
1.26      crook    5535: Another group of control structure words are:
1.1       anton    5536: 
1.44      crook    5537: 
1.1       anton    5538: doc-case
                   5539: doc-endcase
                   5540: doc-of
                   5541: doc-endof
                   5542: 
1.44      crook    5543: 
1.21      crook    5544: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   5545: @code{CS-ROLL}.
1.1       anton    5546: 
                   5547: @subsubsection Programming Style
1.47      crook    5548: @cindex control structures programming style
                   5549: @cindex programming style, arbitrary control structures
1.1       anton    5550: 
                   5551: In order to ensure readability we recommend that you do not create
                   5552: arbitrary control structures directly, but define new control structure
                   5553: words for the control structure you want and use these words in your
1.26      crook    5554: program. For example, instead of writing:
1.1       anton    5555: 
                   5556: @example
1.26      crook    5557: BEGIN
1.1       anton    5558:   ...
1.26      crook    5559: IF [ 1 CS-ROLL ]
1.1       anton    5560:   ...
1.26      crook    5561: AGAIN THEN
1.1       anton    5562: @end example
                   5563: 
1.21      crook    5564: @noindent
1.1       anton    5565: we recommend defining control structure words, e.g.,
                   5566: 
                   5567: @example
1.26      crook    5568: : WHILE ( DEST -- ORIG DEST )
                   5569:  POSTPONE IF
                   5570:  1 CS-ROLL ; immediate
                   5571: 
                   5572: : REPEAT ( orig dest -- )
                   5573:  POSTPONE AGAIN
                   5574:  POSTPONE THEN ; immediate
1.1       anton    5575: @end example
                   5576: 
1.21      crook    5577: @noindent
1.1       anton    5578: and then using these to create the control structure:
                   5579: 
                   5580: @example
1.26      crook    5581: BEGIN
1.1       anton    5582:   ...
1.26      crook    5583: WHILE
1.1       anton    5584:   ...
1.26      crook    5585: REPEAT
1.1       anton    5586: @end example
                   5587: 
                   5588: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   5589: @code{WHILE} are predefined, so in this example it would not be
                   5590: necessary to define them.
                   5591: 
                   5592: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   5593: @subsection Calls and returns
                   5594: @cindex calling a definition
                   5595: @cindex returning from a definition
                   5596: 
1.3       anton    5597: @cindex recursive definitions
                   5598: A definition can be called simply be writing the name of the definition
1.26      crook    5599: to be called. Normally a definition is invisible during its own
1.3       anton    5600: definition. If you want to write a directly recursive definition, you
1.26      crook    5601: can use @code{recursive} to make the current definition visible, or
                   5602: @code{recurse} to call the current definition directly.
1.3       anton    5603: 
1.44      crook    5604: 
1.3       anton    5605: doc-recursive
                   5606: doc-recurse
                   5607: 
1.44      crook    5608: 
1.21      crook    5609: @comment TODO add example of the two recursion methods
1.12      anton    5610: @quotation
                   5611: @progstyle
                   5612: I prefer using @code{recursive} to @code{recurse}, because calling the
                   5613: definition by name is more descriptive (if the name is well-chosen) than
                   5614: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   5615: implementation, it is much better to read (and think) ``now sort the
                   5616: partitions'' than to read ``now do a recursive call''.
                   5617: @end quotation
1.3       anton    5618: 
1.29      crook    5619: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    5620: 
                   5621: @example
1.28      crook    5622: Defer foo
1.3       anton    5623: 
                   5624: : bar ( ... -- ... )
                   5625:  ... foo ... ;
                   5626: 
                   5627: :noname ( ... -- ... )
                   5628:  ... bar ... ;
                   5629: IS foo
                   5630: @end example
                   5631: 
1.170     pazsan   5632: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33      anton    5633: 
1.26      crook    5634: The current definition returns control to the calling definition when
1.33      anton    5635: the end of the definition is reached or @code{EXIT} is encountered.
1.1       anton    5636: 
                   5637: doc-exit
                   5638: doc-;s
                   5639: 
1.44      crook    5640: 
1.1       anton    5641: @node Exception Handling,  , Calls and returns, Control Structures
                   5642: @subsection Exception Handling
1.26      crook    5643: @cindex exceptions
1.1       anton    5644: 
1.68      anton    5645: @c quit is a very bad idea for error handling, 
                   5646: @c because it does not translate into a THROW
                   5647: @c it also does not belong into this chapter
                   5648: 
                   5649: If a word detects an error condition that it cannot handle, it can
                   5650: @code{throw} an exception.  In the simplest case, this will terminate
                   5651: your program, and report an appropriate error.
1.21      crook    5652: 
1.68      anton    5653: doc-throw
1.1       anton    5654: 
1.69      anton    5655: @code{Throw} consumes a cell-sized error number on the stack. There are
                   5656: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
                   5657: Gforth (and most other systems) you can use the iors produced by various
                   5658: words as error numbers (e.g., a typical use of @code{allocate} is
                   5659: @code{allocate throw}).  Gforth also provides the word @code{exception}
                   5660: to define your own error numbers (with decent error reporting); an ANS
                   5661: Forth version of this word (but without the error messages) is available
                   5662: in @code{compat/except.fs}.  And finally, you can use your own error
1.68      anton    5663: numbers (anything outside the range -4095..0), but won't get nice error
                   5664: messages, only numbers.  For example, try:
                   5665: 
                   5666: @example
1.69      anton    5667: -10 throw                    \ ANS defined
                   5668: -267 throw                   \ system defined
                   5669: s" my error" exception throw \ user defined
                   5670: 7 throw                      \ arbitrary number
1.68      anton    5671: @end example
                   5672: 
                   5673: doc---exception-exception
1.1       anton    5674: 
1.69      anton    5675: A common idiom to @code{THROW} a specific error if a flag is true is
                   5676: this:
                   5677: 
                   5678: @example
                   5679: @code{( flag ) 0<> @i{errno} and throw}
                   5680: @end example
                   5681: 
                   5682: Your program can provide exception handlers to catch exceptions.  An
                   5683: exception handler can be used to correct the problem, or to clean up
                   5684: some data structures and just throw the exception to the next exception
                   5685: handler.  Note that @code{throw} jumps to the dynamically innermost
                   5686: exception handler.  The system's exception handler is outermost, and just
                   5687: prints an error and restarts command-line interpretation (or, in batch
                   5688: mode (i.e., while processing the shell command line), leaves Gforth).
1.1       anton    5689: 
1.68      anton    5690: The ANS Forth way to catch exceptions is @code{catch}:
1.1       anton    5691: 
1.68      anton    5692: doc-catch
1.160     anton    5693: doc-nothrow
1.68      anton    5694: 
                   5695: The most common use of exception handlers is to clean up the state when
                   5696: an error happens.  E.g.,
1.1       anton    5697: 
1.26      crook    5698: @example
1.68      anton    5699: base @ >r hex \ actually the hex should be inside foo, or we h
                   5700: ['] foo catch ( nerror|0 )
                   5701: r> base !
1.69      anton    5702: ( nerror|0 ) throw \ pass it on
1.26      crook    5703: @end example
1.1       anton    5704: 
1.69      anton    5705: A use of @code{catch} for handling the error @code{myerror} might look
                   5706: like this:
1.44      crook    5707: 
1.68      anton    5708: @example
1.69      anton    5709: ['] foo catch
                   5710: CASE
1.160     anton    5711:   myerror OF ... ( do something about it ) nothrow ENDOF
1.69      anton    5712:   dup throw \ default: pass other errors on, do nothing on non-errors
                   5713: ENDCASE
1.68      anton    5714: @end example
1.44      crook    5715: 
1.68      anton    5716: Having to wrap the code into a separate word is often cumbersome,
                   5717: therefore Gforth provides an alternative syntax:
1.1       anton    5718: 
                   5719: @example
1.69      anton    5720: TRY
1.68      anton    5721:   @i{code1}
1.172     anton    5722:   IFERROR
                   5723:     @i{code2}
                   5724:   THEN
                   5725:   @i{code3}
1.69      anton    5726: ENDTRY
1.1       anton    5727: @end example
                   5728: 
1.172     anton    5729: This performs @i{code1}.  If @i{code1} completes normally, execution
                   5730: continues with @i{code3}.  If @i{code1} or there is an exception
                   5731: before @code{endtry}, the stacks are reset to the state during
                   5732: @code{try}, the throw value is pushed on the data stack, and execution
                   5733: constinues at @i{code2}, and finally falls through the @i{code3}.
1.26      crook    5734: 
1.68      anton    5735: doc-try
                   5736: doc-endtry
1.172     anton    5737: doc-iferror
                   5738: 
                   5739: If you don't need @i{code2}, you can write @code{restore} instead of
                   5740: @code{iferror then}:
                   5741: 
                   5742: @example
                   5743: TRY
                   5744:   @i{code1}
                   5745: RESTORE
                   5746:   @i{code3}
                   5747: ENDTRY
                   5748: @end example
1.26      crook    5749: 
1.172     anton    5750: @cindex unwind-protect
1.69      anton    5751: The cleanup example from above in this syntax:
1.26      crook    5752: 
1.68      anton    5753: @example
1.174     anton    5754: base @@ @{ oldbase @}
1.172     anton    5755: TRY
1.68      anton    5756:   hex foo \ now the hex is placed correctly
1.69      anton    5757:   0       \ value for throw
1.172     anton    5758: RESTORE
                   5759:   oldbase base !
                   5760: ENDTRY
                   5761: throw
1.1       anton    5762: @end example
                   5763: 
1.172     anton    5764: An additional advantage of this variant is that an exception between
                   5765: @code{restore} and @code{endtry} (e.g., from the user pressing
                   5766: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
                   5767: so the base will be restored under all circumstances.
                   5768: 
                   5769: However, you have to ensure that this code does not cause an exception
                   5770: itself, otherwise the @code{iferror}/@code{restore} code will loop.
                   5771: Moreover, you should also make sure that the stack contents needed by
                   5772: the @code{iferror}/@code{restore} code exist everywhere between
                   5773: @code{try} and @code{endtry}; in our example this is achived by
                   5774: putting the data in a local before the @code{try} (you cannot use the
                   5775: return stack because the exception frame (@i{sys1}) is in the way
                   5776: there).
                   5777: 
                   5778: This kind of usage corresponds to Lisp's @code{unwind-protect}.
                   5779: 
                   5780: @cindex @code{recover} (old Gforth versions)
                   5781: If you do not want this exception-restarting behaviour, you achieve
                   5782: this as follows:
                   5783: 
                   5784: @example
                   5785: TRY
                   5786:   @i{code1}
                   5787: ENDTRY-IFERROR
                   5788:   @i{code2}
                   5789: THEN
                   5790: @end example
                   5791: 
                   5792: If there is an exception in @i{code1}, then @i{code2} is executed,
                   5793: otherwise execution continues behind the @code{then} (or in a possible
                   5794: @code{else} branch).  This corresponds to the construct
                   5795: 
                   5796: @example
                   5797: TRY
                   5798:   @i{code1}
                   5799: RECOVER
                   5800:   @i{code2}
                   5801: ENDTRY
                   5802: @end example
                   5803: 
                   5804: in Gforth before version 0.7.  So you can directly replace
                   5805: @code{recover}-using code; however, we recommend that you check if it
                   5806: would not be better to use one of the other @code{try} variants while
                   5807: you are at it.
                   5808: 
1.173     anton    5809: To ease the transition, Gforth provides two compatibility files:
                   5810: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
                   5811: ... then} syntax (but not @code{iferror} or @code{restore}) for old
                   5812: systems; @file{recover-endtry.fs} provides the @code{try ... recover
                   5813: ... endtry} syntax on new systems, so you can use that file as a
                   5814: stopgap to run old programs.  Both files work on any system (they just
                   5815: do nothing if the system already has the syntax it implements), so you
                   5816: can unconditionally @code{require} one of these files, even if you use
                   5817: a mix old and new systems.
                   5818: 
1.172     anton    5819: doc-restore
                   5820: doc-endtry-iferror
                   5821: 
                   5822: Here's the error handling example:
1.1       anton    5823: 
1.68      anton    5824: @example
1.69      anton    5825: TRY
1.68      anton    5826:   foo
1.172     anton    5827: ENDTRY-IFERROR
1.69      anton    5828:   CASE
1.160     anton    5829:     myerror OF ... ( do something about it ) nothrow ENDOF
1.69      anton    5830:     throw \ pass other errors on
                   5831:   ENDCASE
1.172     anton    5832: THEN
1.68      anton    5833: @end example
1.1       anton    5834: 
1.69      anton    5835: @progstyle
                   5836: As usual, you should ensure that the stack depth is statically known at
                   5837: the end: either after the @code{throw} for passing on errors, or after
                   5838: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
                   5839: selection construct for handling the error).
                   5840: 
1.68      anton    5841: There are two alternatives to @code{throw}: @code{Abort"} is conditional
                   5842: and you can provide an error message.  @code{Abort} just produces an
                   5843: ``Aborted'' error.
1.1       anton    5844: 
1.68      anton    5845: The problem with these words is that exception handlers cannot
                   5846: differentiate between different @code{abort"}s; they just look like
                   5847: @code{-2 throw} to them (the error message cannot be accessed by
                   5848: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
                   5849: exception handlers.
1.44      crook    5850: 
1.68      anton    5851: doc-abort"
1.26      crook    5852: doc-abort
1.29      crook    5853: 
                   5854: 
1.44      crook    5855: 
1.29      crook    5856: @c -------------------------------------------------------------
1.47      crook    5857: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29      crook    5858: @section Defining Words
                   5859: @cindex defining words
                   5860: 
1.47      crook    5861: Defining words are used to extend Forth by creating new entries in the dictionary.
                   5862: 
1.29      crook    5863: @menu
1.67      anton    5864: * CREATE::                      
1.44      crook    5865: * Variables::                   Variables and user variables
1.67      anton    5866: * Constants::                   
1.44      crook    5867: * Values::                      Initialised variables
1.67      anton    5868: * Colon Definitions::           
1.44      crook    5869: * Anonymous Definitions::       Definitions without names
1.69      anton    5870: * Supplying names::             Passing definition names as strings
1.67      anton    5871: * User-defined Defining Words::  
1.170     pazsan   5872: * Deferred Words::              Allow forward references
1.67      anton    5873: * Aliases::                     
1.29      crook    5874: @end menu
                   5875: 
1.44      crook    5876: @node CREATE, Variables, Defining Words, Defining Words
                   5877: @subsection @code{CREATE}
1.29      crook    5878: @cindex simple defining words
                   5879: @cindex defining words, simple
                   5880: 
                   5881: Defining words are used to create new entries in the dictionary. The
                   5882: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   5883: this:
                   5884: 
                   5885: @example
                   5886: CREATE new-word1
                   5887: @end example
                   5888: 
1.69      anton    5889: @code{CREATE} is a parsing word, i.e., it takes an argument from the
                   5890: input stream (@code{new-word1} in our example).  It generates a
                   5891: dictionary entry for @code{new-word1}. When @code{new-word1} is
                   5892: executed, all that it does is leave an address on the stack. The address
                   5893: represents the value of the data space pointer (@code{HERE}) at the time
                   5894: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
                   5895: associating a name with the address of a region of memory.
1.29      crook    5896: 
1.34      anton    5897: doc-create
                   5898: 
1.69      anton    5899: Note that in ANS Forth guarantees only for @code{create} that its body
                   5900: is in dictionary data space (i.e., where @code{here}, @code{allot}
                   5901: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
                   5902: @code{create}d words can be modified with @code{does>}
                   5903: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
                   5904: can only be applied to @code{create}d words.
                   5905: 
1.29      crook    5906: By extending this example to reserve some memory in data space, we end
1.69      anton    5907: up with something like a @i{variable}. Here are two different ways to do
                   5908: it:
1.29      crook    5909: 
                   5910: @example
                   5911: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   5912: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   5913: @end example
                   5914: 
                   5915: The variable can be examined and modified using @code{@@} (``fetch'') and
                   5916: @code{!} (``store'') like this:
                   5917: 
                   5918: @example
                   5919: new-word2 @@ .      \ get address, fetch from it and display
                   5920: 1234 new-word2 !   \ new value, get address, store to it
                   5921: @end example
                   5922: 
1.44      crook    5923: @cindex arrays
                   5924: A similar mechanism can be used to create arrays. For example, an
                   5925: 80-character text input buffer:
1.29      crook    5926: 
                   5927: @example
1.44      crook    5928: CREATE text-buf 80 chars allot
                   5929: 
1.168     anton    5930: text-buf 0 chars + c@@ \ the 1st character (offset 0)
                   5931: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44      crook    5932: @end example
1.29      crook    5933: 
1.44      crook    5934: You can build arbitrarily complex data structures by allocating
1.49      anton    5935: appropriate areas of memory. For further discussions of this, and to
1.66      anton    5936: learn about some Gforth tools that make it easier,
1.49      anton    5937: @xref{Structures}.
1.44      crook    5938: 
                   5939: 
                   5940: @node Variables, Constants, CREATE, Defining Words
                   5941: @subsection Variables
                   5942: @cindex variables
                   5943: 
                   5944: The previous section showed how a sequence of commands could be used to
                   5945: generate a variable.  As a final refinement, the whole code sequence can
                   5946: be wrapped up in a defining word (pre-empting the subject of the next
                   5947: section), making it easier to create new variables:
                   5948: 
                   5949: @example
                   5950: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
                   5951: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
                   5952: 
                   5953: myvariableX foo \ variable foo starts off with an unknown value
                   5954: myvariable0 joe \ whilst joe is initialised to 0
1.29      crook    5955: 
                   5956: 45 3 * foo !   \ set foo to 135
                   5957: 1234 joe !     \ set joe to 1234
                   5958: 3 joe +!       \ increment joe by 3.. to 1237
                   5959: @end example
                   5960: 
                   5961: Not surprisingly, there is no need to define @code{myvariable}, since
1.44      crook    5962: Forth already has a definition @code{Variable}. ANS Forth does not
1.69      anton    5963: guarantee that a @code{Variable} is initialised when it is created
                   5964: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
                   5965: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
                   5966: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47      crook    5967: @code{fvariable} for double and floating-point variables, respectively
1.69      anton    5968: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47      crook    5969: store a boolean, you can use @code{on} and @code{off} to toggle its
                   5970: state.
1.29      crook    5971: 
1.34      anton    5972: doc-variable
                   5973: doc-2variable
                   5974: doc-fvariable
                   5975: 
1.29      crook    5976: @cindex user variables
                   5977: @cindex user space
                   5978: The defining word @code{User} behaves in the same way as @code{Variable}.
                   5979: The difference is that it reserves space in @i{user (data) space} rather
                   5980: than normal data space. In a Forth system that has a multi-tasker, each
                   5981: task has its own set of user variables.
                   5982: 
1.34      anton    5983: doc-user
1.67      anton    5984: @c doc-udp
                   5985: @c doc-uallot
1.34      anton    5986: 
1.29      crook    5987: @comment TODO is that stuff about user variables strictly correct? Is it
                   5988: @comment just terminal tasks that have user variables?
                   5989: @comment should document tasker.fs (with some examples) elsewhere
                   5990: @comment in this manual, then expand on user space and user variables.
                   5991: 
1.44      crook    5992: @node Constants, Values, Variables, Defining Words
                   5993: @subsection Constants
                   5994: @cindex constants
                   5995: 
                   5996: @code{Constant} allows you to declare a fixed value and refer to it by
                   5997: name. For example:
1.29      crook    5998: 
                   5999: @example
                   6000: 12 Constant INCHES-PER-FOOT
                   6001: 3E+08 fconstant SPEED-O-LIGHT
                   6002: @end example
                   6003: 
                   6004: A @code{Variable} can be both read and written, so its run-time
                   6005: behaviour is to supply an address through which its current value can be
                   6006: manipulated. In contrast, the value of a @code{Constant} cannot be
                   6007: changed once it has been declared@footnote{Well, often it can be -- but
                   6008: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   6009: on).} so it's not necessary to supply the address -- it is more
                   6010: efficient to return the value of the constant directly. That's exactly
                   6011: what happens; the run-time effect of a constant is to put its value on
1.49      anton    6012: the top of the stack (You can find one
                   6013: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29      crook    6014: 
1.69      anton    6015: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29      crook    6016: double and floating-point constants, respectively.
                   6017: 
1.34      anton    6018: doc-constant
                   6019: doc-2constant
                   6020: doc-fconstant
                   6021: 
                   6022: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44      crook    6023: @c nac-> How could that not be true in an ANS Forth? You can't define a
                   6024: @c constant, use it and then delete the definition of the constant..
1.69      anton    6025: 
                   6026: @c anton->An ANS Forth system can compile a constant to a literal; On
                   6027: @c decompilation you would see only the number, just as if it had been used
                   6028: @c in the first place.  The word will stay, of course, but it will only be
                   6029: @c used by the text interpreter (no run-time duties, except when it is 
                   6030: @c POSTPONEd or somesuch).
                   6031: 
                   6032: @c nac:
1.44      crook    6033: @c I agree that it's rather deep, but IMO it is an important difference
                   6034: @c relative to other programming languages.. often it's annoying: it
                   6035: @c certainly changes my programming style relative to C.
                   6036: 
1.69      anton    6037: @c anton: In what way?
                   6038: 
1.29      crook    6039: Constants in Forth behave differently from their equivalents in other
                   6040: programming languages. In other languages, a constant (such as an EQU in
                   6041: assembler or a #define in C) only exists at compile-time; in the
                   6042: executable program the constant has been translated into an absolute
                   6043: number and, unless you are using a symbolic debugger, it's impossible to
                   6044: know what abstract thing that number represents. In Forth a constant has
1.44      crook    6045: an entry in the header space and remains there after the code that uses
                   6046: it has been defined. In fact, it must remain in the dictionary since it
                   6047: has run-time duties to perform. For example:
1.29      crook    6048: 
                   6049: @example
                   6050: 12 Constant INCHES-PER-FOOT
                   6051: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   6052: @end example
                   6053: 
                   6054: @cindex in-lining of constants
                   6055: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   6056: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   6057: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   6058: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   6059: attempt to optimise constants by in-lining them where they are used. You
                   6060: can force Gforth to in-line a constant like this:
                   6061: 
                   6062: @example
                   6063: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   6064: @end example
                   6065: 
                   6066: If you use @code{see} to decompile @i{this} version of
                   6067: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49      anton    6068: longer present. To understand how this works, read
                   6069: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29      crook    6070: 
                   6071: In-lining constants in this way might improve execution time
                   6072: fractionally, and can ensure that a constant is now only referenced at
                   6073: compile-time. However, the definition of the constant still remains in
                   6074: the dictionary. Some Forth compilers provide a mechanism for controlling
                   6075: a second dictionary for holding transient words such that this second
                   6076: dictionary can be deleted later in order to recover memory
                   6077: space. However, there is no standard way of doing this.
                   6078: 
                   6079: 
1.44      crook    6080: @node Values, Colon Definitions, Constants, Defining Words
                   6081: @subsection Values
                   6082: @cindex values
1.34      anton    6083: 
1.69      anton    6084: A @code{Value} behaves like a @code{Constant}, but it can be changed.
                   6085: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
                   6086: (not in ANS Forth) you can access (and change) a @code{value} also with
                   6087: @code{>body}.
                   6088: 
                   6089: Here are some
                   6090: examples:
1.29      crook    6091: 
                   6092: @example
1.69      anton    6093: 12 Value APPLES     \ Define APPLES with an initial value of 12
                   6094: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
                   6095: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
                   6096: APPLES              \ puts 35 on the top of the stack.
1.29      crook    6097: @end example
                   6098: 
1.44      crook    6099: doc-value
                   6100: doc-to
1.29      crook    6101: 
1.35      anton    6102: 
1.69      anton    6103: 
1.44      crook    6104: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
                   6105: @subsection Colon Definitions
                   6106: @cindex colon definitions
1.35      anton    6107: 
                   6108: @example
1.44      crook    6109: : name ( ... -- ... )
                   6110:     word1 word2 word3 ;
1.29      crook    6111: @end example
                   6112: 
1.44      crook    6113: @noindent
                   6114: Creates a word called @code{name} that, upon execution, executes
                   6115: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29      crook    6116: 
1.49      anton    6117: The explanation above is somewhat superficial. For simple examples of
                   6118: colon definitions see @ref{Your first definition}.  For an in-depth
1.66      anton    6119: discussion of some of the issues involved, @xref{Interpretation and
1.49      anton    6120: Compilation Semantics}.
1.29      crook    6121: 
1.44      crook    6122: doc-:
                   6123: doc-;
1.1       anton    6124: 
1.34      anton    6125: 
1.69      anton    6126: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44      crook    6127: @subsection Anonymous Definitions
                   6128: @cindex colon definitions
                   6129: @cindex defining words without name
1.34      anton    6130: 
1.44      crook    6131: Sometimes you want to define an @dfn{anonymous word}; a word without a
                   6132: name. You can do this with:
1.1       anton    6133: 
1.44      crook    6134: doc-:noname
1.1       anton    6135: 
1.44      crook    6136: This leaves the execution token for the word on the stack after the
                   6137: closing @code{;}. Here's an example in which a deferred word is
                   6138: initialised with an @code{xt} from an anonymous colon definition:
1.1       anton    6139: 
1.29      crook    6140: @example
1.44      crook    6141: Defer deferred
                   6142: :noname ( ... -- ... )
                   6143:   ... ;
                   6144: IS deferred
1.29      crook    6145: @end example
1.26      crook    6146: 
1.44      crook    6147: @noindent
                   6148: Gforth provides an alternative way of doing this, using two separate
                   6149: words:
1.27      crook    6150: 
1.44      crook    6151: doc-noname
                   6152: @cindex execution token of last defined word
1.116     anton    6153: doc-latestxt
1.1       anton    6154: 
1.44      crook    6155: @noindent
                   6156: The previous example can be rewritten using @code{noname} and
1.116     anton    6157: @code{latestxt}:
1.1       anton    6158: 
1.26      crook    6159: @example
1.44      crook    6160: Defer deferred
                   6161: noname : ( ... -- ... )
                   6162:   ... ;
1.116     anton    6163: latestxt IS deferred
1.26      crook    6164: @end example
1.1       anton    6165: 
1.29      crook    6166: @noindent
1.44      crook    6167: @code{noname} works with any defining word, not just @code{:}.
                   6168: 
1.116     anton    6169: @code{latestxt} also works when the last word was not defined as
1.71      anton    6170: @code{noname}.  It does not work for combined words, though.  It also has
                   6171: the useful property that is is valid as soon as the header for a
                   6172: definition has been built. Thus:
1.44      crook    6173: 
                   6174: @example
1.116     anton    6175: latestxt . : foo [ latestxt . ] ; ' foo .
1.44      crook    6176: @end example
1.1       anton    6177: 
1.44      crook    6178: @noindent
                   6179: prints 3 numbers; the last two are the same.
1.26      crook    6180: 
1.69      anton    6181: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
                   6182: @subsection Supplying the name of a defined word
                   6183: @cindex names for defined words
                   6184: @cindex defining words, name given in a string
                   6185: 
                   6186: By default, a defining word takes the name for the defined word from the
                   6187: input stream. Sometimes you want to supply the name from a string. You
                   6188: can do this with:
                   6189: 
                   6190: doc-nextname
                   6191: 
                   6192: For example:
                   6193: 
                   6194: @example
                   6195: s" foo" nextname create
                   6196: @end example
                   6197: 
                   6198: @noindent
                   6199: is equivalent to:
                   6200: 
                   6201: @example
                   6202: create foo
                   6203: @end example
                   6204: 
                   6205: @noindent
                   6206: @code{nextname} works with any defining word.
                   6207: 
1.1       anton    6208: 
1.170     pazsan   6209: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26      crook    6210: @subsection User-defined Defining Words
                   6211: @cindex user-defined defining words
                   6212: @cindex defining words, user-defined
1.1       anton    6213: 
1.29      crook    6214: You can create a new defining word by wrapping defining-time code around
                   6215: an existing defining word and putting the sequence in a colon
1.69      anton    6216: definition. 
                   6217: 
                   6218: @c anton: This example is very complex and leads in a quite different
                   6219: @c direction from the CREATE-DOES> stuff that follows.  It should probably
                   6220: @c be done elsewhere, or as a subsubsection of this subsection (or as a
                   6221: @c subsection of Defining Words)
                   6222: 
                   6223: For example, suppose that you have a word @code{stats} that
1.29      crook    6224: gathers statistics about colon definitions given the @i{xt} of the
                   6225: definition, and you want every colon definition in your application to
                   6226: make a call to @code{stats}. You can define and use a new version of
                   6227: @code{:} like this:
                   6228: 
                   6229: @example
                   6230: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   6231:   ... ;  \ other code
                   6232: 
1.116     anton    6233: : my: : latestxt postpone literal ['] stats compile, ;
1.29      crook    6234: 
                   6235: my: foo + - ;
                   6236: @end example
                   6237: 
                   6238: When @code{foo} is defined using @code{my:} these steps occur:
                   6239: 
                   6240: @itemize @bullet
                   6241: @item
                   6242: @code{my:} is executed.
                   6243: @item
                   6244: The @code{:} within the definition (the one between @code{my:} and
1.116     anton    6245: @code{latestxt}) is executed, and does just what it always does; it parses
1.29      crook    6246: the input stream for a name, builds a dictionary header for the name
                   6247: @code{foo} and switches @code{state} from interpret to compile.
                   6248: @item
1.116     anton    6249: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29      crook    6250: being defined -- @code{foo} -- onto the stack.
                   6251: @item
                   6252: The code that was produced by @code{postpone literal} is executed; this
                   6253: causes the value on the stack to be compiled as a literal in the code
                   6254: area of @code{foo}.
                   6255: @item
                   6256: The code @code{['] stats} compiles a literal into the definition of
                   6257: @code{my:}. When @code{compile,} is executed, that literal -- the
                   6258: execution token for @code{stats} -- is layed down in the code area of
                   6259: @code{foo} , following the literal@footnote{Strictly speaking, the
                   6260: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   6261: in the code area is implementation-dependent. A threaded implementation
                   6262: might spit out the execution token directly whilst another
                   6263: implementation might spit out a native code sequence.}.
                   6264: @item
                   6265: At this point, the execution of @code{my:} is complete, and control
                   6266: returns to the text interpreter. The text interpreter is in compile
                   6267: state, so subsequent text @code{+ -} is compiled into the definition of
                   6268: @code{foo} and the @code{;} terminates the definition as always.
                   6269: @end itemize
                   6270: 
                   6271: You can use @code{see} to decompile a word that was defined using
                   6272: @code{my:} and see how it is different from a normal @code{:}
                   6273: definition. For example:
                   6274: 
                   6275: @example
                   6276: : bar + - ;  \ like foo but using : rather than my:
                   6277: see bar
                   6278: : bar
                   6279:   + - ;
                   6280: see foo
                   6281: : foo
                   6282:   107645672 stats + - ;
                   6283: 
1.140     anton    6284: \ use ' foo . to show that 107645672 is the xt for foo
1.29      crook    6285: @end example
                   6286: 
                   6287: You can use techniques like this to make new defining words in terms of
                   6288: @i{any} existing defining word.
1.1       anton    6289: 
                   6290: 
1.29      crook    6291: @cindex defining defining words
1.26      crook    6292: @cindex @code{CREATE} ... @code{DOES>}
                   6293: If you want the words defined with your defining words to behave
                   6294: differently from words defined with standard defining words, you can
                   6295: write your defining word like this:
1.1       anton    6296: 
                   6297: @example
1.26      crook    6298: : def-word ( "name" -- )
1.29      crook    6299:     CREATE @i{code1}
1.26      crook    6300: DOES> ( ... -- ... )
1.29      crook    6301:     @i{code2} ;
1.26      crook    6302: 
                   6303: def-word name
1.1       anton    6304: @end example
                   6305: 
1.29      crook    6306: @cindex child words
                   6307: This fragment defines a @dfn{defining word} @code{def-word} and then
                   6308: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   6309: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   6310: is not executed at this time. The word @code{name} is sometimes called a
                   6311: @dfn{child} of @code{def-word}.
                   6312: 
                   6313: When you execute @code{name}, the address of the body of @code{name} is
                   6314: put on the data stack and @i{code2} is executed (the address of the body
                   6315: of @code{name} is the address @code{HERE} returns immediately after the
1.69      anton    6316: @code{CREATE}, i.e., the address a @code{create}d word returns by
                   6317: default).
                   6318: 
                   6319: @c anton:
                   6320: @c www.dictionary.com says:
                   6321: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
                   6322: @c several generations of absence, usually caused by the chance
                   6323: @c recombination of genes.  2.An individual or a part that exhibits
                   6324: @c atavism. Also called throwback.  3.The return of a trait or recurrence
                   6325: @c of previous behavior after a period of absence.
                   6326: @c
                   6327: @c Doesn't seem to fit.
1.29      crook    6328: 
1.69      anton    6329: @c @cindex atavism in child words
1.33      anton    6330: You can use @code{def-word} to define a set of child words that behave
1.69      anton    6331: similarly; they all have a common run-time behaviour determined by
                   6332: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
                   6333: body of the child word. The structure of the data is common to all
                   6334: children of @code{def-word}, but the data values are specific -- and
                   6335: private -- to each child word. When a child word is executed, the
                   6336: address of its private data area is passed as a parameter on TOS to be
                   6337: used and manipulated@footnote{It is legitimate both to read and write to
                   6338: this data area.} by @i{code2}.
1.29      crook    6339: 
                   6340: The two fragments of code that make up the defining words act (are
                   6341: executed) at two completely separate times:
1.1       anton    6342: 
1.29      crook    6343: @itemize @bullet
                   6344: @item
                   6345: At @i{define time}, the defining word executes @i{code1} to generate a
                   6346: child word
                   6347: @item
                   6348: At @i{child execution time}, when a child word is invoked, @i{code2}
                   6349: is executed, using parameters (data) that are private and specific to
                   6350: the child word.
                   6351: @end itemize
                   6352: 
1.44      crook    6353: Another way of understanding the behaviour of @code{def-word} and
                   6354: @code{name} is to say that, if you make the following definitions:
1.33      anton    6355: @example
                   6356: : def-word1 ( "name" -- )
                   6357:     CREATE @i{code1} ;
                   6358: 
                   6359: : action1 ( ... -- ... )
                   6360:     @i{code2} ;
                   6361: 
                   6362: def-word1 name1
                   6363: @end example
                   6364: 
1.44      crook    6365: @noindent
                   6366: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    6367: 
1.29      crook    6368: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    6369: 
1.1       anton    6370: @example
1.29      crook    6371: : CONSTANT ( w "name" -- )
                   6372:     CREATE ,
1.26      crook    6373: DOES> ( -- w )
                   6374:     @@ ;
1.1       anton    6375: @end example
                   6376: 
1.29      crook    6377: @comment There is a beautiful description of how this works and what
                   6378: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   6379: @comment commentary on the Counting Fruits problem.
                   6380: 
                   6381: When you create a constant with @code{5 CONSTANT five}, a set of
                   6382: define-time actions take place; first a new word @code{five} is created,
                   6383: then the value 5 is laid down in the body of @code{five} with
1.44      crook    6384: @code{,}. When @code{five} is executed, the address of the body is put on
1.29      crook    6385: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   6386: no code of its own; it simply contains a data field and a pointer to the
                   6387: code that follows @code{DOES>} in its defining word. That makes words
                   6388: created in this way very compact.
                   6389: 
                   6390: The final example in this section is intended to remind you that space
                   6391: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   6392: both read and written by a Standard program@footnote{Exercise: use this
                   6393: example as a starting point for your own implementation of @code{Value}
                   6394: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   6395: @code{[']}.}:
                   6396: 
                   6397: @example
                   6398: : foo ( "name" -- )
                   6399:     CREATE -1 ,
                   6400: DOES> ( -- )
1.33      anton    6401:     @@ . ;
1.29      crook    6402: 
                   6403: foo first-word
                   6404: foo second-word
                   6405: 
                   6406: 123 ' first-word >BODY !
                   6407: @end example
                   6408: 
                   6409: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   6410: have executed it to get the address of its data field. However, since it
                   6411: was defined to have @code{DOES>} actions, its execution semantics are to
                   6412: perform those @code{DOES>} actions. To get the address of its data field
                   6413: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   6414: translate the xt into the address of the data field.  When you execute
                   6415: @code{first-word}, it will display @code{123}. When you execute
                   6416: @code{second-word} it will display @code{-1}.
1.26      crook    6417: 
                   6418: @cindex stack effect of @code{DOES>}-parts
                   6419: @cindex @code{DOES>}-parts, stack effect
1.29      crook    6420: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    6421: the stack effect of the defined words, not the stack effect of the
                   6422: following code (the following code expects the address of the body on
                   6423: the top of stack, which is not reflected in the stack comment). This is
                   6424: the convention that I use and recommend (it clashes a bit with using
                   6425: locals declarations for stack effect specification, though).
1.1       anton    6426: 
1.53      anton    6427: @menu
                   6428: * CREATE..DOES> applications::  
                   6429: * CREATE..DOES> details::       
1.63      anton    6430: * Advanced does> usage example::  
1.155     anton    6431: * Const-does>::                 
1.53      anton    6432: @end menu
                   6433: 
                   6434: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26      crook    6435: @subsubsection Applications of @code{CREATE..DOES>}
                   6436: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    6437: 
1.26      crook    6438: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    6439: 
1.26      crook    6440: @cindex factoring similar colon definitions
                   6441: When you see a sequence of code occurring several times, and you can
                   6442: identify a meaning, you will factor it out as a colon definition. When
                   6443: you see similar colon definitions, you can factor them using
                   6444: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   6445: that look very similar:
1.1       anton    6446: @example
1.26      crook    6447: : ori, ( reg-target reg-source n -- )
                   6448:     0 asm-reg-reg-imm ;
                   6449: : andi, ( reg-target reg-source n -- )
                   6450:     1 asm-reg-reg-imm ;
1.1       anton    6451: @end example
                   6452: 
1.26      crook    6453: @noindent
                   6454: This could be factored with:
                   6455: @example
                   6456: : reg-reg-imm ( op-code -- )
                   6457:     CREATE ,
                   6458: DOES> ( reg-target reg-source n -- )
                   6459:     @@ asm-reg-reg-imm ;
                   6460: 
                   6461: 0 reg-reg-imm ori,
                   6462: 1 reg-reg-imm andi,
                   6463: @end example
1.1       anton    6464: 
1.26      crook    6465: @cindex currying
                   6466: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   6467: supply a part of the parameters for a word (known as @dfn{currying} in
                   6468: the functional language community). E.g., @code{+} needs two
                   6469: parameters. Creating versions of @code{+} with one parameter fixed can
                   6470: be done like this:
1.82      anton    6471: 
1.1       anton    6472: @example
1.82      anton    6473: : curry+ ( n1 "name" -- )
1.26      crook    6474:     CREATE ,
                   6475: DOES> ( n2 -- n1+n2 )
                   6476:     @@ + ;
                   6477: 
                   6478:  3 curry+ 3+
                   6479: -2 curry+ 2-
1.1       anton    6480: @end example
                   6481: 
1.91      anton    6482: 
1.63      anton    6483: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26      crook    6484: @subsubsection The gory details of @code{CREATE..DOES>}
                   6485: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    6486: 
1.26      crook    6487: doc-does>
1.1       anton    6488: 
1.26      crook    6489: @cindex @code{DOES>} in a separate definition
                   6490: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   6491: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    6492: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    6493: @example
                   6494: : does1 
                   6495: DOES> ( ... -- ... )
1.44      crook    6496:     ... ;
                   6497: 
                   6498: : does2
                   6499: DOES> ( ... -- ... )
                   6500:     ... ;
                   6501: 
                   6502: : def-word ( ... -- ... )
                   6503:     create ...
                   6504:     IF
                   6505:        does1
                   6506:     ELSE
                   6507:        does2
                   6508:     ENDIF ;
                   6509: @end example
                   6510: 
                   6511: In this example, the selection of whether to use @code{does1} or
1.69      anton    6512: @code{does2} is made at definition-time; at the time that the child word is
1.44      crook    6513: @code{CREATE}d.
                   6514: 
                   6515: @cindex @code{DOES>} in interpretation state
                   6516: In a standard program you can apply a @code{DOES>}-part only if the last
                   6517: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   6518: will override the behaviour of the last word defined in any case. In a
                   6519: standard program, you can use @code{DOES>} only in a colon
                   6520: definition. In Gforth, you can also use it in interpretation state, in a
                   6521: kind of one-shot mode; for example:
                   6522: @example
                   6523: CREATE name ( ... -- ... )
                   6524:   @i{initialization}
                   6525: DOES>
                   6526:   @i{code} ;
                   6527: @end example
                   6528: 
                   6529: @noindent
                   6530: is equivalent to the standard:
                   6531: @example
                   6532: :noname
                   6533: DOES>
                   6534:     @i{code} ;
                   6535: CREATE name EXECUTE ( ... -- ... )
                   6536:     @i{initialization}
                   6537: @end example
                   6538: 
1.53      anton    6539: doc->body
                   6540: 
1.152     pazsan   6541: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63      anton    6542: @subsubsection Advanced does> usage example
                   6543: 
                   6544: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
                   6545: for disassembling instructions, that follow a very repetetive scheme:
                   6546: 
                   6547: @example
                   6548: :noname @var{disasm-operands} s" @var{inst-name}" type ;
                   6549: @var{entry-num} cells @var{table} + !
                   6550: @end example
                   6551: 
                   6552: Of course, this inspires the idea to factor out the commonalities to
                   6553: allow a definition like
                   6554: 
                   6555: @example
                   6556: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
                   6557: @end example
                   6558: 
                   6559: The parameters @var{disasm-operands} and @var{table} are usually
1.69      anton    6560: correlated.  Moreover, before I wrote the disassembler, there already
                   6561: existed code that defines instructions like this:
1.63      anton    6562: 
                   6563: @example
                   6564: @var{entry-num} @var{inst-format} @var{inst-name}
                   6565: @end example
                   6566: 
                   6567: This code comes from the assembler and resides in
                   6568: @file{arch/mips/insts.fs}.
                   6569: 
                   6570: So I had to define the @var{inst-format} words that performed the scheme
                   6571: above when executed.  At first I chose to use run-time code-generation:
                   6572: 
                   6573: @example
                   6574: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
                   6575:   :noname Postpone @var{disasm-operands}
                   6576:   name Postpone sliteral Postpone type Postpone ;
                   6577:   swap cells @var{table} + ! ;
                   6578: @end example
                   6579: 
                   6580: Note that this supplies the other two parameters of the scheme above.
1.44      crook    6581: 
1.63      anton    6582: An alternative would have been to write this using
                   6583: @code{create}/@code{does>}:
                   6584: 
                   6585: @example
                   6586: : @var{inst-format} ( entry-num "name" -- )
                   6587:   here name string, ( entry-num c-addr ) \ parse and save "name"
                   6588:   noname create , ( entry-num )
1.116     anton    6589:   latestxt swap cells @var{table} + !
1.63      anton    6590: does> ( addr w -- )
                   6591:   \ disassemble instruction w at addr
                   6592:   @@ >r 
                   6593:   @var{disasm-operands}
                   6594:   r> count type ;
                   6595: @end example
                   6596: 
                   6597: Somehow the first solution is simpler, mainly because it's simpler to
                   6598: shift a string from definition-time to use-time with @code{sliteral}
                   6599: than with @code{string,} and friends.
                   6600: 
                   6601: I wrote a lot of words following this scheme and soon thought about
                   6602: factoring out the commonalities among them.  Note that this uses a
                   6603: two-level defining word, i.e., a word that defines ordinary defining
                   6604: words.
                   6605: 
                   6606: This time a solution involving @code{postpone} and friends seemed more
                   6607: difficult (try it as an exercise), so I decided to use a
                   6608: @code{create}/@code{does>} word; since I was already at it, I also used
                   6609: @code{create}/@code{does>} for the lower level (try using
                   6610: @code{postpone} etc. as an exercise), resulting in the following
                   6611: definition:
                   6612: 
                   6613: @example
                   6614: : define-format ( disasm-xt table-xt -- )
                   6615:     \ define an instruction format that uses disasm-xt for
                   6616:     \ disassembling and enters the defined instructions into table
                   6617:     \ table-xt
                   6618:     create 2,
                   6619: does> ( u "inst" -- )
                   6620:     \ defines an anonymous word for disassembling instruction inst,
                   6621:     \ and enters it as u-th entry into table-xt
                   6622:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
                   6623:     noname create 2,      \ define anonymous word
1.116     anton    6624:     execute latestxt swap ! \ enter xt of defined word into table-xt
1.63      anton    6625: does> ( addr w -- )
                   6626:     \ disassemble instruction w at addr
                   6627:     2@@ >r ( addr w disasm-xt R: c-addr )
                   6628:     execute ( R: c-addr ) \ disassemble operands
                   6629:     r> count type ; \ print name 
                   6630: @end example
                   6631: 
                   6632: Note that the tables here (in contrast to above) do the @code{cells +}
                   6633: by themselves (that's why you have to pass an xt).  This word is used in
                   6634: the following way:
                   6635: 
                   6636: @example
                   6637: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
                   6638: @end example
                   6639: 
1.71      anton    6640: As shown above, the defined instruction format is then used like this:
                   6641: 
                   6642: @example
                   6643: @var{entry-num} @var{inst-format} @var{inst-name}
                   6644: @end example
                   6645: 
1.63      anton    6646: In terms of currying, this kind of two-level defining word provides the
                   6647: parameters in three stages: first @var{disasm-operands} and @var{table},
                   6648: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
                   6649: the instruction to be disassembled.  
                   6650: 
                   6651: Of course this did not quite fit all the instruction format names used
                   6652: in @file{insts.fs}, so I had to define a few wrappers that conditioned
                   6653: the parameters into the right form.
                   6654: 
                   6655: If you have trouble following this section, don't worry.  First, this is
                   6656: involved and takes time (and probably some playing around) to
                   6657: understand; second, this is the first two-level
                   6658: @code{create}/@code{does>} word I have written in seventeen years of
                   6659: Forth; and if I did not have @file{insts.fs} to start with, I may well
                   6660: have elected to use just a one-level defining word (with some repeating
                   6661: of parameters when using the defining word). So it is not necessary to
                   6662: understand this, but it may improve your understanding of Forth.
1.44      crook    6663: 
                   6664: 
1.152     pazsan   6665: @node Const-does>,  , Advanced does> usage example, User-defined Defining Words
1.91      anton    6666: @subsubsection @code{Const-does>}
                   6667: 
                   6668: A frequent use of @code{create}...@code{does>} is for transferring some
                   6669: values from definition-time to run-time.  Gforth supports this use with
                   6670: 
                   6671: doc-const-does>
                   6672: 
                   6673: A typical use of this word is:
                   6674: 
                   6675: @example
                   6676: : curry+ ( n1 "name" -- )
                   6677: 1 0 CONST-DOES> ( n2 -- n1+n2 )
                   6678:     + ;
                   6679: 
                   6680: 3 curry+ 3+
                   6681: @end example
                   6682: 
                   6683: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
                   6684: definition to run-time.
                   6685: 
                   6686: The advantages of using @code{const-does>} are:
                   6687: 
                   6688: @itemize
                   6689: 
                   6690: @item
                   6691: You don't have to deal with storing and retrieving the values, i.e.,
                   6692: your program becomes more writable and readable.
                   6693: 
                   6694: @item
                   6695: When using @code{does>}, you have to introduce a @code{@@} that cannot
                   6696: be optimized away (because you could change the data using
                   6697: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
                   6698: 
                   6699: @end itemize
                   6700: 
                   6701: An ANS Forth implementation of @code{const-does>} is available in
                   6702: @file{compat/const-does.fs}.
                   6703: 
                   6704: 
1.170     pazsan   6705: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
                   6706: @subsection Deferred Words
1.44      crook    6707: @cindex deferred words
                   6708: 
                   6709: The defining word @code{Defer} allows you to define a word by name
                   6710: without defining its behaviour; the definition of its behaviour is
                   6711: deferred. Here are two situation where this can be useful:
                   6712: 
                   6713: @itemize @bullet
                   6714: @item
                   6715: Where you want to allow the behaviour of a word to be altered later, and
                   6716: for all precompiled references to the word to change when its behaviour
                   6717: is changed.
                   6718: @item
                   6719: For mutual recursion; @xref{Calls and returns}.
                   6720: @end itemize
                   6721: 
                   6722: In the following example, @code{foo} always invokes the version of
                   6723: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
                   6724: always invokes the version that prints ``@code{Hello}''. There is no way
                   6725: of getting @code{foo} to use the later version without re-ordering the
                   6726: source code and recompiling it.
                   6727: 
                   6728: @example
                   6729: : greet ." Good morning" ;
                   6730: : foo ... greet ... ;
                   6731: : greet ." Hello" ;
                   6732: : bar ... greet ... ;
                   6733: @end example
                   6734: 
                   6735: This problem can be solved by defining @code{greet} as a @code{Defer}red
                   6736: word. The behaviour of a @code{Defer}red word can be defined and
                   6737: redefined at any time by using @code{IS} to associate the xt of a
                   6738: previously-defined word with it. The previous example becomes:
                   6739: 
                   6740: @example
1.69      anton    6741: Defer greet ( -- )
1.44      crook    6742: : foo ... greet ... ;
                   6743: : bar ... greet ... ;
1.69      anton    6744: : greet1 ( -- ) ." Good morning" ;
                   6745: : greet2 ( -- ) ." Hello" ;
1.132     anton    6746: ' greet2 IS greet  \ make greet behave like greet2
1.44      crook    6747: @end example
                   6748: 
1.69      anton    6749: @progstyle
                   6750: You should write a stack comment for every deferred word, and put only
                   6751: XTs into deferred words that conform to this stack effect.  Otherwise
                   6752: it's too difficult to use the deferred word.
                   6753: 
1.44      crook    6754: A deferred word can be used to improve the statistics-gathering example
                   6755: from @ref{User-defined Defining Words}; rather than edit the
                   6756: application's source code to change every @code{:} to a @code{my:}, do
                   6757: this:
                   6758: 
                   6759: @example
                   6760: : real: : ;     \ retain access to the original
                   6761: defer :         \ redefine as a deferred word
1.132     anton    6762: ' my: IS :      \ use special version of :
1.44      crook    6763: \
                   6764: \ load application here
                   6765: \
1.132     anton    6766: ' real: IS :    \ go back to the original
1.44      crook    6767: @end example
                   6768: 
                   6769: 
1.132     anton    6770: One thing to note is that @code{IS} has special compilation semantics,
                   6771: such that it parses the name at compile time (like @code{TO}):
1.44      crook    6772: 
                   6773: @example
                   6774: : set-greet ( xt -- )
1.132     anton    6775:   IS greet ;
1.44      crook    6776: 
                   6777: ' greet1 set-greet
                   6778: @end example
                   6779: 
1.132     anton    6780: In situations where @code{IS} does not fit, use @code{defer!} instead.
                   6781: 
1.69      anton    6782: A deferred word can only inherit execution semantics from the xt
                   6783: (because that is all that an xt can represent -- for more discussion of
                   6784: this @pxref{Tokens for Words}); by default it will have default
                   6785: interpretation and compilation semantics deriving from this execution
                   6786: semantics.  However, you can change the interpretation and compilation
                   6787: semantics of the deferred word in the usual ways:
1.44      crook    6788: 
                   6789: @example
1.132     anton    6790: : bar .... ; immediate
1.44      crook    6791: Defer fred immediate
                   6792: Defer jim
                   6793: 
1.132     anton    6794: ' bar IS jim  \ jim has default semantics
                   6795: ' bar IS fred \ fred is immediate
1.44      crook    6796: @end example
                   6797: 
                   6798: doc-defer
1.132     anton    6799: doc-defer!
1.44      crook    6800: doc-is
1.132     anton    6801: doc-defer@
                   6802: doc-action-of
1.44      crook    6803: @comment TODO document these: what's defers [is]
                   6804: doc-defers
                   6805: 
                   6806: @c Use @code{words-deferred} to see a list of deferred words.
                   6807: 
1.132     anton    6808: Definitions of these words (except @code{defers}) in ANS Forth are
                   6809: provided in @file{compat/defer.fs}.
1.44      crook    6810: 
                   6811: 
1.170     pazsan   6812: @node Aliases,  , Deferred Words, Defining Words
1.44      crook    6813: @subsection Aliases
                   6814: @cindex aliases
1.1       anton    6815: 
1.44      crook    6816: The defining word @code{Alias} allows you to define a word by name that
                   6817: has the same behaviour as some other word. Here are two situation where
                   6818: this can be useful:
1.1       anton    6819: 
1.44      crook    6820: @itemize @bullet
                   6821: @item
                   6822: When you want access to a word's definition from a different word list
                   6823: (for an example of this, see the definition of the @code{Root} word list
                   6824: in the Gforth source).
                   6825: @item
                   6826: When you want to create a synonym; a definition that can be known by
                   6827: either of two names (for example, @code{THEN} and @code{ENDIF} are
                   6828: aliases).
                   6829: @end itemize
1.1       anton    6830: 
1.69      anton    6831: Like deferred words, an alias has default compilation and interpretation
                   6832: semantics at the beginning (not the modifications of the other word),
                   6833: but you can change them in the usual ways (@code{immediate},
                   6834: @code{compile-only}). For example:
1.1       anton    6835: 
                   6836: @example
1.44      crook    6837: : foo ... ; immediate
                   6838: 
                   6839: ' foo Alias bar \ bar is not an immediate word
                   6840: ' foo Alias fooby immediate \ fooby is an immediate word
1.1       anton    6841: @end example
                   6842: 
1.44      crook    6843: Words that are aliases have the same xt, different headers in the
                   6844: dictionary, and consequently different name tokens (@pxref{Tokens for
                   6845: Words}) and possibly different immediate flags.  An alias can only have
                   6846: default or immediate compilation semantics; you can define aliases for
                   6847: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1       anton    6848: 
1.44      crook    6849: doc-alias
1.1       anton    6850: 
                   6851: 
1.47      crook    6852: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
                   6853: @section Interpretation and Compilation Semantics
1.26      crook    6854: @cindex semantics, interpretation and compilation
1.1       anton    6855: 
1.71      anton    6856: @c !! state and ' are used without explanation
                   6857: @c example for immediate/compile-only? or is the tutorial enough
                   6858: 
1.26      crook    6859: @cindex interpretation semantics
1.71      anton    6860: The @dfn{interpretation semantics} of a (named) word are what the text
1.26      crook    6861: interpreter does when it encounters the word in interpret state. It also
                   6862: appears in some other contexts, e.g., the execution token returned by
1.71      anton    6863: @code{' @i{word}} identifies the interpretation semantics of @i{word}
                   6864: (in other words, @code{' @i{word} execute} is equivalent to
1.29      crook    6865: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    6866: 
1.26      crook    6867: @cindex compilation semantics
1.71      anton    6868: The @dfn{compilation semantics} of a (named) word are what the text
                   6869: interpreter does when it encounters the word in compile state. It also
                   6870: appears in other contexts, e.g, @code{POSTPONE @i{word}}
                   6871: compiles@footnote{In standard terminology, ``appends to the current
                   6872: definition''.} the compilation semantics of @i{word}.
1.1       anton    6873: 
1.26      crook    6874: @cindex execution semantics
                   6875: The standard also talks about @dfn{execution semantics}. They are used
                   6876: only for defining the interpretation and compilation semantics of many
                   6877: words. By default, the interpretation semantics of a word are to
                   6878: @code{execute} its execution semantics, and the compilation semantics of
                   6879: a word are to @code{compile,} its execution semantics.@footnote{In
                   6880: standard terminology: The default interpretation semantics are its
                   6881: execution semantics; the default compilation semantics are to append its
                   6882: execution semantics to the execution semantics of the current
                   6883: definition.}
                   6884: 
1.71      anton    6885: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
                   6886: the text interpreter, ticked, or @code{postpone}d, so they have no
                   6887: interpretation or compilation semantics.  Their behaviour is represented
                   6888: by their XT (@pxref{Tokens for Words}), and we call it execution
                   6889: semantics, too.
                   6890: 
1.26      crook    6891: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   6892: 
                   6893: @cindex immediate words
                   6894: @cindex compile-only words
                   6895: You can change the semantics of the most-recently defined word:
                   6896: 
1.44      crook    6897: 
1.26      crook    6898: doc-immediate
                   6899: doc-compile-only
                   6900: doc-restrict
                   6901: 
1.82      anton    6902: By convention, words with non-default compilation semantics (e.g.,
                   6903: immediate words) often have names surrounded with brackets (e.g.,
                   6904: @code{[']}, @pxref{Execution token}).
1.44      crook    6905: 
1.26      crook    6906: Note that ticking (@code{'}) a compile-only word gives an error
                   6907: (``Interpreting a compile-only word'').
1.1       anton    6908: 
1.47      crook    6909: @menu
1.67      anton    6910: * Combined words::              
1.47      crook    6911: @end menu
1.44      crook    6912: 
1.71      anton    6913: 
1.48      anton    6914: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44      crook    6915: @subsection Combined Words
                   6916: @cindex combined words
                   6917: 
                   6918: Gforth allows you to define @dfn{combined words} -- words that have an
                   6919: arbitrary combination of interpretation and compilation semantics.
                   6920: 
1.26      crook    6921: doc-interpret/compile:
1.1       anton    6922: 
1.26      crook    6923: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   6924: recommend that you do not define such words, as cute as they may be:
                   6925: they make it hard to get at both parts of the word in some contexts.
                   6926: E.g., assume you want to get an execution token for the compilation
                   6927: part. Instead, define two words, one that embodies the interpretation
                   6928: part, and one that embodies the compilation part.  Once you have done
                   6929: that, you can define a combined word with @code{interpret/compile:} for
                   6930: the convenience of your users.
1.1       anton    6931: 
1.26      crook    6932: You might try to use this feature to provide an optimizing
                   6933: implementation of the default compilation semantics of a word. For
                   6934: example, by defining:
1.1       anton    6935: @example
1.26      crook    6936: :noname
                   6937:    foo bar ;
                   6938: :noname
                   6939:    POSTPONE foo POSTPONE bar ;
1.29      crook    6940: interpret/compile: opti-foobar
1.1       anton    6941: @end example
1.26      crook    6942: 
1.23      crook    6943: @noindent
1.26      crook    6944: as an optimizing version of:
                   6945: 
1.1       anton    6946: @example
1.26      crook    6947: : foobar
                   6948:     foo bar ;
1.1       anton    6949: @end example
                   6950: 
1.26      crook    6951: Unfortunately, this does not work correctly with @code{[compile]},
                   6952: because @code{[compile]} assumes that the compilation semantics of all
                   6953: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    6954: opti-foobar} would compile compilation semantics, whereas
                   6955: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    6956: 
1.26      crook    6957: @cindex state-smart words (are a bad idea)
1.82      anton    6958: @anchor{state-smartness}
1.29      crook    6959: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    6960: by @code{interpret/compile:} (words are state-smart if they check
                   6961: @code{STATE} during execution). E.g., they would try to code
                   6962: @code{foobar} like this:
1.1       anton    6963: 
1.26      crook    6964: @example
                   6965: : foobar
                   6966:   STATE @@
                   6967:   IF ( compilation state )
                   6968:     POSTPONE foo POSTPONE bar
                   6969:   ELSE
                   6970:     foo bar
                   6971:   ENDIF ; immediate
                   6972: @end example
1.1       anton    6973: 
1.26      crook    6974: Although this works if @code{foobar} is only processed by the text
                   6975: interpreter, it does not work in other contexts (like @code{'} or
                   6976: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   6977: for a state-smart word, not for the interpretation semantics of the
                   6978: original @code{foobar}; when you execute this execution token (directly
                   6979: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   6980: state, the result will not be what you expected (i.e., it will not
                   6981: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   6982: write them@footnote{For a more detailed discussion of this topic, see
1.66      anton    6983: M. Anton Ertl,
                   6984: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
                   6985: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1       anton    6986: 
1.26      crook    6987: @cindex defining words with arbitrary semantics combinations
                   6988: It is also possible to write defining words that define words with
                   6989: arbitrary combinations of interpretation and compilation semantics. In
                   6990: general, they look like this:
1.1       anton    6991: 
1.26      crook    6992: @example
                   6993: : def-word
                   6994:     create-interpret/compile
1.29      crook    6995:     @i{code1}
1.26      crook    6996: interpretation>
1.29      crook    6997:     @i{code2}
1.26      crook    6998: <interpretation
                   6999: compilation>
1.29      crook    7000:     @i{code3}
1.26      crook    7001: <compilation ;
                   7002: @end example
1.1       anton    7003: 
1.29      crook    7004: For a @i{word} defined with @code{def-word}, the interpretation
                   7005: semantics are to push the address of the body of @i{word} and perform
                   7006: @i{code2}, and the compilation semantics are to push the address of
                   7007: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    7008: can also be defined like this (except that the defined constants don't
                   7009: behave correctly when @code{[compile]}d):
1.1       anton    7010: 
1.26      crook    7011: @example
                   7012: : constant ( n "name" -- )
                   7013:     create-interpret/compile
                   7014:     ,
                   7015: interpretation> ( -- n )
                   7016:     @@
                   7017: <interpretation
                   7018: compilation> ( compilation. -- ; run-time. -- n )
                   7019:     @@ postpone literal
                   7020: <compilation ;
                   7021: @end example
1.1       anton    7022: 
1.44      crook    7023: 
1.26      crook    7024: doc-create-interpret/compile
                   7025: doc-interpretation>
                   7026: doc-<interpretation
                   7027: doc-compilation>
                   7028: doc-<compilation
1.1       anton    7029: 
1.44      crook    7030: 
1.29      crook    7031: Words defined with @code{interpret/compile:} and
1.26      crook    7032: @code{create-interpret/compile} have an extended header structure that
                   7033: differs from other words; however, unless you try to access them with
                   7034: plain address arithmetic, you should not notice this. Words for
                   7035: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    7036: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   7037: with @code{create-interpret/compile}.
1.1       anton    7038: 
1.44      crook    7039: 
1.47      crook    7040: @c -------------------------------------------------------------
1.81      anton    7041: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47      crook    7042: @section Tokens for Words
                   7043: @cindex tokens for words
                   7044: 
                   7045: This section describes the creation and use of tokens that represent
                   7046: words.
                   7047: 
1.71      anton    7048: @menu
                   7049: * Execution token::             represents execution/interpretation semantics
                   7050: * Compilation token::           represents compilation semantics
                   7051: * Name token::                  represents named words
                   7052: @end menu
1.47      crook    7053: 
1.71      anton    7054: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
                   7055: @subsection Execution token
1.47      crook    7056: 
                   7057: @cindex xt
                   7058: @cindex execution token
1.71      anton    7059: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
                   7060: You can use @code{execute} to invoke this behaviour.
1.47      crook    7061: 
1.71      anton    7062: @cindex tick (')
                   7063: You can use @code{'} to get an execution token that represents the
                   7064: interpretation semantics of a named word:
1.47      crook    7065: 
                   7066: @example
1.97      anton    7067: 5 ' .   ( n xt ) 
                   7068: execute ( )      \ execute the xt (i.e., ".")
1.71      anton    7069: @end example
1.47      crook    7070: 
1.71      anton    7071: doc-'
                   7072: 
                   7073: @code{'} parses at run-time; there is also a word @code{[']} that parses
                   7074: when it is compiled, and compiles the resulting XT:
                   7075: 
                   7076: @example
                   7077: : foo ['] . execute ;
                   7078: 5 foo
                   7079: : bar ' execute ; \ by contrast,
                   7080: 5 bar .           \ ' parses "." when bar executes
                   7081: @end example
                   7082: 
                   7083: doc-[']
                   7084: 
                   7085: If you want the execution token of @i{word}, write @code{['] @i{word}}
                   7086: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
                   7087: @code{'} and @code{[']} behave somewhat unusually by complaining about
                   7088: compile-only words (because these words have no interpretation
                   7089: semantics).  You might get what you want by using @code{COMP' @i{word}
                   7090: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
                   7091: token}).
                   7092: 
1.116     anton    7093: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71      anton    7094: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
                   7095: for the only behaviour the word has (the execution semantics).  For
1.116     anton    7096: named words, @code{latestxt} produces an XT for the same behaviour it
1.71      anton    7097: would produce if the word was defined anonymously.
                   7098: 
                   7099: @example
                   7100: :noname ." hello" ;
                   7101: execute
1.47      crook    7102: @end example
                   7103: 
1.71      anton    7104: An XT occupies one cell and can be manipulated like any other cell.
                   7105: 
1.47      crook    7106: @cindex code field address
                   7107: @cindex CFA
1.71      anton    7108: In ANS Forth the XT is just an abstract data type (i.e., defined by the
                   7109: operations that produce or consume it).  For old hands: In Gforth, the
                   7110: XT is implemented as a code field address (CFA).
                   7111: 
                   7112: doc-execute
                   7113: doc-perform
                   7114: 
                   7115: @node Compilation token, Name token, Execution token, Tokens for Words
                   7116: @subsection Compilation token
1.47      crook    7117: 
                   7118: @cindex compilation token
1.71      anton    7119: @cindex CT (compilation token)
                   7120: Gforth represents the compilation semantics of a named word by a
1.47      crook    7121: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   7122: @i{xt} is an execution token. The compilation semantics represented by
                   7123: the compilation token can be performed with @code{execute}, which
                   7124: consumes the whole compilation token, with an additional stack effect
                   7125: determined by the represented compilation semantics.
                   7126: 
                   7127: At present, the @i{w} part of a compilation token is an execution token,
                   7128: and the @i{xt} part represents either @code{execute} or
                   7129: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   7130: word. If the word has default compilation semantics, the @i{xt} will
                   7131: represent @code{compile,}. Otherwise (e.g., for immediate words), the
                   7132: @i{xt} will represent @code{execute}.}. However, don't rely on that
                   7133: knowledge, unless necessary; future versions of Gforth may introduce
                   7134: unusual compilation tokens (e.g., a compilation token that represents
                   7135: the compilation semantics of a literal).
                   7136: 
1.71      anton    7137: You can perform the compilation semantics represented by the compilation
                   7138: token with @code{execute}.  You can compile the compilation semantics
                   7139: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
                   7140: equivalent to @code{postpone @i{word}}.
                   7141: 
                   7142: doc-[comp']
                   7143: doc-comp'
                   7144: doc-postpone,
                   7145: 
                   7146: @node Name token,  , Compilation token, Tokens for Words
                   7147: @subsection Name token
1.47      crook    7148: 
                   7149: @cindex name token
1.116     anton    7150: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
                   7151: token is an abstract data type that occurs as argument or result of the
                   7152: words below.
                   7153: 
                   7154: @c !! put this elswhere?
1.47      crook    7155: @cindex name field address
                   7156: @cindex NFA
1.116     anton    7157: The closest thing to the nt in older Forth systems is the name field
                   7158: address (NFA), but there are significant differences: in older Forth
                   7159: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
                   7160: LFA, NFA, CFA, PFA) and there were words for getting from one to the
                   7161: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
                   7162: is a link field in the structure identified by the name token, but
                   7163: searching usually uses a hash table external to these structures; the
                   7164: name in Gforth has a cell-wide count-and-flags field, and the nt is not
                   7165: implemented as the address of that count field.
1.47      crook    7166: 
                   7167: doc-find-name
1.116     anton    7168: doc-latest
                   7169: doc->name
1.47      crook    7170: doc-name>int
                   7171: doc-name?int
                   7172: doc-name>comp
                   7173: doc-name>string
1.109     anton    7174: doc-id.
                   7175: doc-.name
                   7176: doc-.id
1.47      crook    7177: 
1.81      anton    7178: @c ----------------------------------------------------------
                   7179: @node Compiling words, The Text Interpreter, Tokens for Words, Words
                   7180: @section Compiling words
                   7181: @cindex compiling words
                   7182: @cindex macros
                   7183: 
                   7184: In contrast to most other languages, Forth has no strict boundary
1.82      anton    7185: between compilation and run-time.  E.g., you can run arbitrary code
                   7186: between defining words (or for computing data used by defining words
                   7187: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
                   7188: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
                   7189: running arbitrary code while compiling a colon definition (exception:
                   7190: you must not allot dictionary space).
                   7191: 
                   7192: @menu
                   7193: * Literals::                    Compiling data values
                   7194: * Macros::                      Compiling words
                   7195: @end menu
                   7196: 
                   7197: @node Literals, Macros, Compiling words, Compiling words
                   7198: @subsection Literals
                   7199: @cindex Literals
                   7200: 
                   7201: The simplest and most frequent example is to compute a literal during
                   7202: compilation.  E.g., the following definition prints an array of strings,
                   7203: one string per line:
                   7204: 
                   7205: @example
                   7206: : .strings ( addr u -- ) \ gforth
                   7207:     2* cells bounds U+DO
                   7208:        cr i 2@@ type
                   7209:     2 cells +LOOP ;  
                   7210: @end example
1.81      anton    7211: 
1.82      anton    7212: With a simple-minded compiler like Gforth's, this computes @code{2
                   7213: cells} on every loop iteration.  You can compute this value once and for
                   7214: all at compile time and compile it into the definition like this:
                   7215: 
                   7216: @example
                   7217: : .strings ( addr u -- ) \ gforth
                   7218:     2* cells bounds U+DO
                   7219:        cr i 2@@ type
                   7220:     [ 2 cells ] literal +LOOP ;  
                   7221: @end example
                   7222: 
                   7223: @code{[} switches the text interpreter to interpret state (you will get
                   7224: an @code{ok} prompt if you type this example interactively and insert a
                   7225: newline between @code{[} and @code{]}), so it performs the
                   7226: interpretation semantics of @code{2 cells}; this computes a number.
                   7227: @code{]} switches the text interpreter back into compile state.  It then
                   7228: performs @code{Literal}'s compilation semantics, which are to compile
                   7229: this number into the current word.  You can decompile the word with
                   7230: @code{see .strings} to see the effect on the compiled code.
1.81      anton    7231: 
1.82      anton    7232: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
                   7233: *} in this way.
1.81      anton    7234: 
1.82      anton    7235: doc-[
                   7236: doc-]
1.81      anton    7237: doc-literal
                   7238: doc-]L
1.82      anton    7239: 
                   7240: There are also words for compiling other data types than single cells as
                   7241: literals:
                   7242: 
1.81      anton    7243: doc-2literal
                   7244: doc-fliteral
1.82      anton    7245: doc-sliteral
                   7246: 
                   7247: @cindex colon-sys, passing data across @code{:}
                   7248: @cindex @code{:}, passing data across
                   7249: You might be tempted to pass data from outside a colon definition to the
                   7250: inside on the data stack.  This does not work, because @code{:} puhes a
                   7251: colon-sys, making stuff below unaccessible.  E.g., this does not work:
                   7252: 
                   7253: @example
                   7254: 5 : foo literal ; \ error: "unstructured"
                   7255: @end example
                   7256: 
                   7257: Instead, you have to pass the value in some other way, e.g., through a
                   7258: variable:
                   7259: 
                   7260: @example
                   7261: variable temp
                   7262: 5 temp !
                   7263: : foo [ temp @@ ] literal ;
                   7264: @end example
                   7265: 
                   7266: 
                   7267: @node Macros,  , Literals, Compiling words
                   7268: @subsection Macros
                   7269: @cindex Macros
                   7270: @cindex compiling compilation semantics
                   7271: 
                   7272: @code{Literal} and friends compile data values into the current
                   7273: definition.  You can also write words that compile other words into the
                   7274: current definition.  E.g.,
                   7275: 
                   7276: @example
                   7277: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
                   7278:   POSTPONE + ;
                   7279: 
                   7280: : foo ( n1 n2 -- n )
                   7281:   [ compile-+ ] ;
                   7282: 1 2 foo .
                   7283: @end example
                   7284: 
                   7285: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
                   7286: What happens in this example?  @code{Postpone} compiles the compilation
                   7287: semantics of @code{+} into @code{compile-+}; later the text interpreter
                   7288: executes @code{compile-+} and thus the compilation semantics of +, which
                   7289: compile (the execution semantics of) @code{+} into
                   7290: @code{foo}.@footnote{A recent RFI answer requires that compiling words
                   7291: should only be executed in compile state, so this example is not
                   7292: guaranteed to work on all standard systems, but on any decent system it
                   7293: will work.}
                   7294: 
                   7295: doc-postpone
                   7296: doc-[compile]
                   7297: 
                   7298: Compiling words like @code{compile-+} are usually immediate (or similar)
                   7299: so you do not have to switch to interpret state to execute them;
                   7300: mopifying the last example accordingly produces:
                   7301: 
                   7302: @example
                   7303: : [compile-+] ( compilation: --; interpretation: -- )
                   7304:   \ compiled code: ( n1 n2 -- n )
                   7305:   POSTPONE + ; immediate
                   7306: 
                   7307: : foo ( n1 n2 -- n )
                   7308:   [compile-+] ;
                   7309: 1 2 foo .
                   7310: @end example
                   7311: 
                   7312: Immediate compiling words are similar to macros in other languages (in
                   7313: particular, Lisp).  The important differences to macros in, e.g., C are:
                   7314: 
                   7315: @itemize @bullet
                   7316: 
                   7317: @item
                   7318: You use the same language for defining and processing macros, not a
                   7319: separate preprocessing language and processor.
                   7320: 
                   7321: @item
                   7322: Consequently, the full power of Forth is available in macro definitions.
                   7323: E.g., you can perform arbitrarily complex computations, or generate
                   7324: different code conditionally or in a loop (e.g., @pxref{Advanced macros
                   7325: Tutorial}).  This power is very useful when writing a parser generators
                   7326: or other code-generating software.
                   7327: 
                   7328: @item
                   7329: Macros defined using @code{postpone} etc. deal with the language at a
                   7330: higher level than strings; name binding happens at macro definition
                   7331: time, so you can avoid the pitfalls of name collisions that can happen
                   7332: in C macros.  Of course, Forth is a liberal language and also allows to
                   7333: shoot yourself in the foot with text-interpreted macros like
                   7334: 
                   7335: @example
                   7336: : [compile-+] s" +" evaluate ; immediate
                   7337: @end example
                   7338: 
                   7339: Apart from binding the name at macro use time, using @code{evaluate}
                   7340: also makes your definition @code{state}-smart (@pxref{state-smartness}).
                   7341: @end itemize
                   7342: 
                   7343: You may want the macro to compile a number into a word.  The word to do
                   7344: it is @code{literal}, but you have to @code{postpone} it, so its
                   7345: compilation semantics take effect when the macro is executed, not when
                   7346: it is compiled:
                   7347: 
                   7348: @example
                   7349: : [compile-5] ( -- ) \ compiled code: ( -- n )
                   7350:   5 POSTPONE literal ; immediate
                   7351: 
                   7352: : foo [compile-5] ;
                   7353: foo .
                   7354: @end example
                   7355: 
                   7356: You may want to pass parameters to a macro, that the macro should
                   7357: compile into the current definition.  If the parameter is a number, then
                   7358: you can use @code{postpone literal} (similar for other values).
                   7359: 
                   7360: If you want to pass a word that is to be compiled, the usual way is to
                   7361: pass an execution token and @code{compile,} it:
                   7362: 
                   7363: @example
                   7364: : twice1 ( xt -- ) \ compiled code: ... -- ...
                   7365:   dup compile, compile, ;
                   7366: 
                   7367: : 2+ ( n1 -- n2 )
                   7368:   [ ' 1+ twice1 ] ;
                   7369: @end example
                   7370: 
                   7371: doc-compile,
                   7372: 
                   7373: An alternative available in Gforth, that allows you to pass compile-only
                   7374: words as parameters is to use the compilation token (@pxref{Compilation
                   7375: token}).  The same example in this technique:
                   7376: 
                   7377: @example
                   7378: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
                   7379:   2dup 2>r execute 2r> execute ;
                   7380: 
                   7381: : 2+ ( n1 -- n2 )
                   7382:   [ comp' 1+ twice ] ;
                   7383: @end example
                   7384: 
                   7385: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
                   7386: works even if the executed compilation semantics has an effect on the
                   7387: data stack.
                   7388: 
                   7389: You can also define complete definitions with these words; this provides
                   7390: an alternative to using @code{does>} (@pxref{User-defined Defining
                   7391: Words}).  E.g., instead of
                   7392: 
                   7393: @example
                   7394: : curry+ ( n1 "name" -- )
                   7395:     CREATE ,
                   7396: DOES> ( n2 -- n1+n2 )
                   7397:     @@ + ;
                   7398: @end example
                   7399: 
                   7400: you could define
                   7401: 
                   7402: @example
                   7403: : curry+ ( n1 "name" -- )
                   7404:   \ name execution: ( n2 -- n1+n2 )
                   7405:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81      anton    7406: 
1.82      anton    7407: -3 curry+ 3-
                   7408: see 3-
                   7409: @end example
1.81      anton    7410: 
1.82      anton    7411: The sequence @code{>r : r>} is necessary, because @code{:} puts a
                   7412: colon-sys on the data stack that makes everything below it unaccessible.
1.81      anton    7413: 
1.82      anton    7414: This way of writing defining words is sometimes more, sometimes less
                   7415: convenient than using @code{does>} (@pxref{Advanced does> usage
                   7416: example}).  One advantage of this method is that it can be optimized
                   7417: better, because the compiler knows that the value compiled with
                   7418: @code{literal} is fixed, whereas the data associated with a
                   7419: @code{create}d word can be changed.
1.47      crook    7420: 
1.26      crook    7421: @c ----------------------------------------------------------
1.111     anton    7422: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26      crook    7423: @section  The Text Interpreter
                   7424: @cindex interpreter - outer
                   7425: @cindex text interpreter
                   7426: @cindex outer interpreter
1.1       anton    7427: 
1.34      anton    7428: @c Should we really describe all these ugly details?  IMO the text
                   7429: @c interpreter should be much cleaner, but that may not be possible within
                   7430: @c ANS Forth. - anton
1.44      crook    7431: @c nac-> I wanted to explain how it works to show how you can exploit
                   7432: @c it in your own programs. When I was writing a cross-compiler, figuring out
                   7433: @c some of these gory details was very helpful to me. None of the textbooks
                   7434: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
                   7435: @c seems to positively avoid going into too much detail for some of
                   7436: @c the internals.
1.34      anton    7437: 
1.71      anton    7438: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
                   7439: @c it is; for the ugly details, I would prefer another place.  I wonder
                   7440: @c whether we should have a chapter before "Words" that describes some
                   7441: @c basic concepts referred to in words, and a chapter after "Words" that
                   7442: @c describes implementation details.
                   7443: 
1.29      crook    7444: The text interpreter@footnote{This is an expanded version of the
                   7445: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34      anton    7446: that processes input from the current input device. It is also called
                   7447: the outer interpreter, in contrast to the inner interpreter
                   7448: (@pxref{Engine}) which executes the compiled Forth code on interpretive
                   7449: implementations.
1.27      crook    7450: 
1.29      crook    7451: @cindex interpret state
                   7452: @cindex compile state
                   7453: The text interpreter operates in one of two states: @dfn{interpret
                   7454: state} and @dfn{compile state}. The current state is defined by the
1.71      anton    7455: aptly-named variable @code{state}.
1.29      crook    7456: 
                   7457: This section starts by describing how the text interpreter behaves when
                   7458: it is in interpret state, processing input from the user input device --
                   7459: the keyboard. This is the mode that a Forth system is in after it starts
                   7460: up.
                   7461: 
                   7462: @cindex input buffer
                   7463: @cindex terminal input buffer
                   7464: The text interpreter works from an area of memory called the @dfn{input
                   7465: buffer}@footnote{When the text interpreter is processing input from the
                   7466: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   7467: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   7468: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    7469: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    7470: leading spaces (called @dfn{delimiters}) then parses a string (a
                   7471: sequence of non-space characters) until it reaches either a space
                   7472: character or the end of the buffer. Having parsed a string, it makes two
                   7473: attempts to process it:
1.27      crook    7474: 
1.29      crook    7475: @cindex dictionary
1.27      crook    7476: @itemize @bullet
                   7477: @item
1.29      crook    7478: It looks for the string in a @dfn{dictionary} of definitions. If the
                   7479: string is found, the string names a @dfn{definition} (also known as a
                   7480: @dfn{word}) and the dictionary search returns information that allows
                   7481: the text interpreter to perform the word's @dfn{interpretation
                   7482: semantics}. In most cases, this simply means that the word will be
                   7483: executed.
1.27      crook    7484: @item
                   7485: If the string is not found in the dictionary, the text interpreter
1.29      crook    7486: attempts to treat it as a number, using the rules described in
                   7487: @ref{Number Conversion}. If the string represents a legal number in the
                   7488: current radix, the number is pushed onto a parameter stack (the data
                   7489: stack for integers, the floating-point stack for floating-point
                   7490: numbers).
                   7491: @end itemize
                   7492: 
                   7493: If both attempts fail, or if the word is found in the dictionary but has
                   7494: no interpretation semantics@footnote{This happens if the word was
                   7495: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   7496: remainder of the input buffer, issues an error message and waits for
                   7497: more input. If one of the attempts succeeds, the text interpreter
                   7498: repeats the parsing process until the whole of the input buffer has been
                   7499: processed, at which point it prints the status message ``@code{ ok}''
                   7500: and waits for more input.
                   7501: 
1.71      anton    7502: @c anton: this should be in the input stream subsection (or below it)
                   7503: 
1.29      crook    7504: @cindex parse area
                   7505: The text interpreter keeps track of its position in the input buffer by
                   7506: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   7507: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   7508: of the input buffer. The region from offset @code{>IN @@} to the end of
                   7509: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   7510: the text interpreter processes the contents of the input buffer by
                   7511: parsing strings from the parse area until the parse area is empty.}.
                   7512: This example shows how @code{>IN} changes as the text interpreter parses
                   7513: the input buffer:
                   7514: 
                   7515: @example
                   7516: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   7517:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   7518: 
                   7519: 1 2 3 remaining + remaining . 
                   7520: 
                   7521: : foo 1 2 3 remaining SWAP remaining ;
                   7522: @end example
                   7523: 
                   7524: @noindent
                   7525: The result is:
                   7526: 
                   7527: @example
                   7528: ->+ remaining .<-
                   7529: ->.<-5  ok
                   7530: 
                   7531: ->SWAP remaining ;-<
                   7532: ->;<-  ok
                   7533: @end example
                   7534: 
                   7535: @cindex parsing words
                   7536: The value of @code{>IN} can also be modified by a word in the input
                   7537: buffer that is executed by the text interpreter.  This means that a word
                   7538: can ``trick'' the text interpreter into either skipping a section of the
                   7539: input buffer@footnote{This is how parsing words work.} or into parsing a
                   7540: section twice. For example:
1.27      crook    7541: 
1.29      crook    7542: @example
1.71      anton    7543: : lat ." <<foo>>" ;
                   7544: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29      crook    7545: @end example
                   7546: 
                   7547: @noindent
                   7548: When @code{flat} is executed, this output is produced@footnote{Exercise
                   7549: for the reader: what would happen if the @code{3} were replaced with
                   7550: @code{4}?}:
                   7551: 
                   7552: @example
1.71      anton    7553: <<bar>><<foo>>
1.29      crook    7554: @end example
                   7555: 
1.71      anton    7556: This technique can be used to work around some of the interoperability
                   7557: problems of parsing words.  Of course, it's better to avoid parsing
                   7558: words where possible.
                   7559: 
1.29      crook    7560: @noindent
                   7561: Two important notes about the behaviour of the text interpreter:
1.27      crook    7562: 
                   7563: @itemize @bullet
                   7564: @item
                   7565: It processes each input string to completion before parsing additional
1.29      crook    7566: characters from the input buffer.
                   7567: @item
                   7568: It treats the input buffer as a read-only region (and so must your code).
                   7569: @end itemize
                   7570: 
                   7571: @noindent
                   7572: When the text interpreter is in compile state, its behaviour changes in
                   7573: these ways:
                   7574: 
                   7575: @itemize @bullet
                   7576: @item
                   7577: If a parsed string is found in the dictionary, the text interpreter will
                   7578: perform the word's @dfn{compilation semantics}. In most cases, this
                   7579: simply means that the execution semantics of the word will be appended
                   7580: to the current definition.
1.27      crook    7581: @item
1.29      crook    7582: When a number is encountered, it is compiled into the current definition
                   7583: (as a literal) rather than being pushed onto a parameter stack.
                   7584: @item
                   7585: If an error occurs, @code{state} is modified to put the text interpreter
                   7586: back into interpret state.
                   7587: @item
                   7588: Each time a line is entered from the keyboard, Gforth prints
                   7589: ``@code{ compiled}'' rather than `` @code{ok}''.
                   7590: @end itemize
                   7591: 
                   7592: @cindex text interpreter - input sources
                   7593: When the text interpreter is using an input device other than the
                   7594: keyboard, its behaviour changes in these ways:
                   7595: 
                   7596: @itemize @bullet
                   7597: @item
                   7598: When the parse area is empty, the text interpreter attempts to refill
                   7599: the input buffer from the input source. When the input source is
1.71      anton    7600: exhausted, the input source is set back to the previous input source.
1.29      crook    7601: @item
                   7602: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   7603: time the parse area is emptied.
                   7604: @item
                   7605: If an error occurs, the input source is set back to the user input
                   7606: device.
1.27      crook    7607: @end itemize
1.21      crook    7608: 
1.49      anton    7609: You can read about this in more detail in @ref{Input Sources}.
1.44      crook    7610: 
1.26      crook    7611: doc->in
1.27      crook    7612: doc-source
                   7613: 
1.26      crook    7614: doc-tib
                   7615: doc-#tib
1.1       anton    7616: 
1.44      crook    7617: 
1.26      crook    7618: @menu
1.67      anton    7619: * Input Sources::               
                   7620: * Number Conversion::           
                   7621: * Interpret/Compile states::    
                   7622: * Interpreter Directives::      
1.26      crook    7623: @end menu
1.1       anton    7624: 
1.29      crook    7625: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   7626: @subsection Input Sources
                   7627: @cindex input sources
                   7628: @cindex text interpreter - input sources
                   7629: 
1.44      crook    7630: By default, the text interpreter processes input from the user input
1.29      crook    7631: device (the keyboard) when Forth starts up. The text interpreter can
                   7632: process input from any of these sources:
                   7633: 
                   7634: @itemize @bullet
                   7635: @item
                   7636: The user input device -- the keyboard.
                   7637: @item
                   7638: A file, using the words described in @ref{Forth source files}.
                   7639: @item
                   7640: A block, using the words described in @ref{Blocks}.
                   7641: @item
                   7642: A text string, using @code{evaluate}.
                   7643: @end itemize
                   7644: 
                   7645: A program can identify the current input device from the values of
                   7646: @code{source-id} and @code{blk}.
                   7647: 
1.44      crook    7648: 
1.29      crook    7649: doc-source-id
                   7650: doc-blk
                   7651: 
                   7652: doc-save-input
                   7653: doc-restore-input
                   7654: 
                   7655: doc-evaluate
1.111     anton    7656: doc-query
1.1       anton    7657: 
1.29      crook    7658: 
1.44      crook    7659: 
1.29      crook    7660: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    7661: @subsection Number Conversion
                   7662: @cindex number conversion
                   7663: @cindex double-cell numbers, input format
                   7664: @cindex input format for double-cell numbers
                   7665: @cindex single-cell numbers, input format
                   7666: @cindex input format for single-cell numbers
                   7667: @cindex floating-point numbers, input format
                   7668: @cindex input format for floating-point numbers
1.1       anton    7669: 
1.29      crook    7670: This section describes the rules that the text interpreter uses when it
                   7671: tries to convert a string into a number.
1.1       anton    7672: 
1.26      crook    7673: Let <digit> represent any character that is a legal digit in the current
1.29      crook    7674: number base@footnote{For example, 0-9 when the number base is decimal or
                   7675: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    7676: 
1.26      crook    7677: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    7678: 
1.29      crook    7679: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   7680: in the braces (@i{a} or @i{b} or neither).
1.1       anton    7681: 
1.26      crook    7682: Let * represent any number of instances of the previous character
                   7683: (including none).
1.1       anton    7684: 
1.26      crook    7685: Let any other character represent itself.
1.1       anton    7686: 
1.29      crook    7687: @noindent
1.26      crook    7688: Now, the conversion rules are:
1.21      crook    7689: 
1.26      crook    7690: @itemize @bullet
                   7691: @item
                   7692: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    7693: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    7694: @item
                   7695: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    7696: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    7697: arithmetic. Examples are -45 -5681 -0
                   7698: @item
                   7699: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    7700: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   7701: (all three of these represent the same number).
1.26      crook    7702: @item
                   7703: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    7704: double-precision (double-cell-sized) negative integer, and is
1.26      crook    7705: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    7706: -34.65 (all three of these represent the same number).
1.26      crook    7707: @item
1.29      crook    7708: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   7709: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35      anton    7710: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    7711: number) +12.E-4
1.26      crook    7712: @end itemize
1.1       anton    7713: 
1.174     anton    7714: By default, the number base used for integer number conversion is
                   7715: given by the contents of the variable @code{base}.  Note that a lot of
1.35      anton    7716: confusion can result from unexpected values of @code{base}.  If you
1.174     anton    7717: change @code{base} anywhere, make sure to save the old value and
                   7718: restore it afterwards; better yet, use @code{base-execute}, which does
                   7719: this for you.  In general I recommend keeping @code{base} decimal, and
1.35      anton    7720: using the prefixes described below for the popular non-decimal bases.
1.1       anton    7721: 
1.29      crook    7722: doc-dpl
1.174     anton    7723: doc-base-execute
1.26      crook    7724: doc-base
                   7725: doc-hex
                   7726: doc-decimal
1.1       anton    7727: 
1.26      crook    7728: @cindex '-prefix for character strings
                   7729: @cindex &-prefix for decimal numbers
1.133     anton    7730: @cindex #-prefix for decimal numbers
1.26      crook    7731: @cindex %-prefix for binary numbers
                   7732: @cindex $-prefix for hexadecimal numbers
1.133     anton    7733: @cindex 0x-prefix for hexadecimal numbers
1.35      anton    7734: Gforth allows you to override the value of @code{base} by using a
1.29      crook    7735: prefix@footnote{Some Forth implementations provide a similar scheme by
                   7736: implementing @code{$} etc. as parsing words that process the subsequent
                   7737: number in the input stream and push it onto the stack. For example, see
                   7738: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   7739: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   7740: is required between the prefix and the number.} before the first digit
1.133     anton    7741: of an (integer) number. The following prefixes are supported:
1.1       anton    7742: 
1.26      crook    7743: @itemize @bullet
                   7744: @item
1.35      anton    7745: @code{&} -- decimal
1.26      crook    7746: @item
1.133     anton    7747: @code{#} -- decimal
                   7748: @item
1.35      anton    7749: @code{%} -- binary
1.26      crook    7750: @item
1.35      anton    7751: @code{$} -- hexadecimal
1.26      crook    7752: @item
1.133     anton    7753: @code{0x} -- hexadecimal, if base<33.
                   7754: @item
                   7755: @code{'} -- numeric value (e.g., ASCII code) of next character; an
                   7756: optional @code{'} may be present after the character.
1.26      crook    7757: @end itemize
1.1       anton    7758: 
1.26      crook    7759: Here are some examples, with the equivalent decimal number shown after
                   7760: in braces:
1.1       anton    7761: 
1.26      crook    7762: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133     anton    7763: 'A (65),
                   7764: -'a' (-97),
1.26      crook    7765: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    7766: 
1.26      crook    7767: @cindex number conversion - traps for the unwary
1.29      crook    7768: @noindent
1.26      crook    7769: Number conversion has a number of traps for the unwary:
1.1       anton    7770: 
1.26      crook    7771: @itemize @bullet
                   7772: @item
                   7773: You cannot determine the current number base using the code sequence
1.35      anton    7774: @code{base @@ .} -- the number base is always 10 in the current number
                   7775: base. Instead, use something like @code{base @@ dec.}
1.26      crook    7776: @item
                   7777: If the number base is set to a value greater than 14 (for example,
                   7778: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   7779: it to be intepreted as either a single-precision integer or a
                   7780: floating-point number (Gforth treats it as an integer). The ambiguity
                   7781: can be resolved by explicitly stating the sign of the mantissa and/or
                   7782: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   7783: ambiguity arises; either representation will be treated as a
                   7784: floating-point number.
                   7785: @item
1.29      crook    7786: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    7787: It is used to specify file types.
                   7788: @item
1.72      anton    7789: ANS Forth requires the @code{.} of a double-precision number to be the
                   7790: final character in the string.  Gforth allows the @code{.} to be
                   7791: anywhere after the first digit.
1.26      crook    7792: @item
                   7793: The number conversion process does not check for overflow.
                   7794: @item
1.72      anton    7795: In an ANS Forth program @code{base} is required to be decimal when
                   7796: converting floating-point numbers.  In Gforth, number conversion to
                   7797: floating-point numbers always uses base &10, irrespective of the value
                   7798: of @code{base}.
1.26      crook    7799: @end itemize
1.1       anton    7800: 
1.49      anton    7801: You can read numbers into your programs with the words described in
1.181     anton    7802: @ref{Line input and conversion}.
1.1       anton    7803: 
1.82      anton    7804: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26      crook    7805: @subsection Interpret/Compile states
                   7806: @cindex Interpret/Compile states
1.1       anton    7807: 
1.29      crook    7808: A standard program is not permitted to change @code{state}
                   7809: explicitly. However, it can change @code{state} implicitly, using the
                   7810: words @code{[} and @code{]}. When @code{[} is executed it switches
                   7811: @code{state} to interpret state, and therefore the text interpreter
                   7812: starts interpreting. When @code{]} is executed it switches @code{state}
                   7813: to compile state and therefore the text interpreter starts
1.44      crook    7814: compiling. The most common usage for these words is for switching into
                   7815: interpret state and back from within a colon definition; this technique
1.49      anton    7816: can be used to compile a literal (for an example, @pxref{Literals}) or
                   7817: for conditional compilation (for an example, @pxref{Interpreter
                   7818: Directives}).
1.44      crook    7819: 
1.35      anton    7820: 
                   7821: @c This is a bad example: It's non-standard, and it's not necessary.
                   7822: @c However, I can't think of a good example for switching into compile
                   7823: @c state when there is no current word (@code{state}-smart words are not a
                   7824: @c good reason).  So maybe we should use an example for switching into
                   7825: @c interpret @code{state} in a colon def. - anton
1.44      crook    7826: @c nac-> I agree. I started out by putting in the example, then realised
                   7827: @c that it was non-ANS, so wrote more words around it. I hope this
                   7828: @c re-written version is acceptable to you. I do want to keep the example
                   7829: @c as it is helpful for showing what is and what is not portable, particularly
                   7830: @c where it outlaws a style in common use.
                   7831: 
1.72      anton    7832: @c anton: it's more important to show what's portable.  After we have done
1.83      anton    7833: @c that, we can also show what's not.  In any case, I have written a
                   7834: @c section Compiling Words which also deals with [ ].
1.35      anton    7835: 
1.95      anton    7836: @c  !! The following example does not work in Gforth 0.5.9 or later.
1.29      crook    7837: 
1.95      anton    7838: @c  @code{[} and @code{]} also give you the ability to switch into compile
                   7839: @c  state and back, but we cannot think of any useful Standard application
                   7840: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
                   7841: 
                   7842: @c  @example
                   7843: @c  : AA ." this is A" ;
                   7844: @c  : BB ." this is B" ;
                   7845: @c  : CC ." this is C" ;
                   7846: 
                   7847: @c  create table ] aa bb cc [
                   7848: 
                   7849: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   7850: @c    cells table + @@ execute ;
                   7851: @c  @end example
                   7852: 
                   7853: @c  This example builds a jump table; @code{0 go} will display ``@code{this
                   7854: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
                   7855: @c  defining @code{table} like this:
                   7856: 
                   7857: @c  @example
                   7858: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
                   7859: @c  @end example
                   7860: 
                   7861: @c  The problem with this code is that the definition of @code{table} is not
                   7862: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
                   7863: @c  @i{may} work on systems where code space and data space co-incide, the
                   7864: @c  Standard only allows data space to be assigned for a @code{CREATE}d
                   7865: @c  word. In addition, the Standard only allows @code{@@} to access data
                   7866: @c  space, whilst this example is using it to access code space. The only
                   7867: @c  portable, Standard way to build this table is to build it in data space,
                   7868: @c  like this:
                   7869: 
                   7870: @c  @example
                   7871: @c  create table ' aa , ' bb , ' cc ,
                   7872: @c  @end example
1.29      crook    7873: 
1.95      anton    7874: @c  doc-state
1.44      crook    7875: 
1.29      crook    7876: 
1.82      anton    7877: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
1.26      crook    7878: @subsection Interpreter Directives
                   7879: @cindex interpreter directives
1.72      anton    7880: @cindex conditional compilation
1.1       anton    7881: 
1.29      crook    7882: These words are usually used in interpret state; typically to control
                   7883: which parts of a source file are processed by the text
1.26      crook    7884: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   7885: supplements these with a rich set of immediate control structure words
                   7886: to compensate for the fact that the non-immediate versions can only be
1.29      crook    7887: used in compile state (@pxref{Control Structures}). Typical usages:
                   7888: 
                   7889: @example
1.72      anton    7890: FALSE Constant HAVE-ASSEMBLER
1.29      crook    7891: .
                   7892: .
1.72      anton    7893: HAVE-ASSEMBLER [IF]
1.29      crook    7894: : ASSEMBLER-FEATURE
                   7895:   ...
                   7896: ;
                   7897: [ENDIF]
                   7898: .
                   7899: .
                   7900: : SEE
                   7901:   ... \ general-purpose SEE code
1.72      anton    7902:   [ HAVE-ASSEMBLER [IF] ]
1.29      crook    7903:   ... \ assembler-specific SEE code
                   7904:   [ [ENDIF] ]
                   7905: ;
                   7906: @end example
1.1       anton    7907: 
1.44      crook    7908: 
1.26      crook    7909: doc-[IF]
                   7910: doc-[ELSE]
                   7911: doc-[THEN]
                   7912: doc-[ENDIF]
1.1       anton    7913: 
1.26      crook    7914: doc-[IFDEF]
                   7915: doc-[IFUNDEF]
1.1       anton    7916: 
1.26      crook    7917: doc-[?DO]
                   7918: doc-[DO]
                   7919: doc-[FOR]
                   7920: doc-[LOOP]
                   7921: doc-[+LOOP]
                   7922: doc-[NEXT]
1.1       anton    7923: 
1.26      crook    7924: doc-[BEGIN]
                   7925: doc-[UNTIL]
                   7926: doc-[AGAIN]
                   7927: doc-[WHILE]
                   7928: doc-[REPEAT]
1.1       anton    7929: 
1.27      crook    7930: 
1.26      crook    7931: @c -------------------------------------------------------------
1.111     anton    7932: @node The Input Stream, Word Lists, The Text Interpreter, Words
                   7933: @section The Input Stream
                   7934: @cindex input stream
                   7935: 
                   7936: @c !! integrate this better with the "Text Interpreter" section
                   7937: The text interpreter reads from the input stream, which can come from
                   7938: several sources (@pxref{Input Sources}).  Some words, in particular
                   7939: defining words, but also words like @code{'}, read parameters from the
                   7940: input stream instead of from the stack.
                   7941: 
                   7942: Such words are called parsing words, because they parse the input
                   7943: stream.  Parsing words are hard to use in other words, because it is
                   7944: hard to pass program-generated parameters through the input stream.
                   7945: They also usually have an unintuitive combination of interpretation and
                   7946: compilation semantics when implemented naively, leading to various
                   7947: approaches that try to produce a more intuitive behaviour
                   7948: (@pxref{Combined words}).
                   7949: 
                   7950: It should be obvious by now that parsing words are a bad idea.  If you
                   7951: want to implement a parsing word for convenience, also provide a factor
                   7952: of the word that does not parse, but takes the parameters on the stack.
                   7953: To implement the parsing word on top if it, you can use the following
                   7954: words:
                   7955: 
                   7956: @c anton: these belong in the input stream section
                   7957: doc-parse
1.138     anton    7958: doc-parse-name
1.111     anton    7959: doc-parse-word
                   7960: doc-name
                   7961: doc-word
                   7962: doc-\"-parse
                   7963: doc-refill
                   7964: 
                   7965: Conversely, if you have the bad luck (or lack of foresight) to have to
                   7966: deal with parsing words without having such factors, how do you pass a
                   7967: string that is not in the input stream to it?
                   7968: 
                   7969: doc-execute-parsing
                   7970: 
1.146     anton    7971: A definition of this word in ANS Forth is provided in
                   7972: @file{compat/execute-parsing.fs}.
                   7973: 
1.111     anton    7974: If you want to run a parsing word on a file, the following word should
                   7975: help:
                   7976: 
                   7977: doc-execute-parsing-file
                   7978: 
                   7979: @c -------------------------------------------------------------
                   7980: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26      crook    7981: @section Word Lists
                   7982: @cindex word lists
1.32      anton    7983: @cindex header space
1.1       anton    7984: 
1.36      anton    7985: A wordlist is a list of named words; you can add new words and look up
                   7986: words by name (and you can remove words in a restricted way with
                   7987: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
                   7988: 
                   7989: @cindex search order stack
                   7990: The text interpreter searches the wordlists present in the search order
                   7991: (a stack of wordlists), from the top to the bottom.  Within each
                   7992: wordlist, the search starts conceptually at the newest word; i.e., if
                   7993: two words in a wordlist have the same name, the newer word is found.
1.1       anton    7994: 
1.26      crook    7995: @cindex compilation word list
1.36      anton    7996: New words are added to the @dfn{compilation wordlist} (aka current
                   7997: wordlist).
1.1       anton    7998: 
1.36      anton    7999: @cindex wid
                   8000: A word list is identified by a cell-sized word list identifier (@i{wid})
                   8001: in much the same way as a file is identified by a file handle. The
                   8002: numerical value of the wid has no (portable) meaning, and might change
                   8003: from session to session.
1.1       anton    8004: 
1.29      crook    8005: The ANS Forth ``Search order'' word set is intended to provide a set of
                   8006: low-level tools that allow various different schemes to be
1.74      anton    8007: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26      crook    8008: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
1.45      crook    8009: Forth.
1.1       anton    8010: 
1.27      crook    8011: @comment TODO: locals section refers to here, saying that every word list (aka
                   8012: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78      anton    8013: @c anton: but better in a separate subsection on wordlist internals
1.1       anton    8014: 
1.45      crook    8015: @comment TODO: document markers, reveal, tables, mappedwordlist
                   8016: 
                   8017: @comment the gforthman- prefix is used to pick out the true definition of a
1.27      crook    8018: @comment word from the source files, rather than some alias.
1.44      crook    8019: 
1.26      crook    8020: doc-forth-wordlist
                   8021: doc-definitions
                   8022: doc-get-current
                   8023: doc-set-current
                   8024: doc-get-order
1.45      crook    8025: doc---gforthman-set-order
1.26      crook    8026: doc-wordlist
1.30      anton    8027: doc-table
1.79      anton    8028: doc->order
1.36      anton    8029: doc-previous
1.26      crook    8030: doc-also
1.45      crook    8031: doc---gforthman-forth
1.26      crook    8032: doc-only
1.45      crook    8033: doc---gforthman-order
1.15      anton    8034: 
1.26      crook    8035: doc-find
                   8036: doc-search-wordlist
1.15      anton    8037: 
1.26      crook    8038: doc-words
                   8039: doc-vlist
1.44      crook    8040: @c doc-words-deferred
1.1       anton    8041: 
1.74      anton    8042: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26      crook    8043: doc-root
                   8044: doc-vocabulary
                   8045: doc-seal
                   8046: doc-vocs
                   8047: doc-current
                   8048: doc-context
1.1       anton    8049: 
1.44      crook    8050: 
1.26      crook    8051: @menu
1.75      anton    8052: * Vocabularies::                
1.67      anton    8053: * Why use word lists?::         
1.75      anton    8054: * Word list example::           
1.26      crook    8055: @end menu
                   8056: 
1.75      anton    8057: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
                   8058: @subsection Vocabularies
                   8059: @cindex Vocabularies, detailed explanation
                   8060: 
                   8061: Here is an example of creating and using a new wordlist using ANS
                   8062: Forth words:
                   8063: 
                   8064: @example
                   8065: wordlist constant my-new-words-wordlist
                   8066: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
                   8067: 
                   8068: \ add it to the search order
                   8069: also my-new-words
                   8070: 
                   8071: \ alternatively, add it to the search order and make it
                   8072: \ the compilation word list
                   8073: also my-new-words definitions
                   8074: \ type "order" to see the problem
                   8075: @end example
                   8076: 
                   8077: The problem with this example is that @code{order} has no way to
                   8078: associate the name @code{my-new-words} with the wid of the word list (in
                   8079: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   8080: that has no associated name). There is no Standard way of associating a
                   8081: name with a wid.
                   8082: 
                   8083: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   8084: associates a name with a wid:
                   8085: 
                   8086: @example
                   8087: vocabulary my-new-words
                   8088: 
                   8089: \ add it to the search order
                   8090: also my-new-words
                   8091: 
                   8092: \ alternatively, add it to the search order and make it
                   8093: \ the compilation word list
                   8094: my-new-words definitions
                   8095: \ type "order" to see that the problem is solved
                   8096: @end example
                   8097: 
                   8098: 
                   8099: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26      crook    8100: @subsection Why use word lists?
                   8101: @cindex word lists - why use them?
                   8102: 
1.74      anton    8103: Here are some reasons why people use wordlists:
1.26      crook    8104: 
                   8105: @itemize @bullet
1.74      anton    8106: 
                   8107: @c anton: Gforth's hashing implementation makes the search speed
                   8108: @c independent from the number of words.  But it is linear with the number
                   8109: @c of wordlists that have to be searched, so in effect using more wordlists
                   8110: @c actually slows down compilation.
                   8111: 
                   8112: @c @item
                   8113: @c To improve compilation speed by reducing the number of header space
                   8114: @c entries that must be searched. This is achieved by creating a new
                   8115: @c word list that contains all of the definitions that are used in the
                   8116: @c definition of a Forth system but which would not usually be used by
                   8117: @c programs running on that system. That word list would be on the search
                   8118: @c list when the Forth system was compiled but would be removed from the
                   8119: @c search list for normal operation. This can be a useful technique for
                   8120: @c low-performance systems (for example, 8-bit processors in embedded
                   8121: @c systems) but is unlikely to be necessary in high-performance desktop
                   8122: @c systems.
                   8123: 
1.26      crook    8124: @item
                   8125: To prevent a set of words from being used outside the context in which
                   8126: they are valid. Two classic examples of this are an integrated editor
                   8127: (all of the edit commands are defined in a separate word list; the
                   8128: search order is set to the editor word list when the editor is invoked;
                   8129: the old search order is restored when the editor is terminated) and an
                   8130: integrated assembler (the op-codes for the machine are defined in a
                   8131: separate word list which is used when a @code{CODE} word is defined).
1.74      anton    8132: 
                   8133: @item
                   8134: To organize the words of an application or library into a user-visible
                   8135: set (in @code{forth-wordlist} or some other common wordlist) and a set
                   8136: of helper words used just for the implementation (hidden in a separate
1.75      anton    8137: wordlist).  This keeps @code{words}' output smaller, separates
                   8138: implementation and interface, and reduces the chance of name conflicts
                   8139: within the common wordlist.
1.74      anton    8140: 
1.26      crook    8141: @item
                   8142: To prevent a name-space clash between multiple definitions with the same
                   8143: name. For example, when building a cross-compiler you might have a word
                   8144: @code{IF} that generates conditional code for your target system. By
                   8145: placing this definition in a different word list you can control whether
                   8146: the host system's @code{IF} or the target system's @code{IF} get used in
                   8147: any particular context by controlling the order of the word lists on the
                   8148: search order stack.
1.74      anton    8149: 
1.26      crook    8150: @end itemize
1.1       anton    8151: 
1.74      anton    8152: The downsides of using wordlists are:
                   8153: 
                   8154: @itemize
                   8155: 
                   8156: @item
                   8157: Debugging becomes more cumbersome.
                   8158: 
                   8159: @item
                   8160: Name conflicts worked around with wordlists are still there, and you
                   8161: have to arrange the search order carefully to get the desired results;
                   8162: if you forget to do that, you get hard-to-find errors (as in any case
                   8163: where you read the code differently from the compiler; @code{see} can
1.75      anton    8164: help seeing which of several possible words the name resolves to in such
                   8165: cases).  @code{See} displays just the name of the words, not what
                   8166: wordlist they belong to, so it might be misleading.  Using unique names
                   8167: is a better approach to avoid name conflicts.
1.74      anton    8168: 
                   8169: @item
                   8170: You have to explicitly undo any changes to the search order.  In many
                   8171: cases it would be more convenient if this happened implicitly.  Gforth
                   8172: currently does not provide such a feature, but it may do so in the
                   8173: future.
                   8174: @end itemize
                   8175: 
                   8176: 
1.75      anton    8177: @node Word list example,  , Why use word lists?, Word Lists
                   8178: @subsection Word list example
                   8179: @cindex word lists - example
1.1       anton    8180: 
1.74      anton    8181: The following example is from the
                   8182: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   8183: garbage collector} and uses wordlists to separate public words from
                   8184: helper words:
                   8185: 
                   8186: @example
                   8187: get-current ( wid )
                   8188: vocabulary garbage-collector also garbage-collector definitions
                   8189: ... \ define helper words
                   8190: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
                   8191: ... \ define the public (i.e., API) words
                   8192:     \ they can refer to the helper words
                   8193: previous \ restore original search order (helper words become invisible)
                   8194: @end example
                   8195: 
1.26      crook    8196: @c -------------------------------------------------------------
                   8197: @node Environmental Queries, Files, Word Lists, Words
                   8198: @section Environmental Queries
                   8199: @cindex environmental queries
1.21      crook    8200: 
1.26      crook    8201: ANS Forth introduced the idea of ``environmental queries'' as a way
                   8202: for a program running on a system to determine certain characteristics of the system.
                   8203: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    8204: 
1.32      anton    8205: The Standard requires that the header space used for environmental queries
                   8206: be distinct from the header space used for definitions.
1.21      crook    8207: 
1.26      crook    8208: Typically, environmental queries are supported by creating a set of
1.29      crook    8209: definitions in a word list that is @i{only} used during environmental
1.26      crook    8210: queries; that is what Gforth does. There is no Standard way of adding
                   8211: definitions to the set of recognised environmental queries, but any
                   8212: implementation that supports the loading of optional word sets must have
                   8213: some mechanism for doing this (after loading the word set, the
                   8214: associated environmental query string must return @code{true}). In
                   8215: Gforth, the word list used to honour environmental queries can be
                   8216: manipulated just like any other word list.
1.21      crook    8217: 
1.44      crook    8218: 
1.26      crook    8219: doc-environment?
                   8220: doc-environment-wordlist
1.21      crook    8221: 
1.26      crook    8222: doc-gforth
                   8223: doc-os-class
1.21      crook    8224: 
1.44      crook    8225: 
1.26      crook    8226: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   8227: returning two items on the stack, querying it using @code{environment?}
                   8228: will return an additional item; the @code{true} flag that shows that the
                   8229: string was recognised.
1.21      crook    8230: 
1.26      crook    8231: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    8232: 
1.26      crook    8233: Here are some examples of using environmental queries:
1.21      crook    8234: 
1.26      crook    8235: @example
                   8236: s" address-unit-bits" environment? 0=
                   8237: [IF]
                   8238:      cr .( environmental attribute address-units-bits unknown... ) cr
1.75      anton    8239: [ELSE]
                   8240:      drop \ ensure balanced stack effect
1.26      crook    8241: [THEN]
1.21      crook    8242: 
1.75      anton    8243: \ this might occur in the prelude of a standard program that uses THROW
                   8244: s" exception" environment? [IF]
                   8245:    0= [IF]
                   8246:       : throw abort" exception thrown" ;
                   8247:    [THEN]
                   8248: [ELSE] \ we don't know, so make sure
                   8249:    : throw abort" exception thrown" ;
                   8250: [THEN]
1.21      crook    8251: 
1.26      crook    8252: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   8253:                         [ELSE] .( Not Gforth..) [THEN]
1.75      anton    8254: 
                   8255: \ a program using v*
                   8256: s" gforth" environment? [IF]
                   8257:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
                   8258:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8259:      >r swap 2swap swap 0e r> 0 ?DO
                   8260:        dup f@ over + 2swap dup f@ f* f+ over + 2swap
                   8261:      LOOP
                   8262:      2drop 2drop ; 
                   8263:   [THEN]
                   8264: [ELSE] \ 
                   8265:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8266:   ...
                   8267: [THEN]
1.26      crook    8268: @end example
1.21      crook    8269: 
1.26      crook    8270: Here is an example of adding a definition to the environment word list:
1.21      crook    8271: 
1.26      crook    8272: @example
                   8273: get-current environment-wordlist set-current
                   8274: true constant block
                   8275: true constant block-ext
                   8276: set-current
                   8277: @end example
1.21      crook    8278: 
1.26      crook    8279: You can see what definitions are in the environment word list like this:
1.21      crook    8280: 
1.26      crook    8281: @example
1.79      anton    8282: environment-wordlist >order words previous
1.26      crook    8283: @end example
1.21      crook    8284: 
                   8285: 
1.26      crook    8286: @c -------------------------------------------------------------
                   8287: @node Files, Blocks, Environmental Queries, Words
                   8288: @section Files
1.28      crook    8289: @cindex files
                   8290: @cindex I/O - file-handling
1.21      crook    8291: 
1.26      crook    8292: Gforth provides facilities for accessing files that are stored in the
                   8293: host operating system's file-system. Files that are processed by Gforth
                   8294: can be divided into two categories:
1.21      crook    8295: 
1.23      crook    8296: @itemize @bullet
                   8297: @item
1.29      crook    8298: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    8299: @item
1.29      crook    8300: Files that are processed by some other program (@dfn{general files}).
1.26      crook    8301: @end itemize
                   8302: 
                   8303: @menu
1.48      anton    8304: * Forth source files::          
                   8305: * General files::               
1.167     anton    8306: * Redirection::                 
1.48      anton    8307: * Search Paths::                
1.26      crook    8308: @end menu
                   8309: 
                   8310: @c -------------------------------------------------------------
                   8311: @node Forth source files, General files, Files, Files
                   8312: @subsection Forth source files
                   8313: @cindex including files
                   8314: @cindex Forth source files
1.21      crook    8315: 
1.26      crook    8316: The simplest way to interpret the contents of a file is to use one of
                   8317: these two formats:
1.21      crook    8318: 
1.26      crook    8319: @example
                   8320: include mysource.fs
                   8321: s" mysource.fs" included
                   8322: @end example
1.21      crook    8323: 
1.75      anton    8324: You usually want to include a file only if it is not included already
1.26      crook    8325: (by, say, another source file). In that case, you can use one of these
1.45      crook    8326: three formats:
1.21      crook    8327: 
1.26      crook    8328: @example
                   8329: require mysource.fs
                   8330: needs mysource.fs
                   8331: s" mysource.fs" required
                   8332: @end example
1.21      crook    8333: 
1.26      crook    8334: @cindex stack effect of included files
                   8335: @cindex including files, stack effect
1.45      crook    8336: It is good practice to write your source files such that interpreting them
                   8337: does not change the stack. Source files designed in this way can be used with
1.26      crook    8338: @code{required} and friends without complications. For example:
1.21      crook    8339: 
1.26      crook    8340: @example
1.75      anton    8341: 1024 require foo.fs drop
1.26      crook    8342: @end example
1.21      crook    8343: 
1.75      anton    8344: Here you want to pass the argument 1024 (e.g., a buffer size) to
                   8345: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
                   8346: ), which allows its use with @code{require}.  Of course with such
                   8347: parameters to required files, you have to ensure that the first
                   8348: @code{require} fits for all uses (i.e., @code{require} it early in the
                   8349: master load file).
1.44      crook    8350: 
1.26      crook    8351: doc-include-file
                   8352: doc-included
1.28      crook    8353: doc-included?
1.26      crook    8354: doc-include
                   8355: doc-required
                   8356: doc-require
                   8357: doc-needs
1.75      anton    8358: @c doc-init-included-files @c internal
                   8359: doc-sourcefilename
                   8360: doc-sourceline#
1.44      crook    8361: 
1.26      crook    8362: A definition in ANS Forth for @code{required} is provided in
                   8363: @file{compat/required.fs}.
1.21      crook    8364: 
1.26      crook    8365: @c -------------------------------------------------------------
1.167     anton    8366: @node General files, Redirection, Forth source files, Files
1.26      crook    8367: @subsection General files
                   8368: @cindex general files
                   8369: @cindex file-handling
1.21      crook    8370: 
1.75      anton    8371: Files are opened/created by name and type. The following file access
                   8372: methods (FAMs) are recognised:
1.44      crook    8373: 
1.75      anton    8374: @cindex fam (file access method)
1.26      crook    8375: doc-r/o
                   8376: doc-r/w
                   8377: doc-w/o
                   8378: doc-bin
1.1       anton    8379: 
1.44      crook    8380: 
1.26      crook    8381: When a file is opened/created, it returns a file identifier,
1.29      crook    8382: @i{wfileid} that is used for all other file commands. All file
                   8383: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    8384: successful operation and an implementation-defined non-zero value in the
                   8385: case of an error.
1.21      crook    8386: 
1.44      crook    8387: 
1.26      crook    8388: doc-open-file
                   8389: doc-create-file
1.21      crook    8390: 
1.26      crook    8391: doc-close-file
                   8392: doc-delete-file
                   8393: doc-rename-file
                   8394: doc-read-file
                   8395: doc-read-line
1.154     anton    8396: doc-key-file
                   8397: doc-key?-file
1.26      crook    8398: doc-write-file
                   8399: doc-write-line
                   8400: doc-emit-file
                   8401: doc-flush-file
1.21      crook    8402: 
1.26      crook    8403: doc-file-status
                   8404: doc-file-position
                   8405: doc-reposition-file
                   8406: doc-file-size
                   8407: doc-resize-file
1.21      crook    8408: 
1.93      anton    8409: doc-slurp-file
                   8410: doc-slurp-fid
1.112     anton    8411: doc-stdin
                   8412: doc-stdout
                   8413: doc-stderr
1.44      crook    8414: 
1.26      crook    8415: @c ---------------------------------------------------------
1.167     anton    8416: @node Redirection, Search Paths, General files, Files
                   8417: @subsection Redirection
                   8418: @cindex Redirection
                   8419: @cindex Input Redirection
                   8420: @cindex Output Redirection
                   8421: 
                   8422: You can redirect the output of @code{type} and @code{emit} and all the
                   8423: words that use them (all output words that don't have an explicit
1.174     anton    8424: target file) to an arbitrary file with the @code{outfile-execute},
                   8425: used like this:
1.167     anton    8426: 
                   8427: @example
1.174     anton    8428: : some-warning ( n -- )
                   8429:     cr ." warning# " . ;
                   8430: 
1.167     anton    8431: : print-some-warning ( n -- )
1.174     anton    8432:     ['] some-warning stderr outfile-execute ;
1.167     anton    8433: @end example
                   8434: 
1.174     anton    8435: After @code{some-warning} is executed, the original output direction
                   8436: is restored; this construct is safe against exceptions.  Similarly,
                   8437: there is @code{infile-execute} for redirecting the input of @code{key}
                   8438: and its users (any input word that does not take a file explicitly).
                   8439: 
                   8440: doc-outfile-execute
                   8441: doc-infile-execute
1.167     anton    8442: 
                   8443: If you do not want to redirect the input or output to a file, you can
                   8444: also make use of the fact that @code{key}, @code{emit} and @code{type}
                   8445: are deferred words (@pxref{Deferred Words}).  However, in that case
                   8446: you have to worry about the restoration and the protection against
                   8447: exceptions yourself; also, note that for redirecting the output in
                   8448: this way, you have to redirect both @code{emit} and @code{type}.
                   8449: 
                   8450: @c ---------------------------------------------------------
                   8451: @node Search Paths,  , Redirection, Files
1.26      crook    8452: @subsection Search Paths
                   8453: @cindex path for @code{included}
                   8454: @cindex file search path
                   8455: @cindex @code{include} search path
                   8456: @cindex search path for files
1.21      crook    8457: 
1.26      crook    8458: If you specify an absolute filename (i.e., a filename starting with
                   8459: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   8460: @samp{C:...})) for @code{included} and friends, that file is included
                   8461: just as you would expect.
1.21      crook    8462: 
1.75      anton    8463: If the filename starts with @file{./}, this refers to the directory that
                   8464: the present file was @code{included} from.  This allows files to include
                   8465: other files relative to their own position (irrespective of the current
                   8466: working directory or the absolute position).  This feature is essential
                   8467: for libraries consisting of several files, where a file may include
                   8468: other files from the library.  It corresponds to @code{#include "..."}
                   8469: in C. If the current input source is not a file, @file{.} refers to the
                   8470: directory of the innermost file being included, or, if there is no file
                   8471: being included, to the current working directory.
                   8472: 
                   8473: For relative filenames (not starting with @file{./}), Gforth uses a
                   8474: search path similar to Forth's search order (@pxref{Word Lists}). It
                   8475: tries to find the given filename in the directories present in the path,
                   8476: and includes the first one it finds. There are separate search paths for
                   8477: Forth source files and general files.  If the search path contains the
                   8478: directory @file{.}, this refers to the directory of the current file, or
                   8479: the working directory, as if the file had been specified with @file{./}.
1.21      crook    8480: 
1.26      crook    8481: Use @file{~+} to refer to the current working directory (as in the
                   8482: @code{bash}).
1.1       anton    8483: 
1.75      anton    8484: @c anton: fold the following subsubsections into this subsection?
1.1       anton    8485: 
1.48      anton    8486: @menu
1.75      anton    8487: * Source Search Paths::         
1.48      anton    8488: * General Search Paths::        
                   8489: @end menu
                   8490: 
1.26      crook    8491: @c ---------------------------------------------------------
1.75      anton    8492: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
                   8493: @subsubsection Source Search Paths
                   8494: @cindex search path control, source files
1.5       anton    8495: 
1.26      crook    8496: The search path is initialized when you start Gforth (@pxref{Invoking
1.75      anton    8497: Gforth}). You can display it and change it using @code{fpath} in
                   8498: combination with the general path handling words.
1.5       anton    8499: 
1.75      anton    8500: doc-fpath
                   8501: @c the functionality of the following words is easily available through
                   8502: @c   fpath and the general path words.  The may go away.
                   8503: @c doc-.fpath
                   8504: @c doc-fpath+
                   8505: @c doc-fpath=
                   8506: @c doc-open-fpath-file
1.44      crook    8507: 
                   8508: @noindent
1.26      crook    8509: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    8510: 
1.26      crook    8511: @example
1.75      anton    8512: fpath path= /usr/lib/forth/|./
1.26      crook    8513: require timer.fs
                   8514: @end example
1.5       anton    8515: 
1.75      anton    8516: 
1.26      crook    8517: @c ---------------------------------------------------------
1.75      anton    8518: @node General Search Paths,  , Source Search Paths, Search Paths
1.26      crook    8519: @subsubsection General Search Paths
1.75      anton    8520: @cindex search path control, source files
1.5       anton    8521: 
1.26      crook    8522: Your application may need to search files in several directories, like
                   8523: @code{included} does. To facilitate this, Gforth allows you to define
                   8524: and use your own search paths, by providing generic equivalents of the
                   8525: Forth search path words:
1.5       anton    8526: 
1.75      anton    8527: doc-open-path-file
                   8528: doc-path-allot
                   8529: doc-clear-path
                   8530: doc-also-path
1.26      crook    8531: doc-.path
                   8532: doc-path+
                   8533: doc-path=
1.5       anton    8534: 
1.75      anton    8535: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44      crook    8536: 
1.75      anton    8537: Here's an example of creating an empty search path:
                   8538: @c
1.26      crook    8539: @example
1.75      anton    8540: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26      crook    8541: @end example
1.5       anton    8542: 
1.26      crook    8543: @c -------------------------------------------------------------
                   8544: @node Blocks, Other I/O, Files, Words
                   8545: @section Blocks
1.28      crook    8546: @cindex I/O - blocks
                   8547: @cindex blocks
                   8548: 
                   8549: When you run Gforth on a modern desk-top computer, it runs under the
                   8550: control of an operating system which provides certain services.  One of
                   8551: these services is @var{file services}, which allows Forth source code
                   8552: and data to be stored in files and read into Gforth (@pxref{Files}).
                   8553: 
                   8554: Traditionally, Forth has been an important programming language on
                   8555: systems where it has interfaced directly to the underlying hardware with
                   8556: no intervening operating system. Forth provides a mechanism, called
1.29      crook    8557: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    8558: 
                   8559: A block is a 1024-byte data area, which can be used to hold data or
                   8560: Forth source code. No structure is imposed on the contents of the
                   8561: block. A block is identified by its number; blocks are numbered
                   8562: contiguously from 1 to an implementation-defined maximum.
                   8563: 
                   8564: A typical system that used blocks but no operating system might use a
                   8565: single floppy-disk drive for mass storage, with the disks formatted to
                   8566: provide 256-byte sectors. Blocks would be implemented by assigning the
                   8567: first four sectors of the disk to block 1, the second four sectors to
                   8568: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   8569: would not contain any file system information, just the set of blocks.
                   8570: 
1.29      crook    8571: @cindex blocks file
1.28      crook    8572: On systems that do provide file services, blocks are typically
1.29      crook    8573: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    8574: file}.  The size of the blocks file will be an exact multiple of 1024
                   8575: bytes, corresponding to the number of blocks it contains. This is the
                   8576: mechanism that Gforth uses.
                   8577: 
1.29      crook    8578: @cindex @file{blocks.fb}
1.75      anton    8579: Only one blocks file can be open at a time. If you use block words without
1.28      crook    8580: having specified a blocks file, Gforth defaults to the blocks file
                   8581: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75      anton    8582: locate a blocks file (@pxref{Source Search Paths}).
1.28      crook    8583: 
1.29      crook    8584: @cindex block buffers
1.28      crook    8585: When you read and write blocks under program control, Gforth uses a
1.29      crook    8586: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    8587: not used when you use @code{load} to interpret the contents of a block.
                   8588: 
1.75      anton    8589: The behaviour of the block buffers is analagous to that of a cache.
                   8590: Each block buffer has three states:
1.28      crook    8591: 
                   8592: @itemize @bullet
                   8593: @item
                   8594: Unassigned
                   8595: @item
                   8596: Assigned-clean
                   8597: @item
                   8598: Assigned-dirty
                   8599: @end itemize
                   8600: 
1.29      crook    8601: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    8602: block, the block (specified by its block number) must be assigned to a
                   8603: block buffer.
                   8604: 
                   8605: The assignment of a block to a block buffer is performed by @code{block}
                   8606: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   8607: contents of a block. Use @code{buffer} when you don't care about the
                   8608: existing contents of the block@footnote{The ANS Forth definition of
1.35      anton    8609: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28      crook    8610: with the particular block is already stored in a block buffer due to an
                   8611: earlier @code{block} command, @code{buffer} will return that block
                   8612: buffer and the existing contents of the block will be
                   8613: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    8614: block buffer for the block.}.
1.28      crook    8615: 
1.47      crook    8616: Once a block has been assigned to a block buffer using @code{block} or
1.75      anton    8617: @code{buffer}, that block buffer becomes the @i{current block
                   8618: buffer}. Data may only be manipulated (read or written) within the
                   8619: current block buffer.
1.47      crook    8620: 
                   8621: When the contents of the current block buffer has been modified it is
1.48      anton    8622: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75      anton    8623: either abandon the changes (by doing nothing) or mark the block as
                   8624: changed (assigned-dirty), using @code{update}. Using @code{update} does
                   8625: not change the blocks file; it simply changes a block buffer's state to
                   8626: @i{assigned-dirty}.  The block will be written implicitly when it's
                   8627: buffer is needed for another block, or explicitly by @code{flush} or
                   8628: @code{save-buffers}.
                   8629: 
                   8630: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
                   8631: blocks file on disk. Leaving Gforth with @code{bye} also performs a
                   8632: @code{flush}.
1.28      crook    8633: 
1.29      crook    8634: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    8635: algorithm to assign a block buffer to a block. That means that any
                   8636: particular block can only be assigned to one specific block buffer,
1.29      crook    8637: called (for the particular operation) the @i{victim buffer}. If the
1.47      crook    8638: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
                   8639: the new block immediately. If it is @i{assigned-dirty} its current
                   8640: contents are written back to the blocks file on disk before it is
1.28      crook    8641: allocated to the new block.
                   8642: 
                   8643: Although no structure is imposed on the contents of a block, it is
                   8644: traditional to display the contents as 16 lines each of 64 characters.  A
                   8645: block provides a single, continuous stream of input (for example, it
                   8646: acts as a single parse area) -- there are no end-of-line characters
                   8647: within a block, and no end-of-file character at the end of a
                   8648: block. There are two consequences of this:
1.26      crook    8649: 
1.28      crook    8650: @itemize @bullet
                   8651: @item
                   8652: The last character of one line wraps straight into the first character
                   8653: of the following line
                   8654: @item
                   8655: The word @code{\} -- comment to end of line -- requires special
                   8656: treatment; in the context of a block it causes all characters until the
                   8657: end of the current 64-character ``line'' to be ignored.
                   8658: @end itemize
                   8659: 
                   8660: In Gforth, when you use @code{block} with a non-existent block number,
1.45      crook    8661: the current blocks file will be extended to the appropriate size and the
1.28      crook    8662: block buffer will be initialised with spaces.
                   8663: 
1.47      crook    8664: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
                   8665: for details) but doesn't encourage the use of blocks; the mechanism is
                   8666: only provided for backward compatibility -- ANS Forth requires blocks to
                   8667: be available when files are.
1.28      crook    8668: 
                   8669: Common techniques that are used when working with blocks include:
                   8670: 
                   8671: @itemize @bullet
                   8672: @item
                   8673: A screen editor that allows you to edit blocks without leaving the Forth
                   8674: environment.
                   8675: @item
                   8676: Shadow screens; where every code block has an associated block
                   8677: containing comments (for example: code in odd block numbers, comments in
                   8678: even block numbers). Typically, the block editor provides a convenient
                   8679: mechanism to toggle between code and comments.
                   8680: @item
                   8681: Load blocks; a single block (typically block 1) contains a number of
                   8682: @code{thru} commands which @code{load} the whole of the application.
                   8683: @end itemize
1.26      crook    8684: 
1.29      crook    8685: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   8686: integrated into a Forth programming environment.
1.26      crook    8687: 
                   8688: @comment TODO what about errors on open-blocks?
1.44      crook    8689: 
1.26      crook    8690: doc-open-blocks
                   8691: doc-use
1.75      anton    8692: doc-block-offset
1.26      crook    8693: doc-get-block-fid
                   8694: doc-block-position
1.28      crook    8695: 
1.75      anton    8696: doc-list
1.28      crook    8697: doc-scr
                   8698: 
1.45      crook    8699: doc---gforthman-block
1.28      crook    8700: doc-buffer
                   8701: 
1.75      anton    8702: doc-empty-buffers
                   8703: doc-empty-buffer
1.26      crook    8704: doc-update
1.28      crook    8705: doc-updated?
1.26      crook    8706: doc-save-buffers
1.75      anton    8707: doc-save-buffer
1.26      crook    8708: doc-flush
1.28      crook    8709: 
1.26      crook    8710: doc-load
                   8711: doc-thru
                   8712: doc-+load
                   8713: doc-+thru
1.45      crook    8714: doc---gforthman--->
1.26      crook    8715: doc-block-included
                   8716: 
1.44      crook    8717: 
1.26      crook    8718: @c -------------------------------------------------------------
1.126     pazsan   8719: @node Other I/O, OS command line arguments, Blocks, Words
1.26      crook    8720: @section Other I/O
1.28      crook    8721: @cindex I/O - keyboard and display
1.26      crook    8722: 
                   8723: @menu
                   8724: * Simple numeric output::       Predefined formats
                   8725: * Formatted numeric output::    Formatted (pictured) output
                   8726: * String Formats::              How Forth stores strings in memory
1.67      anton    8727: * Displaying characters and strings::  Other stuff
1.175     anton    8728: * Terminal output::             Cursor positioning etc.
1.181     anton    8729: * Single-key input::            
                   8730: * Line input and conversion::   
1.112     anton    8731: * Pipes::                       How to create your own pipes
1.149     pazsan   8732: * Xchars and Unicode::          Non-ASCII characters
1.26      crook    8733: @end menu
                   8734: 
                   8735: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   8736: @subsection Simple numeric output
1.28      crook    8737: @cindex numeric output - simple/free-format
1.5       anton    8738: 
1.26      crook    8739: The simplest output functions are those that display numbers from the
                   8740: data or floating-point stacks. Floating-point output is always displayed
                   8741: using base 10. Numbers displayed from the data stack use the value stored
                   8742: in @code{base}.
1.5       anton    8743: 
1.44      crook    8744: 
1.26      crook    8745: doc-.
                   8746: doc-dec.
                   8747: doc-hex.
                   8748: doc-u.
                   8749: doc-.r
                   8750: doc-u.r
                   8751: doc-d.
                   8752: doc-ud.
                   8753: doc-d.r
                   8754: doc-ud.r
                   8755: doc-f.
                   8756: doc-fe.
                   8757: doc-fs.
1.111     anton    8758: doc-f.rdp
1.44      crook    8759: 
1.26      crook    8760: Examples of printing the number 1234.5678E23 in the different floating-point output
                   8761: formats are shown below:
1.5       anton    8762: 
                   8763: @example
1.26      crook    8764: f. 123456779999999000000000000.
                   8765: fe. 123.456779999999E24
                   8766: fs. 1.23456779999999E26
1.5       anton    8767: @end example
                   8768: 
                   8769: 
1.26      crook    8770: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   8771: @subsection Formatted numeric output
1.28      crook    8772: @cindex formatted numeric output
1.26      crook    8773: @cindex pictured numeric output
1.28      crook    8774: @cindex numeric output - formatted
1.26      crook    8775: 
1.29      crook    8776: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    8777: output} for formatted printing of integers.  In this technique, digits
                   8778: are extracted from the number (using the current output radix defined by
                   8779: @code{base}), converted to ASCII codes and appended to a string that is
                   8780: built in a scratch-pad area of memory (@pxref{core-idef,
                   8781: Implementation-defined options, Implementation-defined
                   8782: options}). Arbitrary characters can be appended to the string during the
                   8783: extraction process. The completed string is specified by an address
                   8784: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   8785: under program control.
1.5       anton    8786: 
1.75      anton    8787: All of the integer output words described in the previous section
                   8788: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
                   8789: numeric output.
1.5       anton    8790: 
1.47      crook    8791: Three important things to remember about pictured numeric output:
1.5       anton    8792: 
1.26      crook    8793: @itemize @bullet
                   8794: @item
1.28      crook    8795: It always operates on double-precision numbers; to display a
1.49      anton    8796: single-precision number, convert it first (for ways of doing this
                   8797: @pxref{Double precision}).
1.26      crook    8798: @item
1.28      crook    8799: It always treats the double-precision number as though it were
                   8800: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    8801: @item
                   8802: The string is built up from right to left; least significant digit first.
                   8803: @end itemize
1.5       anton    8804: 
1.44      crook    8805: 
1.26      crook    8806: doc-<#
1.47      crook    8807: doc-<<#
1.26      crook    8808: doc-#
                   8809: doc-#s
                   8810: doc-hold
                   8811: doc-sign
                   8812: doc-#>
1.47      crook    8813: doc-#>>
1.5       anton    8814: 
1.26      crook    8815: doc-represent
1.111     anton    8816: doc-f>str-rdp
                   8817: doc-f>buf-rdp
1.5       anton    8818: 
1.44      crook    8819: 
                   8820: @noindent
1.26      crook    8821: Here are some examples of using pictured numeric output:
1.5       anton    8822: 
                   8823: @example
1.26      crook    8824: : my-u. ( u -- )
                   8825:   \ Simplest use of pns.. behaves like Standard u. 
                   8826:   0              \ convert to unsigned double
1.75      anton    8827:   <<#            \ start conversion
1.26      crook    8828:   #s             \ convert all digits
                   8829:   #>             \ complete conversion
1.75      anton    8830:   TYPE SPACE     \ display, with trailing space
                   8831:   #>> ;          \ release hold area
1.5       anton    8832: 
1.26      crook    8833: : cents-only ( u -- )
                   8834:   0              \ convert to unsigned double
1.75      anton    8835:   <<#            \ start conversion
1.26      crook    8836:   # #            \ convert two least-significant digits
                   8837:   #>             \ complete conversion, discard other digits
1.75      anton    8838:   TYPE SPACE     \ display, with trailing space
                   8839:   #>> ;          \ release hold area
1.5       anton    8840: 
1.26      crook    8841: : dollars-and-cents ( u -- )
                   8842:   0              \ convert to unsigned double
1.75      anton    8843:   <<#            \ start conversion
1.26      crook    8844:   # #            \ convert two least-significant digits
                   8845:   [char] . hold  \ insert decimal point
                   8846:   #s             \ convert remaining digits
                   8847:   [char] $ hold  \ append currency symbol
                   8848:   #>             \ complete conversion
1.75      anton    8849:   TYPE SPACE     \ display, with trailing space
                   8850:   #>> ;          \ release hold area
1.5       anton    8851: 
1.26      crook    8852: : my-. ( n -- )
                   8853:   \ handling negatives.. behaves like Standard .
                   8854:   s>d            \ convert to signed double
                   8855:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    8856:   <<#            \ start conversion
1.26      crook    8857:   #s             \ convert all digits
                   8858:   rot sign       \ get at sign byte, append "-" if needed
                   8859:   #>             \ complete conversion
1.75      anton    8860:   TYPE SPACE     \ display, with trailing space
                   8861:   #>> ;          \ release hold area
1.5       anton    8862: 
1.26      crook    8863: : account. ( n -- )
1.75      anton    8864:   \ accountants don't like minus signs, they use parentheses
1.26      crook    8865:   \ for negative numbers
                   8866:   s>d            \ convert to signed double
                   8867:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    8868:   <<#            \ start conversion
1.26      crook    8869:   2 pick         \ get copy of sign byte
                   8870:   0< IF [char] ) hold THEN \ right-most character of output
                   8871:   #s             \ convert all digits
                   8872:   rot            \ get at sign byte
                   8873:   0< IF [char] ( hold THEN
                   8874:   #>             \ complete conversion
1.75      anton    8875:   TYPE SPACE     \ display, with trailing space
                   8876:   #>> ;          \ release hold area
                   8877: 
1.5       anton    8878: @end example
                   8879: 
1.26      crook    8880: Here are some examples of using these words:
1.5       anton    8881: 
                   8882: @example
1.26      crook    8883: 1 my-u. 1
                   8884: hex -1 my-u. decimal FFFFFFFF
                   8885: 1 cents-only 01
                   8886: 1234 cents-only 34
                   8887: 2 dollars-and-cents $0.02
                   8888: 1234 dollars-and-cents $12.34
                   8889: 123 my-. 123
                   8890: -123 my. -123
                   8891: 123 account. 123
                   8892: -456 account. (456)
1.5       anton    8893: @end example
                   8894: 
                   8895: 
1.26      crook    8896: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   8897: @subsection String Formats
1.27      crook    8898: @cindex strings - see character strings
                   8899: @cindex character strings - formats
1.28      crook    8900: @cindex I/O - see character strings
1.75      anton    8901: @cindex counted strings
                   8902: 
                   8903: @c anton: this does not really belong here; maybe the memory section,
                   8904: @c  or the principles chapter
1.26      crook    8905: 
1.27      crook    8906: Forth commonly uses two different methods for representing character
                   8907: strings:
1.26      crook    8908: 
                   8909: @itemize @bullet
                   8910: @item
                   8911: @cindex address of counted string
1.45      crook    8912: @cindex counted string
1.29      crook    8913: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   8914: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   8915: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    8916: memory.
                   8917: @item
1.29      crook    8918: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   8919: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    8920: first byte of the string.
                   8921: @end itemize
                   8922: 
                   8923: ANS Forth encourages the use of the second format when representing
1.75      anton    8924: strings.
1.26      crook    8925: 
1.44      crook    8926: 
1.26      crook    8927: doc-count
                   8928: 
1.44      crook    8929: 
1.49      anton    8930: For words that move, copy and search for strings see @ref{Memory
                   8931: Blocks}. For words that display characters and strings see
                   8932: @ref{Displaying characters and strings}.
1.26      crook    8933: 
1.175     anton    8934: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
1.26      crook    8935: @subsection Displaying characters and strings
1.27      crook    8936: @cindex characters - compiling and displaying
                   8937: @cindex character strings - compiling and displaying
1.26      crook    8938: 
                   8939: This section starts with a glossary of Forth words and ends with a set
                   8940: of examples.
                   8941: 
                   8942: doc-bl
                   8943: doc-space
                   8944: doc-spaces
                   8945: doc-emit
                   8946: doc-toupper
                   8947: doc-."
                   8948: doc-.(
1.98      anton    8949: doc-.\"
1.26      crook    8950: doc-type
1.44      crook    8951: doc-typewhite
1.26      crook    8952: doc-cr
1.27      crook    8953: @cindex cursor control
1.26      crook    8954: doc-s"
1.98      anton    8955: doc-s\"
1.26      crook    8956: doc-c"
                   8957: doc-char
                   8958: doc-[char]
                   8959: 
1.44      crook    8960: 
                   8961: @noindent
1.26      crook    8962: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    8963: 
                   8964: @example
1.26      crook    8965: .( text-1)
                   8966: : my-word
                   8967:   ." text-2" cr
                   8968:   .( text-3)
                   8969: ;
                   8970: 
                   8971: ." text-4"
                   8972: 
                   8973: : my-char
                   8974:   [char] ALPHABET emit
                   8975:   char emit
                   8976: ;
1.5       anton    8977: @end example
                   8978: 
1.26      crook    8979: When you load this code into Gforth, the following output is generated:
1.5       anton    8980: 
1.26      crook    8981: @example
1.30      anton    8982: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    8983: @end example
1.5       anton    8984: 
1.26      crook    8985: @itemize @bullet
                   8986: @item
                   8987: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   8988: is an immediate word; it behaves in the same way whether it is used inside
                   8989: or outside a colon definition.
                   8990: @item
                   8991: Message @code{text-4} is displayed because of Gforth's added interpretation
                   8992: semantics for @code{."}.
                   8993: @item
1.29      crook    8994: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    8995: performs the compilation semantics for @code{."} within the definition of
                   8996: @code{my-word}.
                   8997: @end itemize
1.5       anton    8998: 
1.26      crook    8999: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    9000: 
1.26      crook    9001: @example
1.30      anton    9002: @kbd{my-word @key{RET}} text-2
1.26      crook    9003:  ok
1.30      anton    9004: @kbd{my-char fred @key{RET}} Af ok
                   9005: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    9006: @end example
1.5       anton    9007: 
                   9008: @itemize @bullet
                   9009: @item
1.26      crook    9010: Message @code{text-2} is displayed because of the run-time behaviour of
                   9011: @code{."}.
                   9012: @item
                   9013: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   9014: on the stack at run-time. @code{emit} always displays the character
                   9015: when @code{my-char} is executed.
                   9016: @item
                   9017: @code{char} parses a string at run-time and the second @code{emit} displays
                   9018: the first character of the string.
1.5       anton    9019: @item
1.26      crook    9020: If you type @code{see my-char} you can see that @code{[char]} discarded
                   9021: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   9022: definition of @code{my-char}.
1.5       anton    9023: @end itemize
                   9024: 
                   9025: 
1.181     anton    9026: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
1.175     anton    9027: @subsection Terminal output
                   9028: @cindex output to terminal
                   9029: @cindex terminal output
                   9030: 
                   9031: If you are outputting to a terminal, you may want to control the
                   9032: positioning of the cursor:
                   9033: @cindex cursor positioning
                   9034: 
                   9035: doc-at-xy
                   9036: 
                   9037: In order to know where to position the cursor, it is often helpful to
                   9038: know the size of the screen:
                   9039: @cindex terminal size 
                   9040: 
                   9041: doc-form
                   9042: 
                   9043: And sometimes you want to use:
                   9044: @cindex clear screen
                   9045: 
                   9046: doc-page
                   9047: 
                   9048: Note that on non-terminals you should use @code{12 emit}, not
                   9049: @code{page}, to get a form feed.
                   9050: 
1.5       anton    9051: 
1.181     anton    9052: @node Single-key input, Line input and conversion, Terminal output, Other I/O
                   9053: @subsection Single-key input
                   9054: @cindex single-key input
                   9055: @cindex input, single-key
                   9056: 
                   9057: If you want to get a single printable character, you can use
                   9058: @code{key}; to check whether a character is available for @code{key},
                   9059: you can use @code{key?}.
1.5       anton    9060: 
1.181     anton    9061: doc-key
                   9062: doc-key?
1.27      crook    9063: 
1.181     anton    9064: If you want to process a mix of printable and non-printable
                   9065: characters, you can do that with @code{ekey} and friends.  @code{Ekey}
                   9066: produces a keyboard event that you have to convert into a character
                   9067: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
                   9068: 
                   9069: Typical code for using EKEY looks like this:
                   9070: 
                   9071: @example
                   9072: ekey ekey>char if ( c )
                   9073:   ... \ do something with the character
                   9074: else ekey>fkey if ( key-id )
                   9075:   case
                   9076:     k-up                                  of ... endof
                   9077:     k-f1                                  of ... endof
                   9078:     k-left k-shift-mask or k-ctrl-mask or of ... endof
                   9079:     ...
                   9080:   endcase
                   9081: else ( keyboard-event )
                   9082:   drop \ just ignore an unknown keyboard event type
                   9083: then then
                   9084: @end example
1.44      crook    9085: 
1.45      crook    9086: doc-ekey
1.141     anton    9087: doc-ekey>char
1.181     anton    9088: doc-ekey>fkey
1.45      crook    9089: doc-ekey?
1.141     anton    9090: 
1.181     anton    9091: The key identifiers for cursor keys are:
1.141     anton    9092: 
                   9093: doc-k-left
                   9094: doc-k-right
                   9095: doc-k-up       
                   9096: doc-k-down     
                   9097: doc-k-home     
                   9098: doc-k-end      
                   9099: doc-k-prior
                   9100: doc-k-next
                   9101: doc-k-insert
                   9102: doc-k-delete
                   9103: 
1.181     anton    9104: The key identifiers for function keys (aka keypad keys) are:
1.141     anton    9105: 
1.181     anton    9106: doc-k-f1
                   9107: doc-k-f2
                   9108: doc-k-f3
                   9109: doc-k-f4
                   9110: doc-k-f5
                   9111: doc-k-f6
                   9112: doc-k-f7
                   9113: doc-k-f8
                   9114: doc-k-f9
                   9115: doc-k-f10
                   9116: doc-k-f11
                   9117: doc-k-f12
                   9118: 
                   9119: Note that @code{k-f11} and @code{k-f12} are not as widely available.
                   9120: 
                   9121: You can combine these key identifiers with masks for various shift keys:
                   9122: 
                   9123: doc-k-shift-mask
                   9124: doc-k-ctrl-mask
                   9125: doc-k-alt-mask
                   9126: 
                   9127: Note that, even if a Forth system has @code{ekey>fkey} and the key
                   9128: identifier words, the keys are not necessarily available or it may not
                   9129: necessarily be able to report all the keys and all the possible
                   9130: combinations with shift masks.  Therefore, write your programs in such
                   9131: a way that they are still useful even if the keys and key combinations
                   9132: cannot be pressed or are not recognized.
                   9133: 
                   9134: Examples: Older keyboards often do not have an F11 and F12 key.  If
                   9135: you run Gforth in an xterm, the xterm catches a number of combinations
                   9136: (e.g., @key{Shift-Up}), and never passes it to Gforth.  Finally,
                   9137: Gforth currently does not recognize and report combinations with
                   9138: multiple shift keys (so the @key{shift-ctrl-left} case in the example
                   9139: above would never be entered).
                   9140: 
                   9141: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
                   9142: you need the ANSI.SYS driver to get that behaviour); it works by
                   9143: recognizing the escape sequences that ANSI terminals send when such a
                   9144: key is pressed.  If you have a terminal that sends other escape
                   9145: sequences, you will not get useful results on Gforth.  Other Forth
                   9146: systems may work in a different way.
                   9147: 
                   9148: 
                   9149: @node  Line input and conversion, Pipes, Single-key input, Other I/O
                   9150: @subsection Line input and conversion
                   9151: @cindex line input from terminal
                   9152: @cindex input, linewise from terminal
                   9153: @cindex convertin strings to numbers
                   9154: @cindex I/O - see input
                   9155: 
                   9156: For ways of storing character strings in memory see @ref{String Formats}.
                   9157: 
                   9158: @comment TODO examples for >number >float accept key key? pad parse word refill
                   9159: @comment then index them
1.141     anton    9160: 
                   9161: Words for inputting one line from the keyboard:
                   9162: 
                   9163: doc-accept
                   9164: doc-edit-line
                   9165: 
                   9166: Conversion words:
                   9167: 
1.143     anton    9168: doc-s>number?
                   9169: doc-s>unumber?
1.26      crook    9170: doc->number
                   9171: doc->float
1.143     anton    9172: 
1.141     anton    9173: 
1.27      crook    9174: @comment obsolescent words..
1.141     anton    9175: Obsolescent input and conversion words:
                   9176: 
1.27      crook    9177: doc-convert
1.26      crook    9178: doc-expect
1.27      crook    9179: doc-span
1.5       anton    9180: 
                   9181: 
1.181     anton    9182: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
1.112     anton    9183: @subsection Pipes
                   9184: @cindex pipes, creating your own
                   9185: 
                   9186: In addition to using Gforth in pipes created by other processes
                   9187: (@pxref{Gforth in pipes}), you can create your own pipe with
                   9188: @code{open-pipe}, and read from or write to it.
                   9189: 
                   9190: doc-open-pipe
                   9191: doc-close-pipe
                   9192: 
                   9193: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
                   9194: you don't catch this exception, Gforth will catch it and exit, usually
                   9195: silently (@pxref{Gforth in pipes}).  Since you probably do not want
                   9196: this, you should wrap a @code{catch} or @code{try} block around the code
                   9197: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
                   9198: problem yourself, and then return to regular processing.
                   9199: 
                   9200: doc-broken-pipe-error
                   9201: 
1.155     anton    9202: @node Xchars and Unicode,  , Pipes, Other I/O
                   9203: @subsection Xchars and Unicode
1.149     pazsan   9204: 
                   9205: This chapter needs completion
1.112     anton    9206: 
1.121     anton    9207: @node OS command line arguments, Locals, Other I/O, Words
                   9208: @section OS command line arguments
                   9209: @cindex OS command line arguments
                   9210: @cindex command line arguments, OS
                   9211: @cindex arguments, OS command line
                   9212: 
                   9213: The usual way to pass arguments to Gforth programs on the command line
                   9214: is via the @option{-e} option, e.g.
                   9215: 
                   9216: @example
                   9217: gforth -e "123 456" foo.fs -e bye
                   9218: @end example
                   9219: 
                   9220: However, you may want to interpret the command-line arguments directly.
                   9221: In that case, you can access the (image-specific) command-line arguments
1.123     anton    9222: through @code{next-arg}:
1.121     anton    9223: 
1.123     anton    9224: doc-next-arg
1.121     anton    9225: 
1.123     anton    9226: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121     anton    9227: 
                   9228: @example
                   9229: : echo ( -- )
1.122     anton    9230:     begin
1.123     anton    9231:        next-arg 2dup 0 0 d<> while
                   9232:            type space
                   9233:     repeat
                   9234:     2drop ;
1.121     anton    9235: 
                   9236: echo cr bye
                   9237: @end example
                   9238: 
                   9239: This can be invoked with
                   9240: 
                   9241: @example
                   9242: gforth echo.fs hello world
                   9243: @end example
1.123     anton    9244: 
                   9245: and it will print
                   9246: 
                   9247: @example
                   9248: hello world
                   9249: @end example
                   9250: 
                   9251: The next lower level of dealing with the OS command line are the
                   9252: following words:
                   9253: 
                   9254: doc-arg
                   9255: doc-shift-args
                   9256: 
                   9257: Finally, at the lowest level Gforth provides the following words:
                   9258: 
                   9259: doc-argc
                   9260: doc-argv
1.121     anton    9261: 
1.78      anton    9262: @c -------------------------------------------------------------
1.126     pazsan   9263: @node Locals, Structures, OS command line arguments, Words
1.78      anton    9264: @section Locals
                   9265: @cindex locals
                   9266: 
                   9267: Local variables can make Forth programming more enjoyable and Forth
                   9268: programs easier to read. Unfortunately, the locals of ANS Forth are
                   9269: laden with restrictions. Therefore, we provide not only the ANS Forth
                   9270: locals wordset, but also our own, more powerful locals wordset (we
                   9271: implemented the ANS Forth locals wordset through our locals wordset).
1.44      crook    9272: 
1.78      anton    9273: The ideas in this section have also been published in M. Anton Ertl,
                   9274: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
                   9275: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12      anton    9276: 
                   9277: @menu
1.78      anton    9278: * Gforth locals::               
                   9279: * ANS Forth locals::            
1.5       anton    9280: @end menu
                   9281: 
1.78      anton    9282: @node Gforth locals, ANS Forth locals, Locals, Locals
                   9283: @subsection Gforth locals
                   9284: @cindex Gforth locals
                   9285: @cindex locals, Gforth style
1.5       anton    9286: 
1.78      anton    9287: Locals can be defined with
1.44      crook    9288: 
1.78      anton    9289: @example
                   9290: @{ local1 local2 ... -- comment @}
                   9291: @end example
                   9292: or
                   9293: @example
                   9294: @{ local1 local2 ... @}
                   9295: @end example
1.5       anton    9296: 
1.78      anton    9297: E.g.,
                   9298: @example
                   9299: : max @{ n1 n2 -- n3 @}
                   9300:  n1 n2 > if
                   9301:    n1
                   9302:  else
                   9303:    n2
                   9304:  endif ;
                   9305: @end example
1.44      crook    9306: 
1.78      anton    9307: The similarity of locals definitions with stack comments is intended. A
                   9308: locals definition often replaces the stack comment of a word. The order
                   9309: of the locals corresponds to the order in a stack comment and everything
                   9310: after the @code{--} is really a comment.
1.77      anton    9311: 
1.78      anton    9312: This similarity has one disadvantage: It is too easy to confuse locals
                   9313: declarations with stack comments, causing bugs and making them hard to
                   9314: find. However, this problem can be avoided by appropriate coding
                   9315: conventions: Do not use both notations in the same program. If you do,
                   9316: they should be distinguished using additional means, e.g. by position.
1.77      anton    9317: 
1.78      anton    9318: @cindex types of locals
                   9319: @cindex locals types
                   9320: The name of the local may be preceded by a type specifier, e.g.,
                   9321: @code{F:} for a floating point value:
1.5       anton    9322: 
1.78      anton    9323: @example
                   9324: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   9325: \ complex multiplication
                   9326:  Ar Br f* Ai Bi f* f-
                   9327:  Ar Bi f* Ai Br f* f+ ;
                   9328: @end example
1.44      crook    9329: 
1.78      anton    9330: @cindex flavours of locals
                   9331: @cindex locals flavours
                   9332: @cindex value-flavoured locals
                   9333: @cindex variable-flavoured locals
                   9334: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   9335: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   9336: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   9337: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   9338: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   9339: produces its address (which becomes invalid when the variable's scope is
                   9340: left). E.g., the standard word @code{emit} can be defined in terms of
                   9341: @code{type} like this:
1.5       anton    9342: 
1.78      anton    9343: @example
                   9344: : emit @{ C^ char* -- @}
                   9345:     char* 1 type ;
                   9346: @end example
1.5       anton    9347: 
1.78      anton    9348: @cindex default type of locals
                   9349: @cindex locals, default type
                   9350: A local without type specifier is a @code{W:} local. Both flavours of
                   9351: locals are initialized with values from the data or FP stack.
1.44      crook    9352: 
1.78      anton    9353: Currently there is no way to define locals with user-defined data
                   9354: structures, but we are working on it.
1.5       anton    9355: 
1.78      anton    9356: Gforth allows defining locals everywhere in a colon definition. This
                   9357: poses the following questions:
1.5       anton    9358: 
1.78      anton    9359: @menu
                   9360: * Where are locals visible by name?::  
                   9361: * How long do locals live?::    
                   9362: * Locals programming style::    
                   9363: * Locals implementation::       
                   9364: @end menu
1.44      crook    9365: 
1.78      anton    9366: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   9367: @subsubsection Where are locals visible by name?
                   9368: @cindex locals visibility
                   9369: @cindex visibility of locals
                   9370: @cindex scope of locals
1.5       anton    9371: 
1.78      anton    9372: Basically, the answer is that locals are visible where you would expect
                   9373: it in block-structured languages, and sometimes a little longer. If you
                   9374: want to restrict the scope of a local, enclose its definition in
                   9375: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    9376: 
                   9377: 
1.78      anton    9378: doc-scope
                   9379: doc-endscope
1.5       anton    9380: 
                   9381: 
1.78      anton    9382: These words behave like control structure words, so you can use them
                   9383: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   9384: arbitrary ways.
1.77      anton    9385: 
1.78      anton    9386: If you want a more exact answer to the visibility question, here's the
                   9387: basic principle: A local is visible in all places that can only be
                   9388: reached through the definition of the local@footnote{In compiler
                   9389: construction terminology, all places dominated by the definition of the
                   9390: local.}. In other words, it is not visible in places that can be reached
                   9391: without going through the definition of the local. E.g., locals defined
                   9392: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   9393: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   9394: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77      anton    9395: 
1.78      anton    9396: The reasoning behind this solution is: We want to have the locals
                   9397: visible as long as it is meaningful. The user can always make the
                   9398: visibility shorter by using explicit scoping. In a place that can
                   9399: only be reached through the definition of a local, the meaning of a
                   9400: local name is clear. In other places it is not: How is the local
                   9401: initialized at the control flow path that does not contain the
                   9402: definition? Which local is meant, if the same name is defined twice in
                   9403: two independent control flow paths?
1.77      anton    9404: 
1.78      anton    9405: This should be enough detail for nearly all users, so you can skip the
                   9406: rest of this section. If you really must know all the gory details and
                   9407: options, read on.
1.77      anton    9408: 
1.78      anton    9409: In order to implement this rule, the compiler has to know which places
                   9410: are unreachable. It knows this automatically after @code{AHEAD},
                   9411: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   9412: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   9413: compiler that the control flow never reaches that place. If
                   9414: @code{UNREACHABLE} is not used where it could, the only consequence is
                   9415: that the visibility of some locals is more limited than the rule above
                   9416: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   9417: lie to the compiler), buggy code will be produced.
1.77      anton    9418: 
1.5       anton    9419: 
1.78      anton    9420: doc-unreachable
1.5       anton    9421: 
1.23      crook    9422: 
1.78      anton    9423: Another problem with this rule is that at @code{BEGIN}, the compiler
                   9424: does not know which locals will be visible on the incoming
                   9425: back-edge. All problems discussed in the following are due to this
                   9426: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   9427: loops as examples; the discussion also applies to @code{?DO} and other
                   9428: loops). Perhaps the most insidious example is:
1.26      crook    9429: @example
1.78      anton    9430: AHEAD
                   9431: BEGIN
                   9432:   x
                   9433: [ 1 CS-ROLL ] THEN
                   9434:   @{ x @}
                   9435:   ...
                   9436: UNTIL
1.26      crook    9437: @end example
1.23      crook    9438: 
1.78      anton    9439: This should be legal according to the visibility rule. The use of
                   9440: @code{x} can only be reached through the definition; but that appears
                   9441: textually below the use.
                   9442: 
                   9443: From this example it is clear that the visibility rules cannot be fully
                   9444: implemented without major headaches. Our implementation treats common
                   9445: cases as advertised and the exceptions are treated in a safe way: The
                   9446: compiler makes a reasonable guess about the locals visible after a
                   9447: @code{BEGIN}; if it is too pessimistic, the
                   9448: user will get a spurious error about the local not being defined; if the
                   9449: compiler is too optimistic, it will notice this later and issue a
                   9450: warning. In the case above the compiler would complain about @code{x}
                   9451: being undefined at its use. You can see from the obscure examples in
                   9452: this section that it takes quite unusual control structures to get the
                   9453: compiler into trouble, and even then it will often do fine.
1.23      crook    9454: 
1.78      anton    9455: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   9456: is that all locals visible before the @code{BEGIN} will also be
                   9457: visible after the @code{BEGIN}. This guess is valid for all loops that
                   9458: are entered only through the @code{BEGIN}, in particular, for normal
                   9459: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   9460: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   9461: compiler. When the branch to the @code{BEGIN} is finally generated by
                   9462: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   9463: warns the user if it was too optimistic:
1.26      crook    9464: @example
1.78      anton    9465: IF
                   9466:   @{ x @}
                   9467: BEGIN
                   9468:   \ x ? 
                   9469: [ 1 cs-roll ] THEN
                   9470:   ...
                   9471: UNTIL
1.26      crook    9472: @end example
1.23      crook    9473: 
1.78      anton    9474: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   9475: optimistically assumes that it lives until the @code{THEN}. It notices
                   9476: this difference when it compiles the @code{UNTIL} and issues a
                   9477: warning. The user can avoid the warning, and make sure that @code{x}
                   9478: is not used in the wrong area by using explicit scoping:
                   9479: @example
                   9480: IF
                   9481:   SCOPE
                   9482:   @{ x @}
                   9483:   ENDSCOPE
                   9484: BEGIN
                   9485: [ 1 cs-roll ] THEN
                   9486:   ...
                   9487: UNTIL
                   9488: @end example
1.23      crook    9489: 
1.78      anton    9490: Since the guess is optimistic, there will be no spurious error messages
                   9491: about undefined locals.
1.44      crook    9492: 
1.78      anton    9493: If the @code{BEGIN} is not reachable from above (e.g., after
                   9494: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   9495: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   9496: defined later. Therefore, the compiler assumes that no locals are
                   9497: visible after the @code{BEGIN}. However, the user can use
                   9498: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   9499: visible at the BEGIN as at the point where the top control-flow stack
                   9500: item was created.
1.23      crook    9501: 
1.44      crook    9502: 
1.78      anton    9503: doc-assume-live
1.26      crook    9504: 
1.23      crook    9505: 
1.78      anton    9506: @noindent
                   9507: E.g.,
                   9508: @example
                   9509: @{ x @}
                   9510: AHEAD
                   9511: ASSUME-LIVE
                   9512: BEGIN
                   9513:   x
                   9514: [ 1 CS-ROLL ] THEN
                   9515:   ...
                   9516: UNTIL
                   9517: @end example
1.44      crook    9518: 
1.78      anton    9519: Other cases where the locals are defined before the @code{BEGIN} can be
                   9520: handled by inserting an appropriate @code{CS-ROLL} before the
                   9521: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   9522: behind the @code{ASSUME-LIVE}).
1.23      crook    9523: 
1.78      anton    9524: Cases where locals are defined after the @code{BEGIN} (but should be
                   9525: visible immediately after the @code{BEGIN}) can only be handled by
                   9526: rearranging the loop. E.g., the ``most insidious'' example above can be
                   9527: arranged into:
                   9528: @example
                   9529: BEGIN
                   9530:   @{ x @}
                   9531:   ... 0=
                   9532: WHILE
                   9533:   x
                   9534: REPEAT
                   9535: @end example
1.44      crook    9536: 
1.78      anton    9537: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
                   9538: @subsubsection How long do locals live?
                   9539: @cindex locals lifetime
                   9540: @cindex lifetime of locals
1.23      crook    9541: 
1.78      anton    9542: The right answer for the lifetime question would be: A local lives at
                   9543: least as long as it can be accessed. For a value-flavoured local this
                   9544: means: until the end of its visibility. However, a variable-flavoured
                   9545: local could be accessed through its address far beyond its visibility
                   9546: scope. Ultimately, this would mean that such locals would have to be
                   9547: garbage collected. Since this entails un-Forth-like implementation
                   9548: complexities, I adopted the same cowardly solution as some other
                   9549: languages (e.g., C): The local lives only as long as it is visible;
                   9550: afterwards its address is invalid (and programs that access it
                   9551: afterwards are erroneous).
1.23      crook    9552: 
1.78      anton    9553: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
                   9554: @subsubsection Locals programming style
                   9555: @cindex locals programming style
                   9556: @cindex programming style, locals
1.23      crook    9557: 
1.78      anton    9558: The freedom to define locals anywhere has the potential to change
                   9559: programming styles dramatically. In particular, the need to use the
                   9560: return stack for intermediate storage vanishes. Moreover, all stack
                   9561: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   9562: determined arguments) can be eliminated: If the stack items are in the
                   9563: wrong order, just write a locals definition for all of them; then
                   9564: write the items in the order you want.
1.23      crook    9565: 
1.78      anton    9566: This seems a little far-fetched and eliminating stack manipulations is
                   9567: unlikely to become a conscious programming objective. Still, the number
                   9568: of stack manipulations will be reduced dramatically if local variables
                   9569: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
                   9570: a traditional implementation of @code{max}).
1.23      crook    9571: 
1.78      anton    9572: This shows one potential benefit of locals: making Forth programs more
                   9573: readable. Of course, this benefit will only be realized if the
                   9574: programmers continue to honour the principle of factoring instead of
                   9575: using the added latitude to make the words longer.
1.23      crook    9576: 
1.78      anton    9577: @cindex single-assignment style for locals
                   9578: Using @code{TO} can and should be avoided.  Without @code{TO},
                   9579: every value-flavoured local has only a single assignment and many
                   9580: advantages of functional languages apply to Forth. I.e., programs are
                   9581: easier to analyse, to optimize and to read: It is clear from the
                   9582: definition what the local stands for, it does not turn into something
                   9583: different later.
1.23      crook    9584: 
1.78      anton    9585: E.g., a definition using @code{TO} might look like this:
                   9586: @example
                   9587: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9588:  u1 u2 min 0
                   9589:  ?do
                   9590:    addr1 c@@ addr2 c@@ -
                   9591:    ?dup-if
                   9592:      unloop exit
                   9593:    then
                   9594:    addr1 char+ TO addr1
                   9595:    addr2 char+ TO addr2
                   9596:  loop
                   9597:  u1 u2 - ;
1.26      crook    9598: @end example
1.78      anton    9599: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   9600: every loop iteration. @code{strcmp} is a typical example of the
                   9601: readability problems of using @code{TO}. When you start reading
                   9602: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   9603: string. Only near the end of the loop you realize that it is something
                   9604: else.
1.23      crook    9605: 
1.78      anton    9606: This can be avoided by defining two locals at the start of the loop that
                   9607: are initialized with the right value for the current iteration.
                   9608: @example
                   9609: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9610:  addr1 addr2
                   9611:  u1 u2 min 0 
                   9612:  ?do @{ s1 s2 @}
                   9613:    s1 c@@ s2 c@@ -
                   9614:    ?dup-if
                   9615:      unloop exit
                   9616:    then
                   9617:    s1 char+ s2 char+
                   9618:  loop
                   9619:  2drop
                   9620:  u1 u2 - ;
                   9621: @end example
                   9622: Here it is clear from the start that @code{s1} has a different value
                   9623: in every loop iteration.
1.23      crook    9624: 
1.78      anton    9625: @node Locals implementation,  , Locals programming style, Gforth locals
                   9626: @subsubsection Locals implementation
                   9627: @cindex locals implementation
                   9628: @cindex implementation of locals
1.23      crook    9629: 
1.78      anton    9630: @cindex locals stack
                   9631: Gforth uses an extra locals stack. The most compelling reason for
                   9632: this is that the return stack is not float-aligned; using an extra stack
                   9633: also eliminates the problems and restrictions of using the return stack
                   9634: as locals stack. Like the other stacks, the locals stack grows toward
                   9635: lower addresses. A few primitives allow an efficient implementation:
                   9636: 
                   9637: 
                   9638: doc-@local#
                   9639: doc-f@local#
                   9640: doc-laddr#
                   9641: doc-lp+!#
                   9642: doc-lp!
                   9643: doc->l
                   9644: doc-f>l
                   9645: 
                   9646: 
                   9647: In addition to these primitives, some specializations of these
                   9648: primitives for commonly occurring inline arguments are provided for
                   9649: efficiency reasons, e.g., @code{@@local0} as specialization of
                   9650: @code{@@local#} for the inline argument 0. The following compiling words
                   9651: compile the right specialized version, or the general version, as
                   9652: appropriate:
1.23      crook    9653: 
1.5       anton    9654: 
1.107     dvdkhlng 9655: @c doc-compile-@local
                   9656: @c doc-compile-f@local
1.78      anton    9657: doc-compile-lp+!
1.5       anton    9658: 
                   9659: 
1.78      anton    9660: Combinations of conditional branches and @code{lp+!#} like
                   9661: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   9662: is taken) are provided for efficiency and correctness in loops.
1.5       anton    9663: 
1.78      anton    9664: A special area in the dictionary space is reserved for keeping the
                   9665: local variable names. @code{@{} switches the dictionary pointer to this
                   9666: area and @code{@}} switches it back and generates the locals
                   9667: initializing code. @code{W:} etc.@ are normal defining words. This
                   9668: special area is cleared at the start of every colon definition.
1.5       anton    9669: 
1.78      anton    9670: @cindex word list for defining locals
                   9671: A special feature of Gforth's dictionary is used to implement the
                   9672: definition of locals without type specifiers: every word list (aka
                   9673: vocabulary) has its own methods for searching
                   9674: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   9675: with a special search method: When it is searched for a word, it
                   9676: actually creates that word using @code{W:}. @code{@{} changes the search
                   9677: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   9678: and then the word list for defining locals without type specifiers.
1.5       anton    9679: 
1.78      anton    9680: The lifetime rules support a stack discipline within a colon
                   9681: definition: The lifetime of a local is either nested with other locals
                   9682: lifetimes or it does not overlap them.
1.23      crook    9683: 
1.78      anton    9684: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   9685: pointer manipulation is generated. Between control structure words
                   9686: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   9687: is the simplest of the other three control flow words. It has to
                   9688: restore the locals stack depth of the corresponding @code{BEGIN}
                   9689: before branching. The code looks like this:
                   9690: @format
                   9691: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   9692: @code{branch} <begin>
                   9693: @end format
1.26      crook    9694: 
1.78      anton    9695: @code{UNTIL} is a little more complicated: If it branches back, it
                   9696: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   9697: the locals stack must not be changed. The compiler generates the
                   9698: following code:
                   9699: @format
                   9700: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   9701: @end format
                   9702: The locals stack pointer is only adjusted if the branch is taken.
1.44      crook    9703: 
1.78      anton    9704: @code{THEN} can produce somewhat inefficient code:
                   9705: @format
                   9706: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   9707: <orig target>:
                   9708: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   9709: @end format
                   9710: The second @code{lp+!#} adjusts the locals stack pointer from the
                   9711: level at the @i{orig} point to the level after the @code{THEN}. The
                   9712: first @code{lp+!#} adjusts the locals stack pointer from the current
                   9713: level to the level at the orig point, so the complete effect is an
                   9714: adjustment from the current level to the right level after the
                   9715: @code{THEN}.
1.26      crook    9716: 
1.78      anton    9717: @cindex locals information on the control-flow stack
                   9718: @cindex control-flow stack items, locals information
                   9719: In a conventional Forth implementation a dest control-flow stack entry
                   9720: is just the target address and an orig entry is just the address to be
                   9721: patched. Our locals implementation adds a word list to every orig or dest
                   9722: item. It is the list of locals visible (or assumed visible) at the point
                   9723: described by the entry. Our implementation also adds a tag to identify
                   9724: the kind of entry, in particular to differentiate between live and dead
                   9725: (reachable and unreachable) orig entries.
1.26      crook    9726: 
1.78      anton    9727: A few unusual operations have to be performed on locals word lists:
1.44      crook    9728: 
1.5       anton    9729: 
1.78      anton    9730: doc-common-list
                   9731: doc-sub-list?
                   9732: doc-list-size
1.52      anton    9733: 
                   9734: 
1.78      anton    9735: Several features of our locals word list implementation make these
                   9736: operations easy to implement: The locals word lists are organised as
                   9737: linked lists; the tails of these lists are shared, if the lists
                   9738: contain some of the same locals; and the address of a name is greater
                   9739: than the address of the names behind it in the list.
1.5       anton    9740: 
1.78      anton    9741: Another important implementation detail is the variable
                   9742: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   9743: determine if they can be reached directly or only through the branch
                   9744: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   9745: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   9746: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5       anton    9747: 
1.78      anton    9748: Counted loops are similar to other loops in most respects, but
                   9749: @code{LEAVE} requires special attention: It performs basically the same
                   9750: service as @code{AHEAD}, but it does not create a control-flow stack
                   9751: entry. Therefore the information has to be stored elsewhere;
                   9752: traditionally, the information was stored in the target fields of the
                   9753: branches created by the @code{LEAVE}s, by organizing these fields into a
                   9754: linked list. Unfortunately, this clever trick does not provide enough
                   9755: space for storing our extended control flow information. Therefore, we
                   9756: introduce another stack, the leave stack. It contains the control-flow
                   9757: stack entries for all unresolved @code{LEAVE}s.
1.44      crook    9758: 
1.78      anton    9759: Local names are kept until the end of the colon definition, even if
                   9760: they are no longer visible in any control-flow path. In a few cases
                   9761: this may lead to increased space needs for the locals name area, but
                   9762: usually less than reclaiming this space would cost in code size.
1.5       anton    9763: 
1.44      crook    9764: 
1.78      anton    9765: @node ANS Forth locals,  , Gforth locals, Locals
                   9766: @subsection ANS Forth locals
                   9767: @cindex locals, ANS Forth style
1.5       anton    9768: 
1.78      anton    9769: The ANS Forth locals wordset does not define a syntax for locals, but
                   9770: words that make it possible to define various syntaxes. One of the
                   9771: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   9772: wordset, i.e.:
1.29      crook    9773: 
                   9774: @example
1.78      anton    9775: @{ local1 local2 ... -- comment @}
                   9776: @end example
                   9777: @noindent
                   9778: or
                   9779: @example
                   9780: @{ local1 local2 ... @}
1.29      crook    9781: @end example
                   9782: 
1.78      anton    9783: The order of the locals corresponds to the order in a stack comment. The
                   9784: restrictions are:
1.5       anton    9785: 
1.78      anton    9786: @itemize @bullet
                   9787: @item
                   9788: Locals can only be cell-sized values (no type specifiers are allowed).
                   9789: @item
                   9790: Locals can be defined only outside control structures.
                   9791: @item
                   9792: Locals can interfere with explicit usage of the return stack. For the
                   9793: exact (and long) rules, see the standard. If you don't use return stack
                   9794: accessing words in a definition using locals, you will be all right. The
                   9795: purpose of this rule is to make locals implementation on the return
                   9796: stack easier.
                   9797: @item
                   9798: The whole definition must be in one line.
                   9799: @end itemize
1.5       anton    9800: 
1.78      anton    9801: Locals defined in ANS Forth behave like @code{VALUE}s
                   9802: (@pxref{Values}). I.e., they are initialized from the stack. Using their
                   9803: name produces their value. Their value can be changed using @code{TO}.
1.77      anton    9804: 
1.78      anton    9805: Since the syntax above is supported by Gforth directly, you need not do
                   9806: anything to use it. If you want to port a program using this syntax to
                   9807: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   9808: syntax on the other system.
1.5       anton    9809: 
1.78      anton    9810: Note that a syntax shown in the standard, section A.13 looks
                   9811: similar, but is quite different in having the order of locals
                   9812: reversed. Beware!
1.5       anton    9813: 
1.78      anton    9814: The ANS Forth locals wordset itself consists of one word:
1.5       anton    9815: 
1.78      anton    9816: doc-(local)
1.5       anton    9817: 
1.78      anton    9818: The ANS Forth locals extension wordset defines a syntax using
                   9819: @code{locals|}, but it is so awful that we strongly recommend not to use
                   9820: it. We have implemented this syntax to make porting to Gforth easy, but
                   9821: do not document it here. The problem with this syntax is that the locals
                   9822: are defined in an order reversed with respect to the standard stack
                   9823: comment notation, making programs harder to read, and easier to misread
                   9824: and miswrite. The only merit of this syntax is that it is easy to
                   9825: implement using the ANS Forth locals wordset.
1.53      anton    9826: 
                   9827: 
1.78      anton    9828: @c ----------------------------------------------------------
                   9829: @node Structures, Object-oriented Forth, Locals, Words
                   9830: @section  Structures
                   9831: @cindex structures
                   9832: @cindex records
1.53      anton    9833: 
1.78      anton    9834: This section presents the structure package that comes with Gforth. A
                   9835: version of the package implemented in ANS Forth is available in
                   9836: @file{compat/struct.fs}. This package was inspired by a posting on
                   9837: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   9838: possibly John Hayes). A version of this section has been published in
                   9839: M. Anton Ertl,
                   9840: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
                   9841: Another Forth Structures Package}, Forth Dimensions 19(3), pages
                   9842: 13--16. Marcel Hendrix provided helpful comments.
1.53      anton    9843: 
1.78      anton    9844: @menu
                   9845: * Why explicit structure support?::  
                   9846: * Structure Usage::             
                   9847: * Structure Naming Convention::  
                   9848: * Structure Implementation::    
                   9849: * Structure Glossary::          
                   9850: @end menu
1.55      anton    9851: 
1.78      anton    9852: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   9853: @subsection Why explicit structure support?
1.53      anton    9854: 
1.78      anton    9855: @cindex address arithmetic for structures
                   9856: @cindex structures using address arithmetic
                   9857: If we want to use a structure containing several fields, we could simply
                   9858: reserve memory for it, and access the fields using address arithmetic
                   9859: (@pxref{Address arithmetic}). As an example, consider a structure with
                   9860: the following fields
1.57      anton    9861: 
1.78      anton    9862: @table @code
                   9863: @item a
                   9864: is a float
                   9865: @item b
                   9866: is a cell
                   9867: @item c
                   9868: is a float
                   9869: @end table
1.57      anton    9870: 
1.78      anton    9871: Given the (float-aligned) base address of the structure we get the
                   9872: address of the field
1.52      anton    9873: 
1.78      anton    9874: @table @code
                   9875: @item a
                   9876: without doing anything further.
                   9877: @item b
                   9878: with @code{float+}
                   9879: @item c
                   9880: with @code{float+ cell+ faligned}
                   9881: @end table
1.52      anton    9882: 
1.78      anton    9883: It is easy to see that this can become quite tiring. 
1.52      anton    9884: 
1.78      anton    9885: Moreover, it is not very readable, because seeing a
                   9886: @code{cell+} tells us neither which kind of structure is
                   9887: accessed nor what field is accessed; we have to somehow infer the kind
                   9888: of structure, and then look up in the documentation, which field of
                   9889: that structure corresponds to that offset.
1.53      anton    9890: 
1.78      anton    9891: Finally, this kind of address arithmetic also causes maintenance
                   9892: troubles: If you add or delete a field somewhere in the middle of the
                   9893: structure, you have to find and change all computations for the fields
                   9894: afterwards.
1.52      anton    9895: 
1.78      anton    9896: So, instead of using @code{cell+} and friends directly, how
                   9897: about storing the offsets in constants:
1.52      anton    9898: 
1.78      anton    9899: @example
                   9900: 0 constant a-offset
                   9901: 0 float+ constant b-offset
                   9902: 0 float+ cell+ faligned c-offset
                   9903: @end example
1.64      pazsan   9904: 
1.78      anton    9905: Now we can get the address of field @code{x} with @code{x-offset
                   9906: +}. This is much better in all respects. Of course, you still
                   9907: have to change all later offset definitions if you add a field. You can
                   9908: fix this by declaring the offsets in the following way:
1.57      anton    9909: 
1.78      anton    9910: @example
                   9911: 0 constant a-offset
                   9912: a-offset float+ constant b-offset
                   9913: b-offset cell+ faligned constant c-offset
                   9914: @end example
1.57      anton    9915: 
1.78      anton    9916: Since we always use the offsets with @code{+}, we could use a defining
                   9917: word @code{cfield} that includes the @code{+} in the action of the
                   9918: defined word:
1.64      pazsan   9919: 
1.78      anton    9920: @example
                   9921: : cfield ( n "name" -- )
                   9922:     create ,
                   9923: does> ( name execution: addr1 -- addr2 )
                   9924:     @@ + ;
1.64      pazsan   9925: 
1.78      anton    9926: 0 cfield a
                   9927: 0 a float+ cfield b
                   9928: 0 b cell+ faligned cfield c
                   9929: @end example
1.64      pazsan   9930: 
1.78      anton    9931: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64      pazsan   9932: 
1.78      anton    9933: The structure field words now can be used quite nicely. However,
                   9934: their definition is still a bit cumbersome: We have to repeat the
                   9935: name, the information about size and alignment is distributed before
                   9936: and after the field definitions etc.  The structure package presented
                   9937: here addresses these problems.
1.64      pazsan   9938: 
1.78      anton    9939: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   9940: @subsection Structure Usage
                   9941: @cindex structure usage
1.57      anton    9942: 
1.78      anton    9943: @cindex @code{field} usage
                   9944: @cindex @code{struct} usage
                   9945: @cindex @code{end-struct} usage
                   9946: You can define a structure for a (data-less) linked list with:
1.57      anton    9947: @example
1.78      anton    9948: struct
                   9949:     cell% field list-next
                   9950: end-struct list%
1.57      anton    9951: @end example
                   9952: 
1.78      anton    9953: With the address of the list node on the stack, you can compute the
                   9954: address of the field that contains the address of the next node with
                   9955: @code{list-next}. E.g., you can determine the length of a list
                   9956: with:
1.57      anton    9957: 
                   9958: @example
1.78      anton    9959: : list-length ( list -- n )
                   9960: \ "list" is a pointer to the first element of a linked list
                   9961: \ "n" is the length of the list
                   9962:     0 BEGIN ( list1 n1 )
                   9963:         over
                   9964:     WHILE ( list1 n1 )
                   9965:         1+ swap list-next @@ swap
                   9966:     REPEAT
                   9967:     nip ;
1.57      anton    9968: @end example
                   9969: 
1.78      anton    9970: You can reserve memory for a list node in the dictionary with
                   9971: @code{list% %allot}, which leaves the address of the list node on the
                   9972: stack. For the equivalent allocation on the heap you can use @code{list%
                   9973: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   9974: use @code{list% %allocate}). You can get the the size of a list
                   9975: node with @code{list% %size} and its alignment with @code{list%
                   9976: %alignment}.
                   9977: 
                   9978: Note that in ANS Forth the body of a @code{create}d word is
                   9979: @code{aligned} but not necessarily @code{faligned};
                   9980: therefore, if you do a:
1.57      anton    9981: 
                   9982: @example
1.78      anton    9983: create @emph{name} foo% %allot drop
1.57      anton    9984: @end example
                   9985: 
1.78      anton    9986: @noindent
                   9987: then the memory alloted for @code{foo%} is guaranteed to start at the
                   9988: body of @code{@emph{name}} only if @code{foo%} contains only character,
                   9989: cell and double fields.  Therefore, if your structure contains floats,
                   9990: better use
1.57      anton    9991: 
                   9992: @example
1.78      anton    9993: foo% %allot constant @emph{name}
1.57      anton    9994: @end example
                   9995: 
1.78      anton    9996: @cindex structures containing structures
                   9997: You can include a structure @code{foo%} as a field of
                   9998: another structure, like this:
1.65      anton    9999: @example
1.78      anton    10000: struct
                   10001: ...
                   10002:     foo% field ...
                   10003: ...
                   10004: end-struct ...
1.65      anton    10005: @end example
1.52      anton    10006: 
1.78      anton    10007: @cindex structure extension
                   10008: @cindex extended records
                   10009: Instead of starting with an empty structure, you can extend an
                   10010: existing structure. E.g., a plain linked list without data, as defined
                   10011: above, is hardly useful; You can extend it to a linked list of integers,
                   10012: like this:@footnote{This feature is also known as @emph{extended
                   10013: records}. It is the main innovation in the Oberon language; in other
                   10014: words, adding this feature to Modula-2 led Wirth to create a new
                   10015: language, write a new compiler etc.  Adding this feature to Forth just
                   10016: required a few lines of code.}
1.52      anton    10017: 
1.78      anton    10018: @example
                   10019: list%
                   10020:     cell% field intlist-int
                   10021: end-struct intlist%
                   10022: @end example
1.55      anton    10023: 
1.78      anton    10024: @code{intlist%} is a structure with two fields:
                   10025: @code{list-next} and @code{intlist-int}.
1.55      anton    10026: 
1.78      anton    10027: @cindex structures containing arrays
                   10028: You can specify an array type containing @emph{n} elements of
                   10029: type @code{foo%} like this:
1.55      anton    10030: 
                   10031: @example
1.78      anton    10032: foo% @emph{n} *
1.56      anton    10033: @end example
1.55      anton    10034: 
1.78      anton    10035: You can use this array type in any place where you can use a normal
                   10036: type, e.g., when defining a @code{field}, or with
                   10037: @code{%allot}.
                   10038: 
                   10039: @cindex first field optimization
                   10040: The first field is at the base address of a structure and the word for
                   10041: this field (e.g., @code{list-next}) actually does not change the address
                   10042: on the stack. You may be tempted to leave it away in the interest of
                   10043: run-time and space efficiency. This is not necessary, because the
                   10044: structure package optimizes this case: If you compile a first-field
                   10045: words, no code is generated. So, in the interest of readability and
                   10046: maintainability you should include the word for the field when accessing
                   10047: the field.
1.52      anton    10048: 
                   10049: 
1.78      anton    10050: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   10051: @subsection Structure Naming Convention
                   10052: @cindex structure naming convention
1.52      anton    10053: 
1.78      anton    10054: The field names that come to (my) mind are often quite generic, and,
                   10055: if used, would cause frequent name clashes. E.g., many structures
                   10056: probably contain a @code{counter} field. The structure names
                   10057: that come to (my) mind are often also the logical choice for the names
                   10058: of words that create such a structure.
1.52      anton    10059: 
1.78      anton    10060: Therefore, I have adopted the following naming conventions: 
1.52      anton    10061: 
1.78      anton    10062: @itemize @bullet
                   10063: @cindex field naming convention
                   10064: @item
                   10065: The names of fields are of the form
                   10066: @code{@emph{struct}-@emph{field}}, where
                   10067: @code{@emph{struct}} is the basic name of the structure, and
                   10068: @code{@emph{field}} is the basic name of the field. You can
                   10069: think of field words as converting the (address of the)
                   10070: structure into the (address of the) field.
1.52      anton    10071: 
1.78      anton    10072: @cindex structure naming convention
                   10073: @item
                   10074: The names of structures are of the form
                   10075: @code{@emph{struct}%}, where
                   10076: @code{@emph{struct}} is the basic name of the structure.
                   10077: @end itemize
1.52      anton    10078: 
1.78      anton    10079: This naming convention does not work that well for fields of extended
                   10080: structures; e.g., the integer list structure has a field
                   10081: @code{intlist-int}, but has @code{list-next}, not
                   10082: @code{intlist-next}.
1.53      anton    10083: 
1.78      anton    10084: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   10085: @subsection Structure Implementation
                   10086: @cindex structure implementation
                   10087: @cindex implementation of structures
1.52      anton    10088: 
1.78      anton    10089: The central idea in the implementation is to pass the data about the
                   10090: structure being built on the stack, not in some global
                   10091: variable. Everything else falls into place naturally once this design
                   10092: decision is made.
1.53      anton    10093: 
1.78      anton    10094: The type description on the stack is of the form @emph{align
                   10095: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   10096: very simple.
1.53      anton    10097: 
1.78      anton    10098: @code{field} is a defining word that uses @code{Create}
                   10099: and @code{DOES>}. The body of the field contains the offset
                   10100: of the field, and the normal @code{DOES>} action is simply:
1.53      anton    10101: 
                   10102: @example
1.78      anton    10103: @@ +
1.53      anton    10104: @end example
                   10105: 
1.78      anton    10106: @noindent
                   10107: i.e., add the offset to the address, giving the stack effect
                   10108: @i{addr1 -- addr2} for a field.
                   10109: 
                   10110: @cindex first field optimization, implementation
                   10111: This simple structure is slightly complicated by the optimization
                   10112: for fields with offset 0, which requires a different
                   10113: @code{DOES>}-part (because we cannot rely on there being
                   10114: something on the stack if such a field is invoked during
                   10115: compilation). Therefore, we put the different @code{DOES>}-parts
                   10116: in separate words, and decide which one to invoke based on the
                   10117: offset. For a zero offset, the field is basically a noop; it is
                   10118: immediate, and therefore no code is generated when it is compiled.
1.53      anton    10119: 
1.78      anton    10120: @node Structure Glossary,  , Structure Implementation, Structures
                   10121: @subsection Structure Glossary
                   10122: @cindex structure glossary
1.53      anton    10123: 
1.5       anton    10124: 
1.78      anton    10125: doc-%align
                   10126: doc-%alignment
                   10127: doc-%alloc
                   10128: doc-%allocate
                   10129: doc-%allot
                   10130: doc-cell%
                   10131: doc-char%
                   10132: doc-dfloat%
                   10133: doc-double%
                   10134: doc-end-struct
                   10135: doc-field
                   10136: doc-float%
                   10137: doc-naligned
                   10138: doc-sfloat%
                   10139: doc-%size
                   10140: doc-struct
1.54      anton    10141: 
                   10142: 
1.26      crook    10143: @c -------------------------------------------------------------
1.78      anton    10144: @node Object-oriented Forth, Programming Tools, Structures, Words
                   10145: @section Object-oriented Forth
                   10146: 
                   10147: Gforth comes with three packages for object-oriented programming:
                   10148: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   10149: is preloaded, so you have to @code{include} them before use. The most
                   10150: important differences between these packages (and others) are discussed
                   10151: in @ref{Comparison with other object models}. All packages are written
                   10152: in ANS Forth and can be used with any other ANS Forth.
1.5       anton    10153: 
1.78      anton    10154: @menu
                   10155: * Why object-oriented programming?::  
                   10156: * Object-Oriented Terminology::  
                   10157: * Objects::                     
                   10158: * OOF::                         
                   10159: * Mini-OOF::                    
                   10160: * Comparison with other object models::  
                   10161: @end menu
1.5       anton    10162: 
1.78      anton    10163: @c ----------------------------------------------------------------
                   10164: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
                   10165: @subsection Why object-oriented programming?
                   10166: @cindex object-oriented programming motivation
                   10167: @cindex motivation for object-oriented programming
1.44      crook    10168: 
1.78      anton    10169: Often we have to deal with several data structures (@emph{objects}),
                   10170: that have to be treated similarly in some respects, but differently in
                   10171: others. Graphical objects are the textbook example: circles, triangles,
                   10172: dinosaurs, icons, and others, and we may want to add more during program
                   10173: development. We want to apply some operations to any graphical object,
                   10174: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   10175: has to do something different for every kind of object.
                   10176: @comment TODO add some other operations eg perimeter, area
                   10177: @comment and tie in to concrete examples later..
1.5       anton    10178: 
1.78      anton    10179: We could implement @code{draw} as a big @code{CASE}
                   10180: control structure that executes the appropriate code depending on the
                   10181: kind of object to be drawn. This would be not be very elegant, and,
                   10182: moreover, we would have to change @code{draw} every time we add
                   10183: a new kind of graphical object (say, a spaceship).
1.44      crook    10184: 
1.78      anton    10185: What we would rather do is: When defining spaceships, we would tell
                   10186: the system: ``Here's how you @code{draw} a spaceship; you figure
                   10187: out the rest''.
1.5       anton    10188: 
1.78      anton    10189: This is the problem that all systems solve that (rightfully) call
                   10190: themselves object-oriented; the object-oriented packages presented here
                   10191: solve this problem (and not much else).
                   10192: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44      crook    10193: 
1.78      anton    10194: @c ------------------------------------------------------------------------
                   10195: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
                   10196: @subsection Object-Oriented Terminology
                   10197: @cindex object-oriented terminology
                   10198: @cindex terminology for object-oriented programming
1.5       anton    10199: 
1.78      anton    10200: This section is mainly for reference, so you don't have to understand
                   10201: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   10202: short:
1.44      crook    10203: 
1.78      anton    10204: @table @emph
                   10205: @cindex class
                   10206: @item class
                   10207: a data structure definition with some extras.
1.5       anton    10208: 
1.78      anton    10209: @cindex object
                   10210: @item object
                   10211: an instance of the data structure described by the class definition.
1.5       anton    10212: 
1.78      anton    10213: @cindex instance variables
                   10214: @item instance variables
                   10215: fields of the data structure.
1.5       anton    10216: 
1.78      anton    10217: @cindex selector
                   10218: @cindex method selector
                   10219: @cindex virtual function
                   10220: @item selector
                   10221: (or @emph{method selector}) a word (e.g.,
                   10222: @code{draw}) that performs an operation on a variety of data
                   10223: structures (classes). A selector describes @emph{what} operation to
                   10224: perform. In C++ terminology: a (pure) virtual function.
1.5       anton    10225: 
1.78      anton    10226: @cindex method
                   10227: @item method
                   10228: the concrete definition that performs the operation
                   10229: described by the selector for a specific class. A method specifies
                   10230: @emph{how} the operation is performed for a specific class.
1.5       anton    10231: 
1.78      anton    10232: @cindex selector invocation
                   10233: @cindex message send
                   10234: @cindex invoking a selector
                   10235: @item selector invocation
                   10236: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   10237: is used for determining which method is used. In Smalltalk terminology:
                   10238: a message (consisting of the selector and the other arguments) is sent
                   10239: to the object.
1.5       anton    10240: 
1.78      anton    10241: @cindex receiving object
                   10242: @item receiving object
                   10243: the object used for determining the method executed by a selector
                   10244: invocation. In the @file{objects.fs} model, it is the object that is on
                   10245: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   10246: the Smalltalk @emph{message} terminology.)
1.5       anton    10247: 
1.78      anton    10248: @cindex child class
                   10249: @cindex parent class
                   10250: @cindex inheritance
                   10251: @item child class
                   10252: a class that has (@emph{inherits}) all properties (instance variables,
                   10253: selectors, methods) from a @emph{parent class}. In Smalltalk
                   10254: terminology: The subclass inherits from the superclass. In C++
                   10255: terminology: The derived class inherits from the base class.
1.5       anton    10256: 
1.78      anton    10257: @end table
1.5       anton    10258: 
1.78      anton    10259: @c If you wonder about the message sending terminology, it comes from
                   10260: @c a time when each object had it's own task and objects communicated via
                   10261: @c message passing; eventually the Smalltalk developers realized that
                   10262: @c they can do most things through simple (indirect) calls. They kept the
                   10263: @c terminology.
1.5       anton    10264: 
1.78      anton    10265: @c --------------------------------------------------------------
                   10266: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   10267: @subsection The @file{objects.fs} model
                   10268: @cindex objects
                   10269: @cindex object-oriented programming
1.26      crook    10270: 
1.78      anton    10271: @cindex @file{objects.fs}
                   10272: @cindex @file{oof.fs}
1.26      crook    10273: 
1.78      anton    10274: This section describes the @file{objects.fs} package. This material also
                   10275: has been published in M. Anton Ertl,
                   10276: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
                   10277: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
                   10278: 37--43.
                   10279: @c McKewan's and Zsoter's packages
1.26      crook    10280: 
1.78      anton    10281: This section assumes that you have read @ref{Structures}.
1.5       anton    10282: 
1.78      anton    10283: The techniques on which this model is based have been used to implement
                   10284: the parser generator, Gray, and have also been used in Gforth for
                   10285: implementing the various flavours of word lists (hashed or not,
                   10286: case-sensitive or not, special-purpose word lists for locals etc.).
1.5       anton    10287: 
                   10288: 
1.26      crook    10289: @menu
1.78      anton    10290: * Properties of the Objects model::  
                   10291: * Basic Objects Usage::         
                   10292: * The Objects base class::      
                   10293: * Creating objects::            
                   10294: * Object-Oriented Programming Style::  
                   10295: * Class Binding::               
                   10296: * Method conveniences::         
                   10297: * Classes and Scoping::         
                   10298: * Dividing classes::            
                   10299: * Object Interfaces::           
                   10300: * Objects Implementation::      
                   10301: * Objects Glossary::            
1.26      crook    10302: @end menu
1.5       anton    10303: 
1.78      anton    10304: Marcel Hendrix provided helpful comments on this section.
1.5       anton    10305: 
1.78      anton    10306: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   10307: @subsubsection Properties of the @file{objects.fs} model
                   10308: @cindex @file{objects.fs} properties
1.5       anton    10309: 
1.78      anton    10310: @itemize @bullet
                   10311: @item
                   10312: It is straightforward to pass objects on the stack. Passing
                   10313: selectors on the stack is a little less convenient, but possible.
1.44      crook    10314: 
1.78      anton    10315: @item
                   10316: Objects are just data structures in memory, and are referenced by their
                   10317: address. You can create words for objects with normal defining words
                   10318: like @code{constant}. Likewise, there is no difference between instance
                   10319: variables that contain objects and those that contain other data.
1.5       anton    10320: 
1.78      anton    10321: @item
                   10322: Late binding is efficient and easy to use.
1.44      crook    10323: 
1.78      anton    10324: @item
                   10325: It avoids parsing, and thus avoids problems with state-smartness
                   10326: and reduced extensibility; for convenience there are a few parsing
                   10327: words, but they have non-parsing counterparts. There are also a few
                   10328: defining words that parse. This is hard to avoid, because all standard
                   10329: defining words parse (except @code{:noname}); however, such
                   10330: words are not as bad as many other parsing words, because they are not
                   10331: state-smart.
1.5       anton    10332: 
1.78      anton    10333: @item
                   10334: It does not try to incorporate everything. It does a few things and does
                   10335: them well (IMO). In particular, this model was not designed to support
                   10336: information hiding (although it has features that may help); you can use
                   10337: a separate package for achieving this.
1.5       anton    10338: 
1.78      anton    10339: @item
                   10340: It is layered; you don't have to learn and use all features to use this
                   10341: model. Only a few features are necessary (@pxref{Basic Objects Usage},
                   10342: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
                   10343: are optional and independent of each other.
1.5       anton    10344: 
1.78      anton    10345: @item
                   10346: An implementation in ANS Forth is available.
1.5       anton    10347: 
1.78      anton    10348: @end itemize
1.5       anton    10349: 
1.44      crook    10350: 
1.78      anton    10351: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   10352: @subsubsection Basic @file{objects.fs} Usage
                   10353: @cindex basic objects usage
                   10354: @cindex objects, basic usage
1.5       anton    10355: 
1.78      anton    10356: You can define a class for graphical objects like this:
1.44      crook    10357: 
1.78      anton    10358: @cindex @code{class} usage
                   10359: @cindex @code{end-class} usage
                   10360: @cindex @code{selector} usage
1.5       anton    10361: @example
1.78      anton    10362: object class \ "object" is the parent class
                   10363:   selector draw ( x y graphical -- )
                   10364: end-class graphical
                   10365: @end example
                   10366: 
                   10367: This code defines a class @code{graphical} with an
                   10368: operation @code{draw}.  We can perform the operation
                   10369: @code{draw} on any @code{graphical} object, e.g.:
                   10370: 
                   10371: @example
                   10372: 100 100 t-rex draw
1.26      crook    10373: @end example
1.5       anton    10374: 
1.78      anton    10375: @noindent
                   10376: where @code{t-rex} is a word (say, a constant) that produces a
                   10377: graphical object.
                   10378: 
                   10379: @comment TODO add a 2nd operation eg perimeter.. and use for
                   10380: @comment a concrete example
1.5       anton    10381: 
1.78      anton    10382: @cindex abstract class
                   10383: How do we create a graphical object? With the present definitions,
                   10384: we cannot create a useful graphical object. The class
                   10385: @code{graphical} describes graphical objects in general, but not
                   10386: any concrete graphical object type (C++ users would call it an
                   10387: @emph{abstract class}); e.g., there is no method for the selector
                   10388: @code{draw} in the class @code{graphical}.
1.5       anton    10389: 
1.78      anton    10390: For concrete graphical objects, we define child classes of the
                   10391: class @code{graphical}, e.g.:
1.5       anton    10392: 
1.78      anton    10393: @cindex @code{overrides} usage
                   10394: @cindex @code{field} usage in class definition
1.26      crook    10395: @example
1.78      anton    10396: graphical class \ "graphical" is the parent class
                   10397:   cell% field circle-radius
1.5       anton    10398: 
1.78      anton    10399: :noname ( x y circle -- )
                   10400:   circle-radius @@ draw-circle ;
                   10401: overrides draw
1.5       anton    10402: 
1.78      anton    10403: :noname ( n-radius circle -- )
                   10404:   circle-radius ! ;
                   10405: overrides construct
1.5       anton    10406: 
1.78      anton    10407: end-class circle
                   10408: @end example
1.44      crook    10409: 
1.78      anton    10410: Here we define a class @code{circle} as a child of @code{graphical},
                   10411: with field @code{circle-radius} (which behaves just like a field
                   10412: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   10413: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   10414: defined in @code{object}, the parent class of @code{graphical}).
1.5       anton    10415: 
1.78      anton    10416: Now we can create a circle on the heap (i.e.,
                   10417: @code{allocate}d memory) with:
1.44      crook    10418: 
1.78      anton    10419: @cindex @code{heap-new} usage
1.5       anton    10420: @example
1.78      anton    10421: 50 circle heap-new constant my-circle
1.5       anton    10422: @end example
                   10423: 
1.78      anton    10424: @noindent
                   10425: @code{heap-new} invokes @code{construct}, thus
                   10426: initializing the field @code{circle-radius} with 50. We can draw
                   10427: this new circle at (100,100) with:
1.5       anton    10428: 
                   10429: @example
1.78      anton    10430: 100 100 my-circle draw
1.5       anton    10431: @end example
                   10432: 
1.78      anton    10433: @cindex selector invocation, restrictions
                   10434: @cindex class definition, restrictions
                   10435: Note: You can only invoke a selector if the object on the TOS
                   10436: (the receiving object) belongs to the class where the selector was
                   10437: defined or one of its descendents; e.g., you can invoke
                   10438: @code{draw} only for objects belonging to @code{graphical}
                   10439: or its descendents (e.g., @code{circle}).  Immediately before
                   10440: @code{end-class}, the search order has to be the same as
                   10441: immediately after @code{class}.
                   10442: 
                   10443: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   10444: @subsubsection The @file{object.fs} base class
                   10445: @cindex @code{object} class
                   10446: 
                   10447: When you define a class, you have to specify a parent class.  So how do
                   10448: you start defining classes? There is one class available from the start:
                   10449: @code{object}. It is ancestor for all classes and so is the
                   10450: only class that has no parent. It has two selectors: @code{construct}
                   10451: and @code{print}.
                   10452: 
                   10453: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   10454: @subsubsection Creating objects
                   10455: @cindex creating objects
                   10456: @cindex object creation
                   10457: @cindex object allocation options
                   10458: 
                   10459: @cindex @code{heap-new} discussion
                   10460: @cindex @code{dict-new} discussion
                   10461: @cindex @code{construct} discussion
                   10462: You can create and initialize an object of a class on the heap with
                   10463: @code{heap-new} ( ... class -- object ) and in the dictionary
                   10464: (allocation with @code{allot}) with @code{dict-new} (
                   10465: ... class -- object ). Both words invoke @code{construct}, which
                   10466: consumes the stack items indicated by "..." above.
                   10467: 
                   10468: @cindex @code{init-object} discussion
                   10469: @cindex @code{class-inst-size} discussion
                   10470: If you want to allocate memory for an object yourself, you can get its
                   10471: alignment and size with @code{class-inst-size 2@@} ( class --
                   10472: align size ). Once you have memory for an object, you can initialize
                   10473: it with @code{init-object} ( ... class object -- );
                   10474: @code{construct} does only a part of the necessary work.
                   10475: 
                   10476: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   10477: @subsubsection Object-Oriented Programming Style
                   10478: @cindex object-oriented programming style
                   10479: @cindex programming style, object-oriented
1.5       anton    10480: 
1.78      anton    10481: This section is not exhaustive.
1.5       anton    10482: 
1.78      anton    10483: @cindex stack effects of selectors
                   10484: @cindex selectors and stack effects
                   10485: In general, it is a good idea to ensure that all methods for the
                   10486: same selector have the same stack effect: when you invoke a selector,
                   10487: you often have no idea which method will be invoked, so, unless all
                   10488: methods have the same stack effect, you will not know the stack effect
                   10489: of the selector invocation.
1.5       anton    10490: 
1.78      anton    10491: One exception to this rule is methods for the selector
                   10492: @code{construct}. We know which method is invoked, because we
                   10493: specify the class to be constructed at the same place. Actually, I
                   10494: defined @code{construct} as a selector only to give the users a
                   10495: convenient way to specify initialization. The way it is used, a
                   10496: mechanism different from selector invocation would be more natural
                   10497: (but probably would take more code and more space to explain).
1.5       anton    10498: 
1.78      anton    10499: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   10500: @subsubsection Class Binding
                   10501: @cindex class binding
                   10502: @cindex early binding
1.5       anton    10503: 
1.78      anton    10504: @cindex late binding
                   10505: Normal selector invocations determine the method at run-time depending
                   10506: on the class of the receiving object. This run-time selection is called
                   10507: @i{late binding}.
1.5       anton    10508: 
1.78      anton    10509: Sometimes it's preferable to invoke a different method. For example,
                   10510: you might want to use the simple method for @code{print}ing
                   10511: @code{object}s instead of the possibly long-winded @code{print} method
                   10512: of the receiver class. You can achieve this by replacing the invocation
                   10513: of @code{print} with:
1.5       anton    10514: 
1.78      anton    10515: @cindex @code{[bind]} usage
1.5       anton    10516: @example
1.78      anton    10517: [bind] object print
1.5       anton    10518: @end example
                   10519: 
1.78      anton    10520: @noindent
                   10521: in compiled code or:
                   10522: 
                   10523: @cindex @code{bind} usage
1.5       anton    10524: @example
1.78      anton    10525: bind object print
1.5       anton    10526: @end example
                   10527: 
1.78      anton    10528: @cindex class binding, alternative to
                   10529: @noindent
                   10530: in interpreted code. Alternatively, you can define the method with a
                   10531: name (e.g., @code{print-object}), and then invoke it through the
                   10532: name. Class binding is just a (often more convenient) way to achieve
                   10533: the same effect; it avoids name clutter and allows you to invoke
                   10534: methods directly without naming them first.
1.5       anton    10535: 
1.78      anton    10536: @cindex superclass binding
                   10537: @cindex parent class binding
                   10538: A frequent use of class binding is this: When we define a method
                   10539: for a selector, we often want the method to do what the selector does
                   10540: in the parent class, and a little more. There is a special word for
                   10541: this purpose: @code{[parent]}; @code{[parent]
                   10542: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   10543: selector}}, where @code{@emph{parent}} is the parent
                   10544: class of the current class. E.g., a method definition might look like:
1.44      crook    10545: 
1.78      anton    10546: @cindex @code{[parent]} usage
                   10547: @example
                   10548: :noname
                   10549:   dup [parent] foo \ do parent's foo on the receiving object
                   10550:   ... \ do some more
                   10551: ; overrides foo
                   10552: @end example
1.6       pazsan   10553: 
1.78      anton    10554: @cindex class binding as optimization
                   10555: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   10556: March 1997), Andrew McKewan presents class binding as an optimization
                   10557: technique. I recommend not using it for this purpose unless you are in
                   10558: an emergency. Late binding is pretty fast with this model anyway, so the
                   10559: benefit of using class binding is small; the cost of using class binding
                   10560: where it is not appropriate is reduced maintainability.
1.44      crook    10561: 
1.78      anton    10562: While we are at programming style questions: You should bind
                   10563: selectors only to ancestor classes of the receiving object. E.g., say,
                   10564: you know that the receiving object is of class @code{foo} or its
                   10565: descendents; then you should bind only to @code{foo} and its
                   10566: ancestors.
1.12      anton    10567: 
1.78      anton    10568: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   10569: @subsubsection Method conveniences
                   10570: @cindex method conveniences
1.44      crook    10571: 
1.78      anton    10572: In a method you usually access the receiving object pretty often.  If
                   10573: you define the method as a plain colon definition (e.g., with
                   10574: @code{:noname}), you may have to do a lot of stack
                   10575: gymnastics. To avoid this, you can define the method with @code{m:
                   10576: ... ;m}. E.g., you could define the method for
                   10577: @code{draw}ing a @code{circle} with
1.6       pazsan   10578: 
1.78      anton    10579: @cindex @code{this} usage
                   10580: @cindex @code{m:} usage
                   10581: @cindex @code{;m} usage
                   10582: @example
                   10583: m: ( x y circle -- )
                   10584:   ( x y ) this circle-radius @@ draw-circle ;m
                   10585: @end example
1.6       pazsan   10586: 
1.78      anton    10587: @cindex @code{exit} in @code{m: ... ;m}
                   10588: @cindex @code{exitm} discussion
                   10589: @cindex @code{catch} in @code{m: ... ;m}
                   10590: When this method is executed, the receiver object is removed from the
                   10591: stack; you can access it with @code{this} (admittedly, in this
                   10592: example the use of @code{m: ... ;m} offers no advantage). Note
                   10593: that I specify the stack effect for the whole method (i.e. including
                   10594: the receiver object), not just for the code between @code{m:}
                   10595: and @code{;m}. You cannot use @code{exit} in
                   10596: @code{m:...;m}; instead, use
                   10597: @code{exitm}.@footnote{Moreover, for any word that calls
                   10598: @code{catch} and was defined before loading
                   10599: @code{objects.fs}, you have to redefine it like I redefined
                   10600: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12      anton    10601: 
1.78      anton    10602: @cindex @code{inst-var} usage
                   10603: You will frequently use sequences of the form @code{this
                   10604: @emph{field}} (in the example above: @code{this
                   10605: circle-radius}). If you use the field only in this way, you can
                   10606: define it with @code{inst-var} and eliminate the
                   10607: @code{this} before the field name. E.g., the @code{circle}
                   10608: class above could also be defined with:
1.6       pazsan   10609: 
1.78      anton    10610: @example
                   10611: graphical class
                   10612:   cell% inst-var radius
1.6       pazsan   10613: 
1.78      anton    10614: m: ( x y circle -- )
                   10615:   radius @@ draw-circle ;m
                   10616: overrides draw
1.6       pazsan   10617: 
1.78      anton    10618: m: ( n-radius circle -- )
                   10619:   radius ! ;m
                   10620: overrides construct
1.6       pazsan   10621: 
1.78      anton    10622: end-class circle
                   10623: @end example
1.6       pazsan   10624: 
1.78      anton    10625: @code{radius} can only be used in @code{circle} and its
                   10626: descendent classes and inside @code{m:...;m}.
1.6       pazsan   10627: 
1.78      anton    10628: @cindex @code{inst-value} usage
                   10629: You can also define fields with @code{inst-value}, which is
                   10630: to @code{inst-var} what @code{value} is to
                   10631: @code{variable}.  You can change the value of such a field with
                   10632: @code{[to-inst]}.  E.g., we could also define the class
                   10633: @code{circle} like this:
1.44      crook    10634: 
1.78      anton    10635: @example
                   10636: graphical class
                   10637:   inst-value radius
1.6       pazsan   10638: 
1.78      anton    10639: m: ( x y circle -- )
                   10640:   radius draw-circle ;m
                   10641: overrides draw
1.44      crook    10642: 
1.78      anton    10643: m: ( n-radius circle -- )
                   10644:   [to-inst] radius ;m
                   10645: overrides construct
1.6       pazsan   10646: 
1.78      anton    10647: end-class circle
                   10648: @end example
1.6       pazsan   10649: 
1.78      anton    10650: @c !! :m is easy to confuse with m:.  Another name would be better.
1.6       pazsan   10651: 
1.78      anton    10652: @c Finally, you can define named methods with @code{:m}.  One use of this
                   10653: @c feature is the definition of words that occur only in one class and are
                   10654: @c not intended to be overridden, but which still need method context
                   10655: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
                   10656: @c would be bound frequently, if defined anonymously.
1.6       pazsan   10657: 
                   10658: 
1.78      anton    10659: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
                   10660: @subsubsection Classes and Scoping
                   10661: @cindex classes and scoping
                   10662: @cindex scoping and classes
1.6       pazsan   10663: 
1.78      anton    10664: Inheritance is frequent, unlike structure extension. This exacerbates
                   10665: the problem with the field name convention (@pxref{Structure Naming
                   10666: Convention}): One always has to remember in which class the field was
                   10667: originally defined; changing a part of the class structure would require
                   10668: changes for renaming in otherwise unaffected code.
1.6       pazsan   10669: 
1.78      anton    10670: @cindex @code{inst-var} visibility
                   10671: @cindex @code{inst-value} visibility
                   10672: To solve this problem, I added a scoping mechanism (which was not in my
                   10673: original charter): A field defined with @code{inst-var} (or
                   10674: @code{inst-value}) is visible only in the class where it is defined and in
                   10675: the descendent classes of this class.  Using such fields only makes
                   10676: sense in @code{m:}-defined methods in these classes anyway.
1.6       pazsan   10677: 
1.78      anton    10678: This scoping mechanism allows us to use the unadorned field name,
                   10679: because name clashes with unrelated words become much less likely.
1.6       pazsan   10680: 
1.78      anton    10681: @cindex @code{protected} discussion
                   10682: @cindex @code{private} discussion
                   10683: Once we have this mechanism, we can also use it for controlling the
                   10684: visibility of other words: All words defined after
                   10685: @code{protected} are visible only in the current class and its
                   10686: descendents. @code{public} restores the compilation
                   10687: (i.e. @code{current}) word list that was in effect before. If you
                   10688: have several @code{protected}s without an intervening
                   10689: @code{public} or @code{set-current}, @code{public}
                   10690: will restore the compilation word list in effect before the first of
                   10691: these @code{protected}s.
1.6       pazsan   10692: 
1.78      anton    10693: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
                   10694: @subsubsection Dividing classes
                   10695: @cindex Dividing classes
                   10696: @cindex @code{methods}...@code{end-methods}
1.6       pazsan   10697: 
1.78      anton    10698: You may want to do the definition of methods separate from the
                   10699: definition of the class, its selectors, fields, and instance variables,
                   10700: i.e., separate the implementation from the definition.  You can do this
                   10701: in the following way:
1.6       pazsan   10702: 
1.78      anton    10703: @example
                   10704: graphical class
                   10705:   inst-value radius
                   10706: end-class circle
1.6       pazsan   10707: 
1.78      anton    10708: ... \ do some other stuff
1.6       pazsan   10709: 
1.78      anton    10710: circle methods \ now we are ready
1.44      crook    10711: 
1.78      anton    10712: m: ( x y circle -- )
                   10713:   radius draw-circle ;m
                   10714: overrides draw
1.6       pazsan   10715: 
1.78      anton    10716: m: ( n-radius circle -- )
                   10717:   [to-inst] radius ;m
                   10718: overrides construct
1.44      crook    10719: 
1.78      anton    10720: end-methods
                   10721: @end example
1.7       pazsan   10722: 
1.78      anton    10723: You can use several @code{methods}...@code{end-methods} sections.  The
                   10724: only things you can do to the class in these sections are: defining
                   10725: methods, and overriding the class's selectors.  You must not define new
                   10726: selectors or fields.
1.7       pazsan   10727: 
1.78      anton    10728: Note that you often have to override a selector before using it.  In
                   10729: particular, you usually have to override @code{construct} with a new
                   10730: method before you can invoke @code{heap-new} and friends.  E.g., you
                   10731: must not create a circle before the @code{overrides construct} sequence
                   10732: in the example above.
1.7       pazsan   10733: 
1.78      anton    10734: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
                   10735: @subsubsection Object Interfaces
                   10736: @cindex object interfaces
                   10737: @cindex interfaces for objects
1.7       pazsan   10738: 
1.78      anton    10739: In this model you can only call selectors defined in the class of the
                   10740: receiving objects or in one of its ancestors. If you call a selector
                   10741: with a receiving object that is not in one of these classes, the
                   10742: result is undefined; if you are lucky, the program crashes
                   10743: immediately.
1.7       pazsan   10744: 
1.78      anton    10745: @cindex selectors common to hardly-related classes
                   10746: Now consider the case when you want to have a selector (or several)
                   10747: available in two classes: You would have to add the selector to a
                   10748: common ancestor class, in the worst case to @code{object}. You
                   10749: may not want to do this, e.g., because someone else is responsible for
                   10750: this ancestor class.
1.7       pazsan   10751: 
1.78      anton    10752: The solution for this problem is interfaces. An interface is a
                   10753: collection of selectors. If a class implements an interface, the
                   10754: selectors become available to the class and its descendents. A class
                   10755: can implement an unlimited number of interfaces. For the problem
                   10756: discussed above, we would define an interface for the selector(s), and
                   10757: both classes would implement the interface.
1.7       pazsan   10758: 
1.78      anton    10759: As an example, consider an interface @code{storage} for
                   10760: writing objects to disk and getting them back, and a class
                   10761: @code{foo} that implements it. The code would look like this:
1.7       pazsan   10762: 
1.78      anton    10763: @cindex @code{interface} usage
                   10764: @cindex @code{end-interface} usage
                   10765: @cindex @code{implementation} usage
                   10766: @example
                   10767: interface
                   10768:   selector write ( file object -- )
                   10769:   selector read1 ( file object -- )
                   10770: end-interface storage
1.13      pazsan   10771: 
1.78      anton    10772: bar class
                   10773:   storage implementation
1.13      pazsan   10774: 
1.78      anton    10775: ... overrides write
                   10776: ... overrides read1
                   10777: ...
                   10778: end-class foo
                   10779: @end example
1.13      pazsan   10780: 
1.78      anton    10781: @noindent
                   10782: (I would add a word @code{read} @i{( file -- object )} that uses
                   10783: @code{read1} internally, but that's beyond the point illustrated
                   10784: here.)
1.13      pazsan   10785: 
1.78      anton    10786: Note that you cannot use @code{protected} in an interface; and
                   10787: of course you cannot define fields.
1.13      pazsan   10788: 
1.78      anton    10789: In the Neon model, all selectors are available for all classes;
                   10790: therefore it does not need interfaces. The price you pay in this model
                   10791: is slower late binding, and therefore, added complexity to avoid late
                   10792: binding.
1.13      pazsan   10793: 
1.78      anton    10794: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   10795: @subsubsection @file{objects.fs} Implementation
                   10796: @cindex @file{objects.fs} implementation
1.13      pazsan   10797: 
1.78      anton    10798: @cindex @code{object-map} discussion
                   10799: An object is a piece of memory, like one of the data structures
                   10800: described with @code{struct...end-struct}. It has a field
                   10801: @code{object-map} that points to the method map for the object's
                   10802: class.
1.13      pazsan   10803: 
1.78      anton    10804: @cindex method map
                   10805: @cindex virtual function table
                   10806: The @emph{method map}@footnote{This is Self terminology; in C++
                   10807: terminology: virtual function table.} is an array that contains the
                   10808: execution tokens (@i{xt}s) of the methods for the object's class. Each
                   10809: selector contains an offset into a method map.
1.13      pazsan   10810: 
1.78      anton    10811: @cindex @code{selector} implementation, class
                   10812: @code{selector} is a defining word that uses
                   10813: @code{CREATE} and @code{DOES>}. The body of the
                   10814: selector contains the offset; the @code{DOES>} action for a
                   10815: class selector is, basically:
1.8       pazsan   10816: 
                   10817: @example
1.78      anton    10818: ( object addr ) @@ over object-map @@ + @@ execute
1.13      pazsan   10819: @end example
                   10820: 
1.78      anton    10821: Since @code{object-map} is the first field of the object, it
                   10822: does not generate any code. As you can see, calling a selector has a
                   10823: small, constant cost.
1.26      crook    10824: 
1.78      anton    10825: @cindex @code{current-interface} discussion
                   10826: @cindex class implementation and representation
                   10827: A class is basically a @code{struct} combined with a method
                   10828: map. During the class definition the alignment and size of the class
                   10829: are passed on the stack, just as with @code{struct}s, so
                   10830: @code{field} can also be used for defining class
                   10831: fields. However, passing more items on the stack would be
                   10832: inconvenient, so @code{class} builds a data structure in memory,
                   10833: which is accessed through the variable
                   10834: @code{current-interface}. After its definition is complete, the
                   10835: class is represented on the stack by a pointer (e.g., as parameter for
                   10836: a child class definition).
1.26      crook    10837: 
1.78      anton    10838: A new class starts off with the alignment and size of its parent,
                   10839: and a copy of the parent's method map. Defining new fields extends the
                   10840: size and alignment; likewise, defining new selectors extends the
                   10841: method map. @code{overrides} just stores a new @i{xt} in the method
                   10842: map at the offset given by the selector.
1.13      pazsan   10843: 
1.78      anton    10844: @cindex class binding, implementation
                   10845: Class binding just gets the @i{xt} at the offset given by the selector
                   10846: from the class's method map and @code{compile,}s (in the case of
                   10847: @code{[bind]}) it.
1.13      pazsan   10848: 
1.78      anton    10849: @cindex @code{this} implementation
                   10850: @cindex @code{catch} and @code{this}
                   10851: @cindex @code{this} and @code{catch}
                   10852: I implemented @code{this} as a @code{value}. At the
                   10853: start of an @code{m:...;m} method the old @code{this} is
                   10854: stored to the return stack and restored at the end; and the object on
                   10855: the TOS is stored @code{TO this}. This technique has one
                   10856: disadvantage: If the user does not leave the method via
                   10857: @code{;m}, but via @code{throw} or @code{exit},
                   10858: @code{this} is not restored (and @code{exit} may
                   10859: crash). To deal with the @code{throw} problem, I have redefined
                   10860: @code{catch} to save and restore @code{this}; the same
                   10861: should be done with any word that can catch an exception. As for
                   10862: @code{exit}, I simply forbid it (as a replacement, there is
                   10863: @code{exitm}).
1.13      pazsan   10864: 
1.78      anton    10865: @cindex @code{inst-var} implementation
                   10866: @code{inst-var} is just the same as @code{field}, with
                   10867: a different @code{DOES>} action:
1.13      pazsan   10868: @example
1.78      anton    10869: @@ this +
1.8       pazsan   10870: @end example
1.78      anton    10871: Similar for @code{inst-value}.
1.8       pazsan   10872: 
1.78      anton    10873: @cindex class scoping implementation
                   10874: Each class also has a word list that contains the words defined with
                   10875: @code{inst-var} and @code{inst-value}, and its protected
                   10876: words. It also has a pointer to its parent. @code{class} pushes
                   10877: the word lists of the class and all its ancestors onto the search order stack,
                   10878: and @code{end-class} drops them.
1.20      pazsan   10879: 
1.78      anton    10880: @cindex interface implementation
                   10881: An interface is like a class without fields, parent and protected
                   10882: words; i.e., it just has a method map. If a class implements an
                   10883: interface, its method map contains a pointer to the method map of the
                   10884: interface. The positive offsets in the map are reserved for class
                   10885: methods, therefore interface map pointers have negative
                   10886: offsets. Interfaces have offsets that are unique throughout the
                   10887: system, unlike class selectors, whose offsets are only unique for the
                   10888: classes where the selector is available (invokable).
1.20      pazsan   10889: 
1.78      anton    10890: This structure means that interface selectors have to perform one
                   10891: indirection more than class selectors to find their method. Their body
                   10892: contains the interface map pointer offset in the class method map, and
                   10893: the method offset in the interface method map. The
                   10894: @code{does>} action for an interface selector is, basically:
1.20      pazsan   10895: 
                   10896: @example
1.78      anton    10897: ( object selector-body )
                   10898: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   10899: swap object-map @@ + @@ ( object selector-body map )
                   10900: swap selector-offset @@ + @@ execute
1.20      pazsan   10901: @end example
                   10902: 
1.78      anton    10903: where @code{object-map} and @code{selector-offset} are
                   10904: first fields and generate no code.
1.20      pazsan   10905: 
1.78      anton    10906: As a concrete example, consider the following code:
1.20      pazsan   10907: 
                   10908: @example
1.78      anton    10909: interface
                   10910:   selector if1sel1
                   10911:   selector if1sel2
                   10912: end-interface if1
1.20      pazsan   10913: 
1.78      anton    10914: object class
                   10915:   if1 implementation
                   10916:   selector cl1sel1
                   10917:   cell% inst-var cl1iv1
1.20      pazsan   10918: 
1.78      anton    10919: ' m1 overrides construct
                   10920: ' m2 overrides if1sel1
                   10921: ' m3 overrides if1sel2
                   10922: ' m4 overrides cl1sel2
                   10923: end-class cl1
1.20      pazsan   10924: 
1.78      anton    10925: create obj1 object dict-new drop
                   10926: create obj2 cl1    dict-new drop
                   10927: @end example
1.20      pazsan   10928: 
1.78      anton    10929: The data structure created by this code (including the data structure
                   10930: for @code{object}) is shown in the
                   10931: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
                   10932: @comment TODO add this diagram..
1.20      pazsan   10933: 
1.78      anton    10934: @node Objects Glossary,  , Objects Implementation, Objects
                   10935: @subsubsection @file{objects.fs} Glossary
                   10936: @cindex @file{objects.fs} Glossary
1.20      pazsan   10937: 
                   10938: 
1.78      anton    10939: doc---objects-bind
                   10940: doc---objects-<bind>
                   10941: doc---objects-bind'
                   10942: doc---objects-[bind]
                   10943: doc---objects-class
                   10944: doc---objects-class->map
                   10945: doc---objects-class-inst-size
                   10946: doc---objects-class-override!
1.79      anton    10947: doc---objects-class-previous
                   10948: doc---objects-class>order
1.78      anton    10949: doc---objects-construct
                   10950: doc---objects-current'
                   10951: doc---objects-[current]
                   10952: doc---objects-current-interface
                   10953: doc---objects-dict-new
                   10954: doc---objects-end-class
                   10955: doc---objects-end-class-noname
                   10956: doc---objects-end-interface
                   10957: doc---objects-end-interface-noname
                   10958: doc---objects-end-methods
                   10959: doc---objects-exitm
                   10960: doc---objects-heap-new
                   10961: doc---objects-implementation
                   10962: doc---objects-init-object
                   10963: doc---objects-inst-value
                   10964: doc---objects-inst-var
                   10965: doc---objects-interface
                   10966: doc---objects-m:
                   10967: doc---objects-:m
                   10968: doc---objects-;m
                   10969: doc---objects-method
                   10970: doc---objects-methods
                   10971: doc---objects-object
                   10972: doc---objects-overrides
                   10973: doc---objects-[parent]
                   10974: doc---objects-print
                   10975: doc---objects-protected
                   10976: doc---objects-public
                   10977: doc---objects-selector
                   10978: doc---objects-this
                   10979: doc---objects-<to-inst>
                   10980: doc---objects-[to-inst]
                   10981: doc---objects-to-this
                   10982: doc---objects-xt-new
1.20      pazsan   10983: 
                   10984: 
1.78      anton    10985: @c -------------------------------------------------------------
                   10986: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   10987: @subsection The @file{oof.fs} model
                   10988: @cindex oof
                   10989: @cindex object-oriented programming
1.20      pazsan   10990: 
1.78      anton    10991: @cindex @file{objects.fs}
                   10992: @cindex @file{oof.fs}
1.20      pazsan   10993: 
1.78      anton    10994: This section describes the @file{oof.fs} package.
1.20      pazsan   10995: 
1.78      anton    10996: The package described in this section has been used in bigFORTH since 1991, and
                   10997: used for two large applications: a chromatographic system used to
                   10998: create new medicaments, and a graphic user interface library (MINOS).
1.20      pazsan   10999: 
1.78      anton    11000: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   11001: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   11002: 10(2), 1994.
1.20      pazsan   11003: 
1.78      anton    11004: @menu
                   11005: * Properties of the OOF model::  
                   11006: * Basic OOF Usage::             
                   11007: * The OOF base class::          
                   11008: * Class Declaration::           
                   11009: * Class Implementation::        
                   11010: @end menu
1.20      pazsan   11011: 
1.78      anton    11012: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   11013: @subsubsection Properties of the @file{oof.fs} model
                   11014: @cindex @file{oof.fs} properties
1.20      pazsan   11015: 
1.78      anton    11016: @itemize @bullet
                   11017: @item
                   11018: This model combines object oriented programming with information
                   11019: hiding. It helps you writing large application, where scoping is
                   11020: necessary, because it provides class-oriented scoping.
1.20      pazsan   11021: 
1.78      anton    11022: @item
                   11023: Named objects, object pointers, and object arrays can be created,
                   11024: selector invocation uses the ``object selector'' syntax. Selector invocation
                   11025: to objects and/or selectors on the stack is a bit less convenient, but
                   11026: possible.
1.44      crook    11027: 
1.78      anton    11028: @item
                   11029: Selector invocation and instance variable usage of the active object is
                   11030: straightforward, since both make use of the active object.
1.44      crook    11031: 
1.78      anton    11032: @item
                   11033: Late binding is efficient and easy to use.
1.20      pazsan   11034: 
1.78      anton    11035: @item
                   11036: State-smart objects parse selectors. However, extensibility is provided
                   11037: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20      pazsan   11038: 
1.78      anton    11039: @item
                   11040: An implementation in ANS Forth is available.
1.20      pazsan   11041: 
1.78      anton    11042: @end itemize
1.23      crook    11043: 
                   11044: 
1.78      anton    11045: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   11046: @subsubsection Basic @file{oof.fs} Usage
                   11047: @cindex @file{oof.fs} usage
1.23      crook    11048: 
1.78      anton    11049: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23      crook    11050: 
1.78      anton    11051: You can define a class for graphical objects like this:
1.23      crook    11052: 
1.78      anton    11053: @cindex @code{class} usage
                   11054: @cindex @code{class;} usage
                   11055: @cindex @code{method} usage
                   11056: @example
                   11057: object class graphical \ "object" is the parent class
1.139     pazsan   11058:   method draw ( x y -- )
1.78      anton    11059: class;
                   11060: @end example
1.23      crook    11061: 
1.78      anton    11062: This code defines a class @code{graphical} with an
                   11063: operation @code{draw}.  We can perform the operation
                   11064: @code{draw} on any @code{graphical} object, e.g.:
1.23      crook    11065: 
1.78      anton    11066: @example
                   11067: 100 100 t-rex draw
                   11068: @end example
1.23      crook    11069: 
1.78      anton    11070: @noindent
                   11071: where @code{t-rex} is an object or object pointer, created with e.g.
                   11072: @code{graphical : t-rex}.
1.23      crook    11073: 
1.78      anton    11074: @cindex abstract class
                   11075: How do we create a graphical object? With the present definitions,
                   11076: we cannot create a useful graphical object. The class
                   11077: @code{graphical} describes graphical objects in general, but not
                   11078: any concrete graphical object type (C++ users would call it an
                   11079: @emph{abstract class}); e.g., there is no method for the selector
                   11080: @code{draw} in the class @code{graphical}.
1.23      crook    11081: 
1.78      anton    11082: For concrete graphical objects, we define child classes of the
                   11083: class @code{graphical}, e.g.:
1.23      crook    11084: 
1.78      anton    11085: @example
                   11086: graphical class circle \ "graphical" is the parent class
                   11087:   cell var circle-radius
                   11088: how:
                   11089:   : draw ( x y -- )
                   11090:     circle-radius @@ draw-circle ;
1.23      crook    11091: 
1.139     pazsan   11092:   : init ( n-radius -- )
1.78      anton    11093:     circle-radius ! ;
                   11094: class;
                   11095: @end example
1.1       anton    11096: 
1.78      anton    11097: Here we define a class @code{circle} as a child of @code{graphical},
                   11098: with a field @code{circle-radius}; it defines new methods for the
                   11099: selectors @code{draw} and @code{init} (@code{init} is defined in
                   11100: @code{object}, the parent class of @code{graphical}).
1.1       anton    11101: 
1.78      anton    11102: Now we can create a circle in the dictionary with:
1.1       anton    11103: 
1.78      anton    11104: @example
                   11105: 50 circle : my-circle
                   11106: @end example
1.21      crook    11107: 
1.78      anton    11108: @noindent
                   11109: @code{:} invokes @code{init}, thus initializing the field
                   11110: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   11111: with:
1.1       anton    11112: 
1.78      anton    11113: @example
                   11114: 100 100 my-circle draw
                   11115: @end example
1.1       anton    11116: 
1.78      anton    11117: @cindex selector invocation, restrictions
                   11118: @cindex class definition, restrictions
                   11119: Note: You can only invoke a selector if the receiving object belongs to
                   11120: the class where the selector was defined or one of its descendents;
                   11121: e.g., you can invoke @code{draw} only for objects belonging to
                   11122: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   11123: mechanism will check if you try to invoke a selector that is not
                   11124: defined in this class hierarchy, so you'll get an error at compilation
                   11125: time.
1.1       anton    11126: 
                   11127: 
1.78      anton    11128: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   11129: @subsubsection The @file{oof.fs} base class
                   11130: @cindex @file{oof.fs} base class
1.1       anton    11131: 
1.78      anton    11132: When you define a class, you have to specify a parent class.  So how do
                   11133: you start defining classes? There is one class available from the start:
                   11134: @code{object}. You have to use it as ancestor for all classes. It is the
                   11135: only class that has no parent. Classes are also objects, except that
                   11136: they don't have instance variables; class manipulation such as
                   11137: inheritance or changing definitions of a class is handled through
                   11138: selectors of the class @code{object}.
1.1       anton    11139: 
1.78      anton    11140: @code{object} provides a number of selectors:
1.1       anton    11141: 
1.78      anton    11142: @itemize @bullet
                   11143: @item
                   11144: @code{class} for subclassing, @code{definitions} to add definitions
                   11145: later on, and @code{class?} to get type informations (is the class a
                   11146: subclass of the class passed on the stack?).
1.1       anton    11147: 
1.78      anton    11148: doc---object-class
                   11149: doc---object-definitions
                   11150: doc---object-class?
1.1       anton    11151: 
                   11152: 
1.26      crook    11153: @item
1.78      anton    11154: @code{init} and @code{dispose} as constructor and destructor of the
                   11155: object. @code{init} is invocated after the object's memory is allocated,
                   11156: while @code{dispose} also handles deallocation. Thus if you redefine
                   11157: @code{dispose}, you have to call the parent's dispose with @code{super
                   11158: dispose}, too.
                   11159: 
                   11160: doc---object-init
                   11161: doc---object-dispose
                   11162: 
1.1       anton    11163: 
1.26      crook    11164: @item
1.78      anton    11165: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   11166: @code{[]} to create named and unnamed objects and object arrays or
                   11167: object pointers.
                   11168: 
                   11169: doc---object-new
                   11170: doc---object-new[]
                   11171: doc---object-:
                   11172: doc---object-ptr
                   11173: doc---object-asptr
                   11174: doc---object-[]
                   11175: 
1.1       anton    11176: 
1.26      crook    11177: @item
1.78      anton    11178: @code{::} and @code{super} for explicit scoping. You should use explicit
                   11179: scoping only for super classes or classes with the same set of instance
                   11180: variables. Explicitly-scoped selectors use early binding.
1.21      crook    11181: 
1.78      anton    11182: doc---object-::
                   11183: doc---object-super
1.21      crook    11184: 
                   11185: 
1.26      crook    11186: @item
1.78      anton    11187: @code{self} to get the address of the object
1.21      crook    11188: 
1.78      anton    11189: doc---object-self
1.21      crook    11190: 
                   11191: 
1.78      anton    11192: @item
                   11193: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   11194: pointers and instance defers.
1.21      crook    11195: 
1.78      anton    11196: doc---object-bind
                   11197: doc---object-bound
                   11198: doc---object-link
                   11199: doc---object-is
1.21      crook    11200: 
                   11201: 
1.78      anton    11202: @item
                   11203: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   11204: form the stack, and @code{postpone} to generate selector invocation code.
1.21      crook    11205: 
1.78      anton    11206: doc---object-'
                   11207: doc---object-postpone
1.21      crook    11208: 
                   11209: 
1.78      anton    11210: @item
                   11211: @code{with} and @code{endwith} to select the active object from the
                   11212: stack, and enable its scope. Using @code{with} and @code{endwith}
                   11213: also allows you to create code using selector @code{postpone} without being
                   11214: trapped by the state-smart objects.
1.21      crook    11215: 
1.78      anton    11216: doc---object-with
                   11217: doc---object-endwith
1.21      crook    11218: 
                   11219: 
1.78      anton    11220: @end itemize
1.21      crook    11221: 
1.78      anton    11222: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   11223: @subsubsection Class Declaration
                   11224: @cindex class declaration
1.21      crook    11225: 
1.78      anton    11226: @itemize @bullet
                   11227: @item
                   11228: Instance variables
1.21      crook    11229: 
1.78      anton    11230: doc---oof-var
1.21      crook    11231: 
                   11232: 
1.78      anton    11233: @item
                   11234: Object pointers
1.21      crook    11235: 
1.78      anton    11236: doc---oof-ptr
                   11237: doc---oof-asptr
1.21      crook    11238: 
                   11239: 
1.78      anton    11240: @item
                   11241: Instance defers
1.21      crook    11242: 
1.78      anton    11243: doc---oof-defer
1.21      crook    11244: 
                   11245: 
1.78      anton    11246: @item
                   11247: Method selectors
1.21      crook    11248: 
1.78      anton    11249: doc---oof-early
                   11250: doc---oof-method
1.21      crook    11251: 
                   11252: 
1.78      anton    11253: @item
                   11254: Class-wide variables
1.21      crook    11255: 
1.78      anton    11256: doc---oof-static
1.21      crook    11257: 
                   11258: 
1.78      anton    11259: @item
                   11260: End declaration
1.1       anton    11261: 
1.78      anton    11262: doc---oof-how:
                   11263: doc---oof-class;
1.21      crook    11264: 
                   11265: 
1.78      anton    11266: @end itemize
1.21      crook    11267: 
1.78      anton    11268: @c -------------------------------------------------------------
                   11269: @node Class Implementation,  , Class Declaration, OOF
                   11270: @subsubsection Class Implementation
                   11271: @cindex class implementation
1.21      crook    11272: 
1.78      anton    11273: @c -------------------------------------------------------------
                   11274: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   11275: @subsection The @file{mini-oof.fs} model
                   11276: @cindex mini-oof
1.21      crook    11277: 
1.78      anton    11278: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79      anton    11279: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78      anton    11280: and reduces to the bare minimum of features. This is based on a posting
                   11281: of Bernd Paysan in comp.lang.forth.
1.21      crook    11282: 
1.78      anton    11283: @menu
                   11284: * Basic Mini-OOF Usage::        
                   11285: * Mini-OOF Example::            
                   11286: * Mini-OOF Implementation::     
                   11287: @end menu
1.21      crook    11288: 
1.78      anton    11289: @c -------------------------------------------------------------
                   11290: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
                   11291: @subsubsection Basic @file{mini-oof.fs} Usage
                   11292: @cindex mini-oof usage
1.21      crook    11293: 
1.78      anton    11294: There is a base class (@code{class}, which allocates one cell for the
                   11295: object pointer) plus seven other words: to define a method, a variable,
                   11296: a class; to end a class, to resolve binding, to allocate an object and
                   11297: to compile a class method.
                   11298: @comment TODO better description of the last one
1.26      crook    11299: 
1.21      crook    11300: 
1.78      anton    11301: doc-object
                   11302: doc-method
                   11303: doc-var
                   11304: doc-class
                   11305: doc-end-class
                   11306: doc-defines
                   11307: doc-new
                   11308: doc-::
1.21      crook    11309: 
                   11310: 
                   11311: 
1.78      anton    11312: @c -------------------------------------------------------------
                   11313: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   11314: @subsubsection Mini-OOF Example
                   11315: @cindex mini-oof example
1.1       anton    11316: 
1.78      anton    11317: A short example shows how to use this package. This example, in slightly
                   11318: extended form, is supplied as @file{moof-exm.fs}
                   11319: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20      pazsan   11320: 
1.26      crook    11321: @example
1.78      anton    11322: object class
                   11323:   method init
                   11324:   method draw
                   11325: end-class graphical
1.26      crook    11326: @end example
1.20      pazsan   11327: 
1.78      anton    11328: This code defines a class @code{graphical} with an
                   11329: operation @code{draw}.  We can perform the operation
                   11330: @code{draw} on any @code{graphical} object, e.g.:
1.20      pazsan   11331: 
1.26      crook    11332: @example
1.78      anton    11333: 100 100 t-rex draw
1.26      crook    11334: @end example
1.12      anton    11335: 
1.78      anton    11336: where @code{t-rex} is an object or object pointer, created with e.g.
                   11337: @code{graphical new Constant t-rex}.
1.12      anton    11338: 
1.78      anton    11339: For concrete graphical objects, we define child classes of the
                   11340: class @code{graphical}, e.g.:
1.12      anton    11341: 
1.26      crook    11342: @example
                   11343: graphical class
1.78      anton    11344:   cell var circle-radius
                   11345: end-class circle \ "graphical" is the parent class
1.12      anton    11346: 
1.78      anton    11347: :noname ( x y -- )
                   11348:   circle-radius @@ draw-circle ; circle defines draw
                   11349: :noname ( r -- )
                   11350:   circle-radius ! ; circle defines init
                   11351: @end example
1.12      anton    11352: 
1.78      anton    11353: There is no implicit init method, so we have to define one. The creation
                   11354: code of the object now has to call init explicitely.
1.21      crook    11355: 
1.78      anton    11356: @example
                   11357: circle new Constant my-circle
                   11358: 50 my-circle init
1.12      anton    11359: @end example
                   11360: 
1.78      anton    11361: It is also possible to add a function to create named objects with
                   11362: automatic call of @code{init}, given that all objects have @code{init}
                   11363: on the same place:
1.38      anton    11364: 
1.78      anton    11365: @example
                   11366: : new: ( .. o "name" -- )
                   11367:     new dup Constant init ;
                   11368: 80 circle new: large-circle
                   11369: @end example
1.12      anton    11370: 
1.78      anton    11371: We can draw this new circle at (100,100) with:
1.12      anton    11372: 
1.78      anton    11373: @example
                   11374: 100 100 my-circle draw
                   11375: @end example
1.12      anton    11376: 
1.78      anton    11377: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
                   11378: @subsubsection @file{mini-oof.fs} Implementation
1.12      anton    11379: 
1.78      anton    11380: Object-oriented systems with late binding typically use a
                   11381: ``vtable''-approach: the first variable in each object is a pointer to a
                   11382: table, which contains the methods as function pointers. The vtable
                   11383: may also contain other information.
1.12      anton    11384: 
1.79      anton    11385: So first, let's declare selectors:
1.37      anton    11386: 
                   11387: @example
1.79      anton    11388: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
1.78      anton    11389:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
                   11390: @end example
1.37      anton    11391: 
1.79      anton    11392: During selector declaration, the number of selectors and instance
                   11393: variables is on the stack (in address units). @code{method} creates one
                   11394: selector and increments the selector number. To execute a selector, it
1.78      anton    11395: takes the object, fetches the vtable pointer, adds the offset, and
1.79      anton    11396: executes the method @i{xt} stored there. Each selector takes the object
                   11397: it is invoked with as top of stack parameter; it passes the parameters
                   11398: (including the object) unchanged to the appropriate method which should
1.78      anton    11399: consume that object.
1.37      anton    11400: 
1.78      anton    11401: Now, we also have to declare instance variables
1.37      anton    11402: 
1.78      anton    11403: @example
1.79      anton    11404: : var ( m v size "name" -- m v' ) Create  over , +
1.78      anton    11405:   DOES> ( o -- addr ) @@ + ;
1.37      anton    11406: @end example
                   11407: 
1.78      anton    11408: As before, a word is created with the current offset. Instance
                   11409: variables can have different sizes (cells, floats, doubles, chars), so
                   11410: all we do is take the size and add it to the offset. If your machine
                   11411: has alignment restrictions, put the proper @code{aligned} or
                   11412: @code{faligned} before the variable, to adjust the variable
                   11413: offset. That's why it is on the top of stack.
1.37      anton    11414: 
1.78      anton    11415: We need a starting point (the base object) and some syntactic sugar:
1.37      anton    11416: 
1.78      anton    11417: @example
                   11418: Create object  1 cells , 2 cells ,
1.79      anton    11419: : class ( class -- class selectors vars ) dup 2@@ ;
1.78      anton    11420: @end example
1.12      anton    11421: 
1.78      anton    11422: For inheritance, the vtable of the parent object has to be
                   11423: copied when a new, derived class is declared. This gives all the
                   11424: methods of the parent class, which can be overridden, though.
1.12      anton    11425: 
1.78      anton    11426: @example
1.79      anton    11427: : end-class  ( class selectors vars "name" -- )
1.78      anton    11428:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   11429:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
                   11430: @end example
1.12      anton    11431: 
1.78      anton    11432: The first line creates the vtable, initialized with
                   11433: @code{noop}s. The second line is the inheritance mechanism, it
                   11434: copies the xts from the parent vtable.
1.12      anton    11435: 
1.78      anton    11436: We still have no way to define new methods, let's do that now:
1.12      anton    11437: 
1.26      crook    11438: @example
1.79      anton    11439: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78      anton    11440: @end example
1.12      anton    11441: 
1.78      anton    11442: To allocate a new object, we need a word, too:
1.12      anton    11443: 
1.78      anton    11444: @example
                   11445: : new ( class -- o )  here over @@ allot swap over ! ;
1.12      anton    11446: @end example
                   11447: 
1.78      anton    11448: Sometimes derived classes want to access the method of the
                   11449: parent object. There are two ways to achieve this with Mini-OOF:
                   11450: first, you could use named words, and second, you could look up the
                   11451: vtable of the parent object.
1.12      anton    11452: 
1.78      anton    11453: @example
                   11454: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
                   11455: @end example
1.12      anton    11456: 
                   11457: 
1.78      anton    11458: Nothing can be more confusing than a good example, so here is
                   11459: one. First let's declare a text object (called
                   11460: @code{button}), that stores text and position:
1.12      anton    11461: 
1.78      anton    11462: @example
                   11463: object class
                   11464:   cell var text
                   11465:   cell var len
                   11466:   cell var x
                   11467:   cell var y
                   11468:   method init
                   11469:   method draw
                   11470: end-class button
                   11471: @end example
1.12      anton    11472: 
1.78      anton    11473: @noindent
                   11474: Now, implement the two methods, @code{draw} and @code{init}:
1.21      crook    11475: 
1.26      crook    11476: @example
1.78      anton    11477: :noname ( o -- )
                   11478:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
                   11479:  button defines draw
                   11480: :noname ( addr u o -- )
                   11481:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
                   11482:  button defines init
1.26      crook    11483: @end example
1.12      anton    11484: 
1.78      anton    11485: @noindent
                   11486: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79      anton    11487: new data and no new selectors:
1.78      anton    11488: 
                   11489: @example
                   11490: button class
                   11491: end-class bold-button
1.12      anton    11492: 
1.78      anton    11493: : bold   27 emit ." [1m" ;
                   11494: : normal 27 emit ." [0m" ;
                   11495: @end example
1.1       anton    11496: 
1.78      anton    11497: @noindent
                   11498: The class @code{bold-button} has a different draw method to
                   11499: @code{button}, but the new method is defined in terms of the draw method
                   11500: for @code{button}:
1.20      pazsan   11501: 
1.78      anton    11502: @example
                   11503: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   11504: @end example
1.21      crook    11505: 
1.78      anton    11506: @noindent
1.79      anton    11507: Finally, create two objects and apply selectors:
1.21      crook    11508: 
1.26      crook    11509: @example
1.78      anton    11510: button new Constant foo
                   11511: s" thin foo" foo init
                   11512: page
                   11513: foo draw
                   11514: bold-button new Constant bar
                   11515: s" fat bar" bar init
                   11516: 1 bar y !
                   11517: bar draw
1.26      crook    11518: @end example
1.21      crook    11519: 
                   11520: 
1.78      anton    11521: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
                   11522: @subsection Comparison with other object models
                   11523: @cindex comparison of object models
                   11524: @cindex object models, comparison
                   11525: 
                   11526: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   11527: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   11528: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   11529: relation of the object models described here to two well-known and two
                   11530: closely-related (by the use of method maps) models.  Andras Zsoter
                   11531: helped us with this section.
                   11532: 
                   11533: @cindex Neon model
                   11534: The most popular model currently seems to be the Neon model (see
                   11535: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   11536: 1997) by Andrew McKewan) but this model has a number of limitations
                   11537: @footnote{A longer version of this critique can be
                   11538: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   11539: Dimensions, May 1997) by Anton Ertl.}:
                   11540: 
                   11541: @itemize @bullet
                   11542: @item
                   11543: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
                   11544: to pass objects on the stack.
1.21      crook    11545: 
1.78      anton    11546: @item
                   11547: It requires that the selector parses the input stream (at
1.79      anton    11548: compile time); this leads to reduced extensibility and to bugs that are
1.78      anton    11549: hard to find.
1.21      crook    11550: 
1.78      anton    11551: @item
1.79      anton    11552: It allows using every selector on every object; this eliminates the
                   11553: need for interfaces, but makes it harder to create efficient
                   11554: implementations.
1.78      anton    11555: @end itemize
1.21      crook    11556: 
1.78      anton    11557: @cindex Pountain's object-oriented model
                   11558: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   11559: Press, London, 1987) by Dick Pountain. However, it is not really about
                   11560: object-oriented programming, because it hardly deals with late
                   11561: binding. Instead, it focuses on features like information hiding and
                   11562: overloading that are characteristic of modular languages like Ada (83).
1.26      crook    11563: 
1.78      anton    11564: @cindex Zsoter's object-oriented model
1.79      anton    11565: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
                   11566: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
                   11567: describes a model that makes heavy use of an active object (like
                   11568: @code{this} in @file{objects.fs}): The active object is not only used
                   11569: for accessing all fields, but also specifies the receiving object of
                   11570: every selector invocation; you have to change the active object
                   11571: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
                   11572: changes more or less implicitly at @code{m: ... ;m}. Such a change at
                   11573: the method entry point is unnecessary with Zsoter's model, because the
                   11574: receiving object is the active object already. On the other hand, the
                   11575: explicit change is absolutely necessary in that model, because otherwise
                   11576: no one could ever change the active object. An ANS Forth implementation
                   11577: of this model is available through
                   11578: @uref{http://www.forth.org/oopf.html}.
1.21      crook    11579: 
1.78      anton    11580: @cindex @file{oof.fs}, differences to other models
                   11581: The @file{oof.fs} model combines information hiding and overloading
                   11582: resolution (by keeping names in various word lists) with object-oriented
                   11583: programming. It sets the active object implicitly on method entry, but
                   11584: also allows explicit changing (with @code{>o...o>} or with
                   11585: @code{with...endwith}). It uses parsing and state-smart objects and
                   11586: classes for resolving overloading and for early binding: the object or
                   11587: class parses the selector and determines the method from this. If the
                   11588: selector is not parsed by an object or class, it performs a call to the
                   11589: selector for the active object (late binding), like Zsoter's model.
                   11590: Fields are always accessed through the active object. The big
                   11591: disadvantage of this model is the parsing and the state-smartness, which
                   11592: reduces extensibility and increases the opportunities for subtle bugs;
                   11593: essentially, you are only safe if you never tick or @code{postpone} an
                   11594: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21      crook    11595: 
1.78      anton    11596: @cindex @file{mini-oof.fs}, differences to other models
                   11597: The @file{mini-oof.fs} model is quite similar to a very stripped-down
                   11598: version of the @file{objects.fs} model, but syntactically it is a
                   11599: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21      crook    11600: 
                   11601: 
1.78      anton    11602: @c -------------------------------------------------------------
1.150     anton    11603: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78      anton    11604: @section Programming Tools
                   11605: @cindex programming tools
1.21      crook    11606: 
1.78      anton    11607: @c !! move this and assembler down below OO stuff.
1.21      crook    11608: 
1.78      anton    11609: @menu
1.150     anton    11610: * Examining::                   Data and Code.
                   11611: * Forgetting words::            Usually before reloading.
1.78      anton    11612: * Debugging::                   Simple and quick.
                   11613: * Assertions::                  Making your programs self-checking.
                   11614: * Singlestep Debugger::         Executing your program word by word.
                   11615: @end menu
1.21      crook    11616: 
1.78      anton    11617: @node Examining, Forgetting words, Programming Tools, Programming Tools
                   11618: @subsection Examining data and code
                   11619: @cindex examining data and code
                   11620: @cindex data examination
                   11621: @cindex code examination
1.44      crook    11622: 
1.78      anton    11623: The following words inspect the stack non-destructively:
1.21      crook    11624: 
1.78      anton    11625: doc-.s
                   11626: doc-f.s
1.158     anton    11627: doc-maxdepth-.s
1.44      crook    11628: 
1.78      anton    11629: There is a word @code{.r} but it does @i{not} display the return stack!
                   11630: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21      crook    11631: 
1.78      anton    11632: doc-depth
                   11633: doc-fdepth
                   11634: doc-clearstack
1.124     anton    11635: doc-clearstacks
1.21      crook    11636: 
1.78      anton    11637: The following words inspect memory.
1.21      crook    11638: 
1.78      anton    11639: doc-?
                   11640: doc-dump
1.21      crook    11641: 
1.78      anton    11642: And finally, @code{see} allows to inspect code:
1.21      crook    11643: 
1.78      anton    11644: doc-see
                   11645: doc-xt-see
1.111     anton    11646: doc-simple-see
                   11647: doc-simple-see-range
1.182   ! anton    11648: doc-see-code
        !          11649: doc-see-code-range
1.21      crook    11650: 
1.78      anton    11651: @node Forgetting words, Debugging, Examining, Programming Tools
                   11652: @subsection Forgetting words
                   11653: @cindex words, forgetting
                   11654: @cindex forgeting words
1.21      crook    11655: 
1.78      anton    11656: @c  anton: other, maybe better places for this subsection: Defining Words;
                   11657: @c  Dictionary allocation.  At least a reference should be there.
1.21      crook    11658: 
1.78      anton    11659: Forth allows you to forget words (and everything that was alloted in the
                   11660: dictonary after them) in a LIFO manner.
1.21      crook    11661: 
1.78      anton    11662: doc-marker
1.21      crook    11663: 
1.78      anton    11664: The most common use of this feature is during progam development: when
                   11665: you change a source file, forget all the words it defined and load it
                   11666: again (since you also forget everything defined after the source file
                   11667: was loaded, you have to reload that, too).  Note that effects like
                   11668: storing to variables and destroyed system words are not undone when you
                   11669: forget words.  With a system like Gforth, that is fast enough at
                   11670: starting up and compiling, I find it more convenient to exit and restart
                   11671: Gforth, as this gives me a clean slate.
1.21      crook    11672: 
1.78      anton    11673: Here's an example of using @code{marker} at the start of a source file
                   11674: that you are debugging; it ensures that you only ever have one copy of
                   11675: the file's definitions compiled at any time:
1.21      crook    11676: 
1.78      anton    11677: @example
                   11678: [IFDEF] my-code
                   11679:     my-code
                   11680: [ENDIF]
1.26      crook    11681: 
1.78      anton    11682: marker my-code
                   11683: init-included-files
1.21      crook    11684: 
1.78      anton    11685: \ .. definitions start here
                   11686: \ .
                   11687: \ .
                   11688: \ end
                   11689: @end example
1.21      crook    11690: 
1.26      crook    11691: 
1.78      anton    11692: @node Debugging, Assertions, Forgetting words, Programming Tools
                   11693: @subsection Debugging
                   11694: @cindex debugging
1.21      crook    11695: 
1.78      anton    11696: Languages with a slow edit/compile/link/test development loop tend to
                   11697: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21      crook    11698: 
1.78      anton    11699: A much better (faster) way in fast-compiling languages is to add
                   11700: printing code at well-selected places, let the program run, look at
                   11701: the output, see where things went wrong, add more printing code, etc.,
                   11702: until the bug is found.
1.21      crook    11703: 
1.78      anton    11704: The simple debugging aids provided in @file{debugs.fs}
                   11705: are meant to support this style of debugging.
1.21      crook    11706: 
1.78      anton    11707: The word @code{~~} prints debugging information (by default the source
                   11708: location and the stack contents). It is easy to insert. If you use Emacs
                   11709: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   11710: query-replace them with nothing). The deferred words
1.101     anton    11711: @code{printdebugdata} and @code{.debugline} control the output of
1.78      anton    11712: @code{~~}. The default source location output format works well with
                   11713: Emacs' compilation mode, so you can step through the program at the
                   11714: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   11715: is that you can step in any direction and you know where the crash has
                   11716: happened or where the strange data has occurred).
1.21      crook    11717: 
1.78      anton    11718: doc-~~
                   11719: doc-printdebugdata
1.101     anton    11720: doc-.debugline
1.21      crook    11721: 
1.106     anton    11722: @cindex filenames in @code{~~} output
                   11723: @code{~~} (and assertions) will usually print the wrong file name if a
                   11724: marker is executed in the same file after their occurance.  They will
                   11725: print @samp{*somewhere*} as file name if a marker is executed in the
                   11726: same file before their occurance.
                   11727: 
                   11728: 
1.78      anton    11729: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   11730: @subsection Assertions
                   11731: @cindex assertions
1.21      crook    11732: 
1.78      anton    11733: It is a good idea to make your programs self-checking, especially if you
                   11734: make an assumption that may become invalid during maintenance (for
                   11735: example, that a certain field of a data structure is never zero). Gforth
                   11736: supports @dfn{assertions} for this purpose. They are used like this:
1.21      crook    11737: 
                   11738: @example
1.78      anton    11739: assert( @i{flag} )
1.26      crook    11740: @end example
                   11741: 
1.78      anton    11742: The code between @code{assert(} and @code{)} should compute a flag, that
                   11743: should be true if everything is alright and false otherwise. It should
                   11744: not change anything else on the stack. The overall stack effect of the
                   11745: assertion is @code{( -- )}. E.g.
1.21      crook    11746: 
1.26      crook    11747: @example
1.78      anton    11748: assert( 1 1 + 2 = ) \ what we learn in school
                   11749: assert( dup 0<> ) \ assert that the top of stack is not zero
                   11750: assert( false ) \ this code should not be reached
1.21      crook    11751: @end example
                   11752: 
1.78      anton    11753: The need for assertions is different at different times. During
                   11754: debugging, we want more checking, in production we sometimes care more
                   11755: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   11756: becomes a comment. Depending on the importance of an assertion and the
                   11757: time it takes to check it, you may want to turn off some assertions and
                   11758: keep others turned on. Gforth provides several levels of assertions for
                   11759: this purpose:
                   11760: 
                   11761: 
                   11762: doc-assert0(
                   11763: doc-assert1(
                   11764: doc-assert2(
                   11765: doc-assert3(
                   11766: doc-assert(
                   11767: doc-)
1.21      crook    11768: 
                   11769: 
1.78      anton    11770: The variable @code{assert-level} specifies the highest assertions that
                   11771: are turned on. I.e., at the default @code{assert-level} of one,
                   11772: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   11773: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26      crook    11774: 
1.78      anton    11775: The value of @code{assert-level} is evaluated at compile-time, not at
                   11776: run-time. Therefore you cannot turn assertions on or off at run-time;
                   11777: you have to set the @code{assert-level} appropriately before compiling a
                   11778: piece of code. You can compile different pieces of code at different
                   11779: @code{assert-level}s (e.g., a trusted library at level 1 and
                   11780: newly-written code at level 3).
1.26      crook    11781: 
                   11782: 
1.78      anton    11783: doc-assert-level
1.26      crook    11784: 
                   11785: 
1.78      anton    11786: If an assertion fails, a message compatible with Emacs' compilation mode
                   11787: is produced and the execution is aborted (currently with @code{ABORT"}.
                   11788: If there is interest, we will introduce a special throw code. But if you
                   11789: intend to @code{catch} a specific condition, using @code{throw} is
                   11790: probably more appropriate than an assertion).
1.106     anton    11791: 
                   11792: @cindex filenames in assertion output
                   11793: Assertions (and @code{~~}) will usually print the wrong file name if a
                   11794: marker is executed in the same file after their occurance.  They will
                   11795: print @samp{*somewhere*} as file name if a marker is executed in the
                   11796: same file before their occurance.
1.44      crook    11797: 
1.78      anton    11798: Definitions in ANS Forth for these assertion words are provided
                   11799: in @file{compat/assert.fs}.
1.26      crook    11800: 
1.44      crook    11801: 
1.78      anton    11802: @node Singlestep Debugger,  , Assertions, Programming Tools
                   11803: @subsection Singlestep Debugger
                   11804: @cindex singlestep Debugger
                   11805: @cindex debugging Singlestep
1.44      crook    11806: 
1.159     anton    11807: The singlestep debugger works only with the engine @code{gforth-ditc}.
1.112     anton    11808: 
1.78      anton    11809: When you create a new word there's often the need to check whether it
                   11810: behaves correctly or not. You can do this by typing @code{dbg
                   11811: badword}. A debug session might look like this:
1.26      crook    11812: 
1.78      anton    11813: @example
                   11814: : badword 0 DO i . LOOP ;  ok
                   11815: 2 dbg badword 
                   11816: : badword  
                   11817: Scanning code...
1.44      crook    11818: 
1.78      anton    11819: Nesting debugger ready!
1.44      crook    11820: 
1.78      anton    11821: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   11822: 400D4740  8049F68 DO             -> [ 0 ] 
                   11823: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   11824: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   11825: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   11826: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   11827: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   11828: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   11829: 400D4758  804B384 ;              ->  ok
                   11830: @end example
1.21      crook    11831: 
1.78      anton    11832: Each line displayed is one step. You always have to hit return to
                   11833: execute the next word that is displayed. If you don't want to execute
                   11834: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   11835: an overview what keys are available:
1.44      crook    11836: 
1.78      anton    11837: @table @i
1.44      crook    11838: 
1.78      anton    11839: @item @key{RET}
                   11840: Next; Execute the next word.
1.21      crook    11841: 
1.78      anton    11842: @item n
                   11843: Nest; Single step through next word.
1.44      crook    11844: 
1.78      anton    11845: @item u
                   11846: Unnest; Stop debugging and execute rest of word. If we got to this word
                   11847: with nest, continue debugging with the calling word.
1.44      crook    11848: 
1.78      anton    11849: @item d
                   11850: Done; Stop debugging and execute rest.
1.21      crook    11851: 
1.78      anton    11852: @item s
                   11853: Stop; Abort immediately.
1.44      crook    11854: 
1.78      anton    11855: @end table
1.44      crook    11856: 
1.78      anton    11857: Debugging large application with this mechanism is very difficult, because
                   11858: you have to nest very deeply into the program before the interesting part
                   11859: begins. This takes a lot of time. 
1.26      crook    11860: 
1.78      anton    11861: To do it more directly put a @code{BREAK:} command into your source code.
                   11862: When program execution reaches @code{BREAK:} the single step debugger is
                   11863: invoked and you have all the features described above.
1.44      crook    11864: 
1.78      anton    11865: If you have more than one part to debug it is useful to know where the
                   11866: program has stopped at the moment. You can do this by the 
                   11867: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   11868: string is typed out when the ``breakpoint'' is reached.
1.44      crook    11869: 
1.26      crook    11870: 
1.78      anton    11871: doc-dbg
                   11872: doc-break:
                   11873: doc-break"
1.44      crook    11874: 
1.150     anton    11875: @c ------------------------------------------------------------
                   11876: @node C Interface, Assembler and Code Words, Programming Tools, Words
                   11877: @section C Interface
                   11878: @cindex C interface
                   11879: @cindex foreign language interface
                   11880: @cindex interface to C functions
                   11881: 
1.178     anton    11882: Note that the C interface is not yet complete; callbacks are missing,
                   11883: as well as a way of declaring structs, unions, and their fields.
1.150     anton    11884: 
                   11885: @menu
                   11886: * Calling C Functions::         
                   11887: * Declaring C Functions::       
1.180     anton    11888: * Calling C function pointers::  
1.150     anton    11889: * Callbacks::                   
1.178     anton    11890: * C interface internals::       
1.155     anton    11891: * Low-Level C Interface Words::  
1.150     anton    11892: @end menu
                   11893: 
1.151     pazsan   11894: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150     anton    11895: @subsection Calling C functions
1.155     anton    11896: @cindex C functions, calls to
                   11897: @cindex calling C functions
1.150     anton    11898: 
1.151     pazsan   11899: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150     anton    11900: can call it as follows: You push the arguments on the stack(s), and
                   11901: then call the word for the C function.  The arguments have to be
                   11902: pushed in the same order as the arguments appear in the C
                   11903: documentation (i.e., the first argument is deepest on the stack).
                   11904: Integer and pointer arguments have to be pushed on the data stack,
                   11905: floating-point arguments on the FP stack; these arguments are consumed
1.155     anton    11906: by the called C function.
1.150     anton    11907: 
1.155     anton    11908: On returning from the C function, the return value, if any, resides on
                   11909: the appropriate stack: an integer return value is pushed on the data
                   11910: stack, an FP return value on the FP stack, and a void return value
                   11911: results in not pushing anything.  Note that most C functions have a
                   11912: return value, even if that is often not used in C; in Forth, you have
                   11913: to @code{drop} this return value explicitly if you do not use it.
1.150     anton    11914: 
1.177     anton    11915: The C interface automatically converts between the C type and the
                   11916: Forth type as necessary, on a best-effort basis (in some cases, there
                   11917: may be some loss).
1.150     anton    11918: 
                   11919: As an example, consider the POSIX function @code{lseek()}:
                   11920: 
                   11921: @example
                   11922: off_t lseek(int fd, off_t offset, int whence);
                   11923: @end example
                   11924: 
                   11925: This function takes three integer arguments, and returns an integer
                   11926: argument, so a Forth call for setting the current file offset to the
                   11927: start of the file could look like this:
                   11928: 
                   11929: @example
                   11930: fd @@ 0 SEEK_SET lseek -1 = if
                   11931:   ... \ error handling
                   11932: then
                   11933: @end example
                   11934: 
                   11935: You might be worried that an @code{off_t} does not fit into a cell, so
                   11936: you could not pass larger offsets to lseek, and might get only a part
1.155     anton    11937: of the return values.  In that case, in your declaration of the
                   11938: function (@pxref{Declaring C Functions}) you should declare it to use
                   11939: double-cells for the off_t argument and return value, and maybe give
                   11940: the resulting Forth word a different name, like @code{dlseek}; the
                   11941: result could be called like this:
1.150     anton    11942: 
                   11943: @example
                   11944: fd @@ 0. SEEK_SET dlseek -1. d= if
                   11945:   ... \ error handling
                   11946: then
                   11947: @end example
                   11948: 
                   11949: Passing and returning structs or unions is currently not supported by
                   11950: our interface@footnote{If you know the calling convention of your C
                   11951: compiler, you usually can call such functions in some way, but that
                   11952: way is usually not portable between platforms, and sometimes not even
                   11953: between C compilers.}.
                   11954: 
1.177     anton    11955: Calling functions with a variable number of arguments (@emph{variadic}
                   11956: functions, e.g., @code{printf()}) is only supported by having you
                   11957: declare one function-calling word for each argument pattern, and
                   11958: calling the appropriate word for the desired pattern.
                   11959: 
1.150     anton    11960: 
1.155     anton    11961: 
1.180     anton    11962: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
1.150     anton    11963: @subsection Declaring C Functions
1.155     anton    11964: @cindex C functions, declarations
                   11965: @cindex declaring C functions
1.150     anton    11966: 
                   11967: Before you can call @code{lseek} or @code{dlseek}, you have to declare
1.177     anton    11968: it.  The declaration consists of two parts: 
                   11969: 
                   11970: @table @b
                   11971: 
                   11972: @item The C part
1.179     anton    11973: is the C declaration of the function, or more typically and portably,
                   11974: a C-style @code{#include} of a file that contains the declaration of
                   11975: the C function.
1.177     anton    11976: 
                   11977: @item The Forth part
                   11978: declares the Forth types of the parameters and the Forth word name
                   11979: corresponding to the C function.
                   11980: 
                   11981: @end table
                   11982: 
                   11983: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
                   11984: declarations are:
                   11985: 
                   11986: @example
                   11987: \c #define _FILE_OFFSET_BITS 64
                   11988: \c #include <sys/types.h>
                   11989: \c #include <unistd.h>
                   11990: c-function lseek lseek n n n -- n
                   11991: c-function dlseek lseek n d n -- d
                   11992: @end example
                   11993: 
1.178     anton    11994: The C part of the declarations is prefixed by @code{\c}, and the rest
1.177     anton    11995: of the line is ordinary C code.  You can use as many lines of C
                   11996: declarations as you like, and they are visible for all further
                   11997: function declarations.
                   11998: 
                   11999: The Forth part declares each interface word with @code{c-function},
                   12000: followed by the Forth name of the word, the C name of the called
                   12001: function, and the stack effect of the word.  The stack effect contains
1.178     anton    12002: an arbitrary number of types of parameters, then @code{--}, and then
1.177     anton    12003: exactly one type for the return value.  The possible types are:
                   12004: 
                   12005: @table @code
                   12006: 
                   12007: @item n
                   12008: single-cell integer
                   12009: 
                   12010: @item a
                   12011: address (single-cell)
                   12012: 
                   12013: @item d
                   12014: double-cell integer
                   12015: 
                   12016: @item r
                   12017: floating-point value
                   12018: 
                   12019: @item func
                   12020: C function pointer
                   12021: 
                   12022: @item void
                   12023: no value (used as return type for void functions)
                   12024: 
                   12025: @end table
                   12026: 
                   12027: @cindex variadic C functions
                   12028: 
                   12029: To deal with variadic C functions, you can declare one Forth word for
                   12030: every pattern you want to use, e.g.:
                   12031: 
                   12032: @example
                   12033: \c #include <stdio.h>
                   12034: c-function printf-nr printf a n r -- n
                   12035: c-function printf-rn printf a r n -- n
                   12036: @end example
                   12037: 
                   12038: Note that with C functions declared as variadic (or if you don't
                   12039: provide a prototype), the C interface has no C type to convert to, so
                   12040: no automatic conversion happens, which may lead to portability
                   12041: problems in some cases.  In such cases you can perform the conversion
                   12042: explicitly on the C level, e.g., as follows:
                   12043: 
                   12044: @example
1.178     anton    12045: \c #define printfll(s,ll) printf(s,(long long)ll)
                   12046: c-function printfll printfll a n -- n
1.177     anton    12047: @end example
                   12048: 
                   12049: Here, instead of calling @code{printf()} directly, we define a macro
1.178     anton    12050: that casts (converts) the Forth single-cell integer into a
                   12051: C @code{long long} before calling @code{printf()}.
1.177     anton    12052: 
                   12053: doc-\c
                   12054: doc-c-function
                   12055: 
                   12056: In order to work, this C interface invokes GCC at run-time and uses
1.178     anton    12057: dynamic linking.  If these features are not available, there are
                   12058: other, less convenient and less portable C interfaces in @file{lib.fs}
                   12059: and @file{oldlib.fs}.  These interfaces are mostly undocumented and
                   12060: mostly incompatible with each other and with the documented C
                   12061: interface; you can find some examples for the @file{lib.fs} interface
                   12062: in @file{lib.fs}.
1.177     anton    12063: 
                   12064: 
1.180     anton    12065: @node Calling C function pointers, Callbacks, Declaring C Functions, C Interface
                   12066: @subsection Calling C function pointers from Forth
                   12067: @cindex C function pointers, calling from Forth
1.177     anton    12068: 
1.180     anton    12069: If you come across a C function pointer (e.g., in some C-constructed
                   12070: structure) and want to call it from your Forth program, you can also
                   12071: use the features explained until now to achieve that, as follows:
1.150     anton    12072: 
1.180     anton    12073: Let us assume that there is a C function pointer type @code{func1}
                   12074: defined in some header file @file{func1.h}, and you know that these
                   12075: functions take one integer argument and return an integer result; and
                   12076: you want to call functions through such pointers.  Just define
1.155     anton    12077: 
1.180     anton    12078: @example
                   12079: \c #include <func1.h>
                   12080: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
                   12081: c-function call-func1 call_func1 n func -- n
                   12082: @end example
                   12083: 
                   12084: and then you can call a function pointed to by, say @code{func1a} as
                   12085: follows:
                   12086: 
                   12087: @example
                   12088: -5 func1a call-func1 .
                   12089: @end example
                   12090: 
                   12091: In the C part, @code{call_func} is defined as a macro to avoid having
                   12092: to declare the exact parameter and return types, so the C compiler
                   12093: knows them from the declaration of @code{func1}.
                   12094: 
                   12095: The Forth word @code{call-func1} is similar to @code{execute}, except
                   12096: that it takes a C @code{func1} pointer instead of a Forth execution
                   12097: token, and it is specific to @code{func1} pointers.  For each type of
                   12098: function pointer you want to call from Forth, you have to define
                   12099: a separate calling word.
                   12100: 
                   12101: 
                   12102: @node Callbacks, C interface internals, Calling C function pointers, C Interface
1.150     anton    12103: @subsection Callbacks
1.155     anton    12104: @cindex Callback functions written in Forth
                   12105: @cindex C function pointers to Forth words
                   12106: 
1.177     anton    12107: Callbacks are not yet supported by the documented C interface.  You
                   12108: can use the undocumented @file{lib.fs} interface for callbacks.
                   12109: 
1.155     anton    12110: In some cases you have to pass a function pointer to a C function,
                   12111: i.e., the library wants to call back to your application (and the
                   12112: pointed-to function is called a callback function).  You can pass the
                   12113: address of an existing C function (that you get with @code{lib-sym},
                   12114: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
                   12115: function, you probably want to define the function as a Forth word.
                   12116: 
                   12117: @c I don't understand the existing callback interface from the example - anton
                   12118: 
1.165     anton    12119: 
                   12120: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
                   12121: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
                   12122: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
                   12123: @c > > C-Funktionsadresse auf dem TOS).
                   12124: @c >
                   12125: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
                   12126: @c > gesehen habe, wozu das gut ist.
                   12127: @c 
                   12128: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch 
                   12129: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen 
                   12130: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit 
                   12131: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte 
                   12132: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit 
                   12133: @c demselben Prototyp.
                   12134: 
                   12135: 
1.178     anton    12136: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
1.177     anton    12137: @subsection How the C interface works
                   12138: 
                   12139: The documented C interface works by generating a C code out of the
                   12140: declarations.
                   12141: 
                   12142: In particular, for every Forth word declared with @code{c-function},
                   12143: it generates a wrapper function in C that takes the Forth data from
                   12144: the Forth stacks, and calls the target C function with these data as
                   12145: arguments.  The C compiler then performs an implicit conversion
                   12146: between the Forth type from the stack, and the C type for the
                   12147: parameter, which is given by the C function prototype.  After the C
                   12148: function returns, the return value is likewise implicitly converted to
                   12149: a Forth type and written back on the stack.
                   12150: 
                   12151: The @code{\c} lines are literally included in the C code (but without
                   12152: the @code{\c}), and provide the necessary declarations so that the C
                   12153: compiler knows the C types and has enough information to perform the
                   12154: conversion.
                   12155: 
                   12156: These wrapper functions are eventually compiled and dynamically linked
                   12157: into Gforth, and then they can be called.
                   12158: 
                   12159: 
1.178     anton    12160: @node Low-Level C Interface Words,  , C interface internals, C Interface
1.155     anton    12161: @subsection Low-Level C Interface Words
1.44      crook    12162: 
1.155     anton    12163: doc-open-lib
                   12164: doc-lib-sym
1.177     anton    12165: doc-call-c
1.26      crook    12166: 
1.78      anton    12167: @c -------------------------------------------------------------
1.150     anton    12168: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78      anton    12169: @section Assembler and Code Words
                   12170: @cindex assembler
                   12171: @cindex code words
1.44      crook    12172: 
1.78      anton    12173: @menu
                   12174: * Code and ;code::              
                   12175: * Common Assembler::            Assembler Syntax
                   12176: * Common Disassembler::         
                   12177: * 386 Assembler::               Deviations and special cases
                   12178: * Alpha Assembler::             Deviations and special cases
                   12179: * MIPS assembler::              Deviations and special cases
1.161     anton    12180: * PowerPC assembler::           Deviations and special cases
1.78      anton    12181: * Other assemblers::            How to write them
                   12182: @end menu
1.21      crook    12183: 
1.78      anton    12184: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
                   12185: @subsection @code{Code} and @code{;code}
1.26      crook    12186: 
1.78      anton    12187: Gforth provides some words for defining primitives (words written in
                   12188: machine code), and for defining the machine-code equivalent of
                   12189: @code{DOES>}-based defining words. However, the machine-independent
                   12190: nature of Gforth poses a few problems: First of all, Gforth runs on
                   12191: several architectures, so it can provide no standard assembler. What's
                   12192: worse is that the register allocation not only depends on the processor,
                   12193: but also on the @code{gcc} version and options used.
1.44      crook    12194: 
1.78      anton    12195: The words that Gforth offers encapsulate some system dependences (e.g.,
                   12196: the header structure), so a system-independent assembler may be used in
                   12197: Gforth. If you do not have an assembler, you can compile machine code
                   12198: directly with @code{,} and @code{c,}@footnote{This isn't portable,
                   12199: because these words emit stuff in @i{data} space; it works because
                   12200: Gforth has unified code/data spaces. Assembler isn't likely to be
                   12201: portable anyway.}.
1.21      crook    12202: 
1.44      crook    12203: 
1.78      anton    12204: doc-assembler
                   12205: doc-init-asm
                   12206: doc-code
                   12207: doc-end-code
                   12208: doc-;code
                   12209: doc-flush-icache
1.44      crook    12210: 
1.21      crook    12211: 
1.78      anton    12212: If @code{flush-icache} does not work correctly, @code{code} words
                   12213: etc. will not work (reliably), either.
1.44      crook    12214: 
1.78      anton    12215: The typical usage of these @code{code} words can be shown most easily by
                   12216: analogy to the equivalent high-level defining words:
1.44      crook    12217: 
1.78      anton    12218: @example
                   12219: : foo                              code foo
                   12220:    <high-level Forth words>              <assembler>
                   12221: ;                                  end-code
                   12222:                                 
                   12223: : bar                              : bar
                   12224:    <high-level Forth words>           <high-level Forth words>
                   12225:    CREATE                             CREATE
                   12226:       <high-level Forth words>           <high-level Forth words>
                   12227:    DOES>                              ;code
                   12228:       <high-level Forth words>           <assembler>
                   12229: ;                                  end-code
                   12230: @end example
1.21      crook    12231: 
1.78      anton    12232: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44      crook    12233: 
1.78      anton    12234: @cindex registers of the inner interpreter
                   12235: In the assembly code you will want to refer to the inner interpreter's
                   12236: registers (e.g., the data stack pointer) and you may want to use other
                   12237: registers for temporary storage. Unfortunately, the register allocation
                   12238: is installation-dependent.
1.44      crook    12239: 
1.78      anton    12240: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100     anton    12241: (return stack pointer) may be in different places in @code{gforth} and
                   12242: @code{gforth-fast}, or different installations.  This means that you
                   12243: cannot write a @code{NEXT} routine that works reliably on both versions
                   12244: or different installations; so for doing @code{NEXT}, I recommend
                   12245: jumping to @code{' noop >code-address}, which contains nothing but a
                   12246: @code{NEXT}.
1.21      crook    12247: 
1.78      anton    12248: For general accesses to the inner interpreter's registers, the easiest
                   12249: solution is to use explicit register declarations (@pxref{Explicit Reg
                   12250: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
                   12251: all of the inner interpreter's registers: You have to compile Gforth
                   12252: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
                   12253: the appropriate declarations must be present in the @code{machine.h}
                   12254: file (see @code{mips.h} for an example; you can find a full list of all
                   12255: declarable register symbols with @code{grep register engine.c}). If you
                   12256: give explicit registers to all variables that are declared at the
                   12257: beginning of @code{engine()}, you should be able to use the other
                   12258: caller-saved registers for temporary storage. Alternatively, you can use
                   12259: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
                   12260: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
                   12261: reserve a register (however, this restriction on register allocation may
                   12262: slow Gforth significantly).
1.44      crook    12263: 
1.78      anton    12264: If this solution is not viable (e.g., because @code{gcc} does not allow
                   12265: you to explicitly declare all the registers you need), you have to find
                   12266: out by looking at the code where the inner interpreter's registers
                   12267: reside and which registers can be used for temporary storage. You can
                   12268: get an assembly listing of the engine's code with @code{make engine.s}.
1.44      crook    12269: 
1.78      anton    12270: In any case, it is good practice to abstract your assembly code from the
                   12271: actual register allocation. E.g., if the data stack pointer resides in
                   12272: register @code{$17}, create an alias for this register called @code{sp},
                   12273: and use that in your assembly code.
1.21      crook    12274: 
1.78      anton    12275: @cindex code words, portable
                   12276: Another option for implementing normal and defining words efficiently
                   12277: is to add the desired functionality to the source of Gforth. For normal
                   12278: words you just have to edit @file{primitives} (@pxref{Automatic
                   12279: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
                   12280: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
                   12281: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44      crook    12282: 
1.78      anton    12283: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
                   12284: @subsection Common Assembler
1.44      crook    12285: 
1.78      anton    12286: The assemblers in Gforth generally use a postfix syntax, i.e., the
                   12287: instruction name follows the operands.
1.21      crook    12288: 
1.78      anton    12289: The operands are passed in the usual order (the same that is used in the
                   12290: manual of the architecture).  Since they all are Forth words, they have
                   12291: to be separated by spaces; you can also use Forth words to compute the
                   12292: operands.
1.44      crook    12293: 
1.78      anton    12294: The instruction names usually end with a @code{,}.  This makes it easier
                   12295: to visually separate instructions if you put several of them on one
                   12296: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21      crook    12297: 
1.78      anton    12298: Registers are usually specified by number; e.g., (decimal) @code{11}
                   12299: specifies registers R11 and F11 on the Alpha architecture (which one,
                   12300: depends on the instruction).  The usual names are also available, e.g.,
                   12301: @code{s2} for R11 on Alpha.
1.21      crook    12302: 
1.78      anton    12303: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
                   12304: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
                   12305: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
                   12306: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
                   12307: conditions are specified in a way specific to each assembler.
1.1       anton    12308: 
1.78      anton    12309: Note that the register assignments of the Gforth engine can change
                   12310: between Gforth versions, or even between different compilations of the
                   12311: same Gforth version (e.g., if you use a different GCC version).  So if
                   12312: you want to refer to Gforth's registers (e.g., the stack pointer or
                   12313: TOS), I recommend defining your own words for refering to these
                   12314: registers, and using them later on; then you can easily adapt to a
                   12315: changed register assignment.  The stability of the register assignment
                   12316: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1       anton    12317: 
1.100     anton    12318: The most common use of these registers is to dispatch to the next word
                   12319: (the @code{next} routine).  A portable way to do this is to jump to
                   12320: @code{' noop >code-address} (of course, this is less efficient than
                   12321: integrating the @code{next} code and scheduling it well).
1.1       anton    12322: 
1.96      anton    12323: Another difference between Gforth version is that the top of stack is
                   12324: kept in memory in @code{gforth} and, on most platforms, in a register in
                   12325: @code{gforth-fast}.
                   12326: 
1.78      anton    12327: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
                   12328: @subsection Common Disassembler
1.127     anton    12329: @cindex disassembler, general
                   12330: @cindex gdb disassembler
1.1       anton    12331: 
1.78      anton    12332: You can disassemble a @code{code} word with @code{see}
                   12333: (@pxref{Debugging}).  You can disassemble a section of memory with
1.1       anton    12334: 
1.127     anton    12335: doc-discode
1.44      crook    12336: 
1.127     anton    12337: There are two kinds of disassembler for Gforth: The Forth disassembler
                   12338: (available on some CPUs) and the gdb disassembler (available on
                   12339: platforms with @command{gdb} and @command{mktemp}).  If both are
                   12340: available, the Forth disassembler is used by default.  If you prefer
                   12341: the gdb disassembler, say
                   12342: 
                   12343: @example
                   12344: ' disasm-gdb is discode
                   12345: @end example
                   12346: 
                   12347: If neither is available, @code{discode} performs @code{dump}.
                   12348: 
                   12349: The Forth disassembler generally produces output that can be fed into the
1.78      anton    12350: assembler (i.e., same syntax, etc.).  It also includes additional
                   12351: information in comments.  In particular, the address of the instruction
                   12352: is given in a comment before the instruction.
1.1       anton    12353: 
1.127     anton    12354: The gdb disassembler produces output in the same format as the gdb
                   12355: @code{disassemble} command (@pxref{Machine Code,,Source and machine
                   12356: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
                   12357: the 386 and AMD64 architectures).
                   12358: 
1.78      anton    12359: @code{See} may display more or less than the actual code of the word,
                   12360: because the recognition of the end of the code is unreliable.  You can
1.127     anton    12361: use @code{discode} if it did not display enough.  It may display more, if
1.78      anton    12362: the code word is not immediately followed by a named word.  If you have
1.116     anton    12363: something else there, you can follow the word with @code{align latest ,}
1.78      anton    12364: to ensure that the end is recognized.
1.21      crook    12365: 
1.78      anton    12366: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
                   12367: @subsection 386 Assembler
1.44      crook    12368: 
1.78      anton    12369: The 386 assembler included in Gforth was written by Bernd Paysan, it's
                   12370: available under GPL, and originally part of bigFORTH.
1.21      crook    12371: 
1.78      anton    12372: The 386 disassembler included in Gforth was written by Andrew McKewan
                   12373: and is in the public domain.
1.21      crook    12374: 
1.91      anton    12375: The disassembler displays code in an Intel-like prefix syntax.
1.21      crook    12376: 
1.78      anton    12377: The assembler uses a postfix syntax with reversed parameters.
1.1       anton    12378: 
1.78      anton    12379: The assembler includes all instruction of the Athlon, i.e. 486 core
                   12380: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
                   12381: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
                   12382: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1       anton    12383: 
1.78      anton    12384: There are several prefixes to switch between different operation sizes,
                   12385: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
                   12386: double-word accesses. Addressing modes can be switched with @code{.wa}
                   12387: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
                   12388: need a prefix for byte register names (@code{AL} et al).
1.1       anton    12389: 
1.78      anton    12390: For floating point operations, the prefixes are @code{.fs} (IEEE
                   12391: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
                   12392: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21      crook    12393: 
1.78      anton    12394: The MMX opcodes don't have size prefixes, they are spelled out like in
                   12395: the Intel assembler. Instead of move from and to memory, there are
                   12396: PLDQ/PLDD and PSTQ/PSTD.
1.21      crook    12397: 
1.78      anton    12398: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
                   12399: ax.  Immediate values are indicated by postfixing them with @code{#},
1.91      anton    12400: e.g., @code{3 #}.  Here are some examples of addressing modes in various
                   12401: syntaxes:
1.21      crook    12402: 
1.26      crook    12403: @example
1.91      anton    12404: Gforth          Intel (NASM)   AT&T (gas)      Name
                   12405: .w ax           ax             %ax             register (16 bit)
                   12406: ax              eax            %eax            register (32 bit)
                   12407: 3 #             offset 3       $3              immediate
                   12408: 1000 #)         byte ptr 1000  1000            displacement
                   12409: bx )            [ebx]          (%ebx)          base
                   12410: 100 di d)       100[edi]       100(%edi)       base+displacement
                   12411: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
                   12412: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
                   12413: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
                   12414: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
                   12415: @end example
                   12416: 
                   12417: You can use @code{L)} and @code{LI)} instead of @code{D)} and
                   12418: @code{DI)} to enforce 32-bit displacement fields (useful for
                   12419: later patching).
1.21      crook    12420: 
1.78      anton    12421: Some example of instructions are:
1.1       anton    12422: 
                   12423: @example
1.78      anton    12424: ax bx mov             \ move ebx,eax
                   12425: 3 # ax mov            \ mov eax,3
1.137     pazsan   12426: 100 di d) ax mov      \ mov eax,100[edi]
1.78      anton    12427: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
                   12428: .w ax bx mov          \ mov bx,ax
1.1       anton    12429: @end example
                   12430: 
1.78      anton    12431: The following forms are supported for binary instructions:
1.1       anton    12432: 
                   12433: @example
1.78      anton    12434: <reg> <reg> <inst>
                   12435: <n> # <reg> <inst>
                   12436: <mem> <reg> <inst>
                   12437: <reg> <mem> <inst>
1.136     pazsan   12438: <n> # <mem> <inst>
1.1       anton    12439: @end example
                   12440: 
1.136     pazsan   12441: The shift/rotate syntax is:
1.1       anton    12442: 
1.26      crook    12443: @example
1.78      anton    12444: <reg/mem> 1 # shl \ shortens to shift without immediate
                   12445: <reg/mem> 4 # shl
                   12446: <reg/mem> cl shl
1.26      crook    12447: @end example
1.1       anton    12448: 
1.78      anton    12449: Precede string instructions (@code{movs} etc.) with @code{.b} to get
                   12450: the byte version.
1.1       anton    12451: 
1.78      anton    12452: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
                   12453: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
                   12454: pc < >= <= >}. (Note that most of these words shadow some Forth words
                   12455: when @code{assembler} is in front of @code{forth} in the search path,
                   12456: e.g., in @code{code} words).  Currently the control structure words use
                   12457: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
                   12458: to shuffle them (you can also use @code{swap} etc.).
1.21      crook    12459: 
1.78      anton    12460: Here is an example of a @code{code} word (assumes that the stack pointer
                   12461: is in esi and the TOS is in ebx):
1.21      crook    12462: 
1.26      crook    12463: @example
1.78      anton    12464: code my+ ( n1 n2 -- n )
                   12465:     4 si D) bx add
                   12466:     4 # si add
                   12467:     Next
                   12468: end-code
1.26      crook    12469: @end example
1.21      crook    12470: 
1.161     anton    12471: 
1.78      anton    12472: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
                   12473: @subsection Alpha Assembler
1.21      crook    12474: 
1.78      anton    12475: The Alpha assembler and disassembler were originally written by Bernd
                   12476: Thallner.
1.26      crook    12477: 
1.78      anton    12478: The register names @code{a0}--@code{a5} are not available to avoid
                   12479: shadowing hex numbers.
1.2       jwilke   12480: 
1.78      anton    12481: Immediate forms of arithmetic instructions are distinguished by a
                   12482: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
                   12483: does not count as arithmetic instruction).
1.2       jwilke   12484: 
1.78      anton    12485: You have to specify all operands to an instruction, even those that
                   12486: other assemblers consider optional, e.g., the destination register for
                   12487: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2       jwilke   12488: 
1.78      anton    12489: You can specify conditions for @code{if,} by removing the first @code{b}
                   12490: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2       jwilke   12491: 
1.26      crook    12492: @example
1.78      anton    12493: 11 fgt if, \ if F11>0e
                   12494:   ...
                   12495: endif,
1.26      crook    12496: @end example
1.2       jwilke   12497: 
1.78      anton    12498: @code{fbgt,} gives @code{fgt}.  
                   12499: 
1.161     anton    12500: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78      anton    12501: @subsection MIPS assembler
1.2       jwilke   12502: 
1.78      anton    12503: The MIPS assembler was originally written by Christian Pirker.
1.2       jwilke   12504: 
1.78      anton    12505: Currently the assembler and disassembler only cover the MIPS-I
                   12506: architecture (R3000), and don't support FP instructions.
1.2       jwilke   12507: 
1.78      anton    12508: The register names @code{$a0}--@code{$a3} are not available to avoid
                   12509: shadowing hex numbers.
1.2       jwilke   12510: 
1.78      anton    12511: Because there is no way to distinguish registers from immediate values,
                   12512: you have to explicitly use the immediate forms of instructions, i.e.,
                   12513: @code{addiu,}, not just @code{addu,} (@command{as} does this
                   12514: implicitly).
1.2       jwilke   12515: 
1.78      anton    12516: If the architecture manual specifies several formats for the instruction
                   12517: (e.g., for @code{jalr,}), you usually have to use the one with more
                   12518: arguments (i.e., two for @code{jalr,}).  When in doubt, see
                   12519: @code{arch/mips/testasm.fs} for an example of correct use.
1.2       jwilke   12520: 
1.78      anton    12521: Branches and jumps in the MIPS architecture have a delay slot.  You have
                   12522: to fill it yourself (the simplest way is to use @code{nop,}), the
                   12523: assembler does not do it for you (unlike @command{as}).  Even
                   12524: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
                   12525: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
                   12526: and @code{then,} just specify branch targets, they are not affected.
1.2       jwilke   12527: 
1.78      anton    12528: Note that you must not put branches, jumps, or @code{li,} into the delay
                   12529: slot: @code{li,} may expand to several instructions, and control flow
                   12530: instructions may not be put into the branch delay slot in any case.
1.2       jwilke   12531: 
1.78      anton    12532: For branches the argument specifying the target is a relative address;
                   12533: You have to add the address of the delay slot to get the absolute
                   12534: address.
1.1       anton    12535: 
1.78      anton    12536: The MIPS architecture also has load delay slots and restrictions on
                   12537: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
                   12538: yourself to satisfy these restrictions, the assembler does not do it for
                   12539: you.
1.1       anton    12540: 
1.78      anton    12541: You can specify the conditions for @code{if,} etc. by taking a
                   12542: conditional branch and leaving away the @code{b} at the start and the
                   12543: @code{,} at the end.  E.g.,
1.1       anton    12544: 
1.26      crook    12545: @example
1.78      anton    12546: 4 5 eq if,
                   12547:   ... \ do something if $4 equals $5
                   12548: then,
1.26      crook    12549: @end example
1.1       anton    12550: 
1.161     anton    12551: 
                   12552: @node PowerPC assembler, Other assemblers, MIPS assembler, Assembler and Code Words
                   12553: @subsection PowerPC assembler
                   12554: 
1.162     anton    12555: The PowerPC assembler and disassembler were contributed by Michal
1.161     anton    12556: Revucky.
                   12557: 
1.162     anton    12558: This assembler does not follow the convention of ending mnemonic names
                   12559: with a ``,'', so some mnemonic names shadow regular Forth words (in
                   12560: particular: @code{and or xor fabs}); so if you want to use the Forth
                   12561: words, you have to make them visible first, e.g., with @code{also
                   12562: forth}.
                   12563: 
1.161     anton    12564: Registers are referred to by their number, e.g., @code{9} means the
                   12565: integer register 9 or the FP register 9 (depending on the
                   12566: instruction).
                   12567: 
                   12568: Because there is no way to distinguish registers from immediate values,
                   12569: you have to explicitly use the immediate forms of instructions, i.e.,
1.162     anton    12570: @code{addi,}, not just @code{add,}.
1.161     anton    12571: 
1.162     anton    12572: The assembler and disassembler usually support the most general form
1.161     anton    12573: of an instruction, but usually not the shorter forms (especially for
                   12574: branches).
                   12575: 
                   12576: 
                   12577: 
                   12578: @node Other assemblers,  , PowerPC assembler, Assembler and Code Words
1.78      anton    12579: @subsection Other assemblers
                   12580: 
                   12581: If you want to contribute another assembler/disassembler, please contact
1.103     anton    12582: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
                   12583: an assembler already.  If you are writing them from scratch, please use
                   12584: a similar syntax style as the one we use (i.e., postfix, commas at the
                   12585: end of the instruction names, @pxref{Common Assembler}); make the output
                   12586: of the disassembler be valid input for the assembler, and keep the style
1.78      anton    12587: similar to the style we used.
                   12588: 
                   12589: Hints on implementation: The most important part is to have a good test
                   12590: suite that contains all instructions.  Once you have that, the rest is
                   12591: easy.  For actual coding you can take a look at
                   12592: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
                   12593: the assembler and disassembler, avoiding redundancy and some potential
                   12594: bugs.  You can also look at that file (and @pxref{Advanced does> usage
                   12595: example}) to get ideas how to factor a disassembler.
                   12596: 
                   12597: Start with the disassembler, because it's easier to reuse data from the
                   12598: disassembler for the assembler than the other way round.
1.1       anton    12599: 
1.78      anton    12600: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
                   12601: how simple it can be.
1.1       anton    12602: 
1.161     anton    12603: 
                   12604: 
                   12605: 
1.78      anton    12606: @c -------------------------------------------------------------
                   12607: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
                   12608: @section Threading Words
                   12609: @cindex threading words
1.1       anton    12610: 
1.78      anton    12611: @cindex code address
                   12612: These words provide access to code addresses and other threading stuff
                   12613: in Gforth (and, possibly, other interpretive Forths). It more or less
                   12614: abstracts away the differences between direct and indirect threading
                   12615: (and, for direct threading, the machine dependences). However, at
                   12616: present this wordset is still incomplete. It is also pretty low-level;
                   12617: some day it will hopefully be made unnecessary by an internals wordset
                   12618: that abstracts implementation details away completely.
1.1       anton    12619: 
1.78      anton    12620: The terminology used here stems from indirect threaded Forth systems; in
                   12621: such a system, the XT of a word is represented by the CFA (code field
                   12622: address) of a word; the CFA points to a cell that contains the code
                   12623: address.  The code address is the address of some machine code that
                   12624: performs the run-time action of invoking the word (e.g., the
                   12625: @code{dovar:} routine pushes the address of the body of the word (a
                   12626: variable) on the stack
                   12627: ).
1.1       anton    12628: 
1.78      anton    12629: @cindex code address
                   12630: @cindex code field address
                   12631: In an indirect threaded Forth, you can get the code address of @i{name}
                   12632: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
                   12633: >code-address}, independent of the threading method.
1.1       anton    12634: 
1.78      anton    12635: doc-threading-method
                   12636: doc->code-address
                   12637: doc-code-address!
1.1       anton    12638: 
1.78      anton    12639: @cindex @code{does>}-handler
                   12640: @cindex @code{does>}-code
                   12641: For a word defined with @code{DOES>}, the code address usually points to
                   12642: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
                   12643: routine (in Gforth on some platforms, it can also point to the dodoes
                   12644: routine itself).  What you are typically interested in, though, is
                   12645: whether a word is a @code{DOES>}-defined word, and what Forth code it
                   12646: executes; @code{>does-code} tells you that.
1.1       anton    12647: 
1.78      anton    12648: doc->does-code
1.1       anton    12649: 
1.78      anton    12650: To create a @code{DOES>}-defined word with the following basic words,
                   12651: you have to set up a @code{DOES>}-handler with @code{does-handler!};
                   12652: @code{/does-handler} aus behind you have to place your executable Forth
                   12653: code.  Finally you have to create a word and modify its behaviour with
                   12654: @code{does-handler!}.
1.1       anton    12655: 
1.78      anton    12656: doc-does-code!
                   12657: doc-does-handler!
                   12658: doc-/does-handler
1.1       anton    12659: 
1.78      anton    12660: The code addresses produced by various defining words are produced by
                   12661: the following words:
1.1       anton    12662: 
1.78      anton    12663: doc-docol:
                   12664: doc-docon:
                   12665: doc-dovar:
                   12666: doc-douser:
                   12667: doc-dodefer:
                   12668: doc-dofield:
1.1       anton    12669: 
1.99      anton    12670: @cindex definer
                   12671: The following two words generalize @code{>code-address},
                   12672: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
                   12673: 
                   12674: doc->definer
                   12675: doc-definer!
                   12676: 
1.26      crook    12677: @c -------------------------------------------------------------
1.78      anton    12678: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21      crook    12679: @section Passing Commands to the Operating System
                   12680: @cindex operating system - passing commands
                   12681: @cindex shell commands
                   12682: 
                   12683: Gforth allows you to pass an arbitrary string to the host operating
                   12684: system shell (if such a thing exists) for execution.
                   12685: 
                   12686: doc-sh
                   12687: doc-system
                   12688: doc-$?
1.23      crook    12689: doc-getenv
1.44      crook    12690: 
1.26      crook    12691: @c -------------------------------------------------------------
1.47      crook    12692: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
                   12693: @section Keeping track of Time
                   12694: @cindex time-related words
                   12695: 
                   12696: doc-ms
                   12697: doc-time&date
1.79      anton    12698: doc-utime
                   12699: doc-cputime
1.47      crook    12700: 
                   12701: 
                   12702: @c -------------------------------------------------------------
                   12703: @node Miscellaneous Words,  , Keeping track of Time, Words
1.21      crook    12704: @section Miscellaneous Words
                   12705: @cindex miscellaneous words
                   12706: 
1.29      crook    12707: @comment TODO find homes for these
                   12708: 
1.26      crook    12709: These section lists the ANS Forth words that are not documented
1.21      crook    12710: elsewhere in this manual. Ultimately, they all need proper homes.
                   12711: 
1.68      anton    12712: doc-quit
1.44      crook    12713: 
1.26      crook    12714: The following ANS Forth words are not currently supported by Gforth 
1.27      crook    12715: (@pxref{ANS conformance}):
1.21      crook    12716: 
                   12717: @code{EDITOR} 
                   12718: @code{EMIT?} 
                   12719: @code{FORGET} 
                   12720: 
1.24      anton    12721: @c ******************************************************************
                   12722: @node Error messages, Tools, Words, Top
                   12723: @chapter Error messages
                   12724: @cindex error messages
                   12725: @cindex backtrace
                   12726: 
                   12727: A typical Gforth error message looks like this:
                   12728: 
                   12729: @example
1.86      anton    12730: in file included from \evaluated string/:-1
1.24      anton    12731: in file included from ./yyy.fs:1
                   12732: ./xxx.fs:4: Invalid memory address
1.134     anton    12733: >>>bar<<<
1.79      anton    12734: Backtrace:
1.25      anton    12735: $400E664C @@
                   12736: $400E6664 foo
1.24      anton    12737: @end example
                   12738: 
                   12739: The message identifying the error is @code{Invalid memory address}.  The
                   12740: error happened when text-interpreting line 4 of the file
                   12741: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
                   12742: word on the line where the error happened, is pointed out (with
1.134     anton    12743: @code{>>>} and @code{<<<}).
1.24      anton    12744: 
                   12745: The file containing the error was included in line 1 of @file{./yyy.fs},
                   12746: and @file{yyy.fs} was included from a non-file (in this case, by giving
                   12747: @file{yyy.fs} as command-line parameter to Gforth).
                   12748: 
                   12749: At the end of the error message you find a return stack dump that can be
                   12750: interpreted as a backtrace (possibly empty). On top you find the top of
                   12751: the return stack when the @code{throw} happened, and at the bottom you
                   12752: find the return stack entry just above the return stack of the topmost
                   12753: text interpreter.
                   12754: 
                   12755: To the right of most return stack entries you see a guess for the word
                   12756: that pushed that return stack entry as its return address. This gives a
                   12757: backtrace. In our case we see that @code{bar} called @code{foo}, and
                   12758: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
                   12759: address} exception).
                   12760: 
                   12761: Note that the backtrace is not perfect: We don't know which return stack
                   12762: entries are return addresses (so we may get false positives); and in
                   12763: some cases (e.g., for @code{abort"}) we cannot determine from the return
                   12764: address the word that pushed the return address, so for some return
                   12765: addresses you see no names in the return stack dump.
1.25      anton    12766: 
                   12767: @cindex @code{catch} and backtraces
                   12768: The return stack dump represents the return stack at the time when a
                   12769: specific @code{throw} was executed.  In programs that make use of
                   12770: @code{catch}, it is not necessarily clear which @code{throw} should be
                   12771: used for the return stack dump (e.g., consider one @code{throw} that
                   12772: indicates an error, which is caught, and during recovery another error
1.160     anton    12773: happens; which @code{throw} should be used for the stack dump?).
                   12774: Gforth presents the return stack dump for the first @code{throw} after
                   12775: the last executed (not returned-to) @code{catch} or @code{nothrow};
                   12776: this works well in the usual case. To get the right backtrace, you
                   12777: usually want to insert @code{nothrow} or @code{['] false catch drop}
                   12778: after a @code{catch} if the error is not rethrown.
1.25      anton    12779: 
                   12780: @cindex @code{gforth-fast} and backtraces
                   12781: @cindex @code{gforth-fast}, difference from @code{gforth}
                   12782: @cindex backtraces with @code{gforth-fast}
                   12783: @cindex return stack dump with @code{gforth-fast}
1.79      anton    12784: @code{Gforth} is able to do a return stack dump for throws generated
1.25      anton    12785: from primitives (e.g., invalid memory address, stack empty etc.);
                   12786: @code{gforth-fast} is only able to do a return stack dump from a
1.96      anton    12787: directly called @code{throw} (including @code{abort} etc.).  Given an
1.30      anton    12788: exception caused by a primitive in @code{gforth-fast}, you will
                   12789: typically see no return stack dump at all; however, if the exception is
                   12790: caught by @code{catch} (e.g., for restoring some state), and then
                   12791: @code{throw}n again, the return stack dump will be for the first such
                   12792: @code{throw}.
1.2       jwilke   12793: 
1.5       anton    12794: @c ******************************************************************
1.24      anton    12795: @node Tools, ANS conformance, Error messages, Top
1.1       anton    12796: @chapter Tools
                   12797: 
                   12798: @menu
                   12799: * ANS Report::                  Report the words used, sorted by wordset.
1.127     anton    12800: * Stack depth changes::         Where does this stack item come from?
1.1       anton    12801: @end menu
                   12802: 
                   12803: See also @ref{Emacs and Gforth}.
                   12804: 
1.126     pazsan   12805: @node ANS Report, Stack depth changes, Tools, Tools
1.1       anton    12806: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   12807: @cindex @file{ans-report.fs}
                   12808: @cindex report the words used in your program
                   12809: @cindex words used in your program
                   12810: 
                   12811: If you want to label a Forth program as ANS Forth Program, you must
                   12812: document which wordsets the program uses; for extension wordsets, it is
                   12813: helpful to list the words the program requires from these wordsets
                   12814: (because Forth systems are allowed to provide only some words of them).
                   12815: 
                   12816: The @file{ans-report.fs} tool makes it easy for you to determine which
                   12817: words from which wordset and which non-ANS words your application
                   12818: uses. You simply have to include @file{ans-report.fs} before loading the
                   12819: program you want to check. After loading your program, you can get the
                   12820: report with @code{print-ans-report}. A typical use is to run this as
                   12821: batch job like this:
                   12822: @example
                   12823: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   12824: @end example
                   12825: 
                   12826: The output looks like this (for @file{compat/control.fs}):
                   12827: @example
                   12828: The program uses the following words
                   12829: from CORE :
                   12830: : POSTPONE THEN ; immediate ?dup IF 0= 
                   12831: from BLOCK-EXT :
                   12832: \ 
                   12833: from FILE :
                   12834: ( 
                   12835: @end example
                   12836: 
                   12837: @subsection Caveats
                   12838: 
                   12839: Note that @file{ans-report.fs} just checks which words are used, not whether
                   12840: they are used in an ANS Forth conforming way!
                   12841: 
                   12842: Some words are defined in several wordsets in the
                   12843: standard. @file{ans-report.fs} reports them for only one of the
                   12844: wordsets, and not necessarily the one you expect. It depends on usage
                   12845: which wordset is the right one to specify. E.g., if you only use the
                   12846: compilation semantics of @code{S"}, it is a Core word; if you also use
                   12847: its interpretation semantics, it is a File word.
1.124     anton    12848: 
                   12849: 
1.127     anton    12850: @node Stack depth changes,  , ANS Report, Tools
1.124     anton    12851: @section Stack depth changes during interpretation
                   12852: @cindex @file{depth-changes.fs}
                   12853: @cindex depth changes during interpretation
                   12854: @cindex stack depth changes during interpretation
                   12855: @cindex items on the stack after interpretation
                   12856: 
                   12857: Sometimes you notice that, after loading a file, there are items left
                   12858: on the stack.  The tool @file{depth-changes.fs} helps you find out
                   12859: quickly where in the file these stack items are coming from.
                   12860: 
                   12861: The simplest way of using @file{depth-changes.fs} is to include it
                   12862: before the file(s) you want to check, e.g.:
                   12863: 
                   12864: @example
                   12865: gforth depth-changes.fs my-file.fs
                   12866: @end example
                   12867: 
                   12868: This will compare the stack depths of the data and FP stack at every
                   12869: empty line (in interpretation state) against these depths at the last
                   12870: empty line (in interpretation state).  If the depths are not equal,
                   12871: the position in the file and the stack contents are printed with
                   12872: @code{~~} (@pxref{Debugging}).  This indicates that a stack depth
                   12873: change has occured in the paragraph of non-empty lines before the
                   12874: indicated line.  It is a good idea to leave an empty line at the end
                   12875: of the file, so the last paragraph is checked, too.
                   12876: 
                   12877: Checking only at empty lines usually works well, but sometimes you
                   12878: have big blocks of non-empty lines (e.g., when building a big table),
                   12879: and you want to know where in this block the stack depth changed.  You
                   12880: can check all interpreted lines with
                   12881: 
                   12882: @example
                   12883: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
                   12884: @end example
                   12885: 
                   12886: This checks the stack depth at every end-of-line.  So the depth change
                   12887: occured in the line reported by the @code{~~} (not in the line
                   12888: before).
                   12889: 
                   12890: Note that, while this offers better accuracy in indicating where the
                   12891: stack depth changes, it will often report many intentional stack depth
                   12892: changes (e.g., when an interpreted computation stretches across
                   12893: several lines).  You can suppress the checking of some lines by
                   12894: putting backslashes at the end of these lines (not followed by white
                   12895: space), and using
                   12896: 
                   12897: @example
                   12898: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
                   12899: @end example
1.1       anton    12900: 
                   12901: @c ******************************************************************
1.65      anton    12902: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1       anton    12903: @chapter ANS conformance
                   12904: @cindex ANS conformance of Gforth
                   12905: 
                   12906: To the best of our knowledge, Gforth is an
                   12907: 
                   12908: ANS Forth System
                   12909: @itemize @bullet
                   12910: @item providing the Core Extensions word set
                   12911: @item providing the Block word set
                   12912: @item providing the Block Extensions word set
                   12913: @item providing the Double-Number word set
                   12914: @item providing the Double-Number Extensions word set
                   12915: @item providing the Exception word set
                   12916: @item providing the Exception Extensions word set
                   12917: @item providing the Facility word set
1.40      anton    12918: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1       anton    12919: @item providing the File Access word set
                   12920: @item providing the File Access Extensions word set
                   12921: @item providing the Floating-Point word set
                   12922: @item providing the Floating-Point Extensions word set
                   12923: @item providing the Locals word set
                   12924: @item providing the Locals Extensions word set
                   12925: @item providing the Memory-Allocation word set
                   12926: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   12927: @item providing the Programming-Tools word set
                   12928: @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
                   12929: @item providing the Search-Order word set
                   12930: @item providing the Search-Order Extensions word set
                   12931: @item providing the String word set
                   12932: @item providing the String Extensions word set (another easy one)
                   12933: @end itemize
                   12934: 
1.118     anton    12935: Gforth has the following environmental restrictions:
                   12936: 
                   12937: @cindex environmental restrictions
                   12938: @itemize @bullet
                   12939: @item
                   12940: While processing the OS command line, if an exception is not caught,
                   12941: Gforth exits with a non-zero exit code instyead of performing QUIT.
                   12942: 
                   12943: @item
                   12944: When an @code{throw} is performed after a @code{query}, Gforth does not
                   12945: allways restore the input source specification in effect at the
                   12946: corresponding catch.
                   12947: 
                   12948: @end itemize
                   12949: 
                   12950: 
1.1       anton    12951: @cindex system documentation
                   12952: In addition, ANS Forth systems are required to document certain
                   12953: implementation choices. This chapter tries to meet these
                   12954: requirements. In many cases it gives a way to ask the system for the
                   12955: information instead of providing the information directly, in
                   12956: particular, if the information depends on the processor, the operating
                   12957: system or the installation options chosen, or if they are likely to
                   12958: change during the maintenance of Gforth.
                   12959: 
                   12960: @comment The framework for the rest has been taken from pfe.
                   12961: 
                   12962: @menu
                   12963: * The Core Words::              
                   12964: * The optional Block word set::  
                   12965: * The optional Double Number word set::  
                   12966: * The optional Exception word set::  
                   12967: * The optional Facility word set::  
                   12968: * The optional File-Access word set::  
                   12969: * The optional Floating-Point word set::  
                   12970: * The optional Locals word set::  
                   12971: * The optional Memory-Allocation word set::  
                   12972: * The optional Programming-Tools word set::  
                   12973: * The optional Search-Order word set::  
                   12974: @end menu
                   12975: 
                   12976: 
                   12977: @c =====================================================================
                   12978: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   12979: @comment  node-name,  next,  previous,  up
                   12980: @section The Core Words
                   12981: @c =====================================================================
                   12982: @cindex core words, system documentation
                   12983: @cindex system documentation, core words
                   12984: 
                   12985: @menu
                   12986: * core-idef::                   Implementation Defined Options                   
                   12987: * core-ambcond::                Ambiguous Conditions                
                   12988: * core-other::                  Other System Documentation                  
                   12989: @end menu
                   12990: 
                   12991: @c ---------------------------------------------------------------------
                   12992: @node core-idef, core-ambcond, The Core Words, The Core Words
                   12993: @subsection Implementation Defined Options
                   12994: @c ---------------------------------------------------------------------
                   12995: @cindex core words, implementation-defined options
                   12996: @cindex implementation-defined options, core words
                   12997: 
                   12998: 
                   12999: @table @i
                   13000: @item (Cell) aligned addresses:
                   13001: @cindex cell-aligned addresses
                   13002: @cindex aligned addresses
                   13003: processor-dependent. Gforth's alignment words perform natural alignment
                   13004: (e.g., an address aligned for a datum of size 8 is divisible by
                   13005: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   13006: 
                   13007: @item @code{EMIT} and non-graphic characters:
                   13008: @cindex @code{EMIT} and non-graphic characters
                   13009: @cindex non-graphic characters and @code{EMIT}
                   13010: The character is output using the C library function (actually, macro)
                   13011: @code{putc}.
                   13012: 
                   13013: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   13014: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   13015: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   13016: @cindex @code{ACCEPT}, editing
                   13017: @cindex @code{EXPECT}, editing
                   13018: This is modeled on the GNU readline library (@pxref{Readline
                   13019: Interaction, , Command Line Editing, readline, The GNU Readline
                   13020: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   13021: producing a full word completion every time you type it (instead of
1.28      crook    13022: producing the common prefix of all completions). @xref{Command-line editing}.
1.1       anton    13023: 
                   13024: @item character set:
                   13025: @cindex character set
                   13026: The character set of your computer and display device. Gforth is
                   13027: 8-bit-clean (but some other component in your system may make trouble).
                   13028: 
                   13029: @item Character-aligned address requirements:
                   13030: @cindex character-aligned address requirements
                   13031: installation-dependent. Currently a character is represented by a C
                   13032: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   13033: (Comments on that requested).
                   13034: 
                   13035: @item character-set extensions and matching of names:
                   13036: @cindex character-set extensions and matching of names
1.26      crook    13037: @cindex case-sensitivity for name lookup
                   13038: @cindex name lookup, case-sensitivity
                   13039: @cindex locale and case-sensitivity
1.21      crook    13040: Any character except the ASCII NUL character can be used in a
1.1       anton    13041: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47      crook    13042: matching is performed using the C library function @code{strncasecmp}, whose
1.1       anton    13043: function is probably influenced by the locale. E.g., the @code{C} locale
                   13044: does not know about accents and umlauts, so they are matched
                   13045: case-sensitively in that locale. For portability reasons it is best to
                   13046: write programs such that they work in the @code{C} locale. Then one can
                   13047: use libraries written by a Polish programmer (who might use words
                   13048: containing ISO Latin-2 encoded characters) and by a French programmer
                   13049: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   13050: funny results for some of the words (which ones, depends on the font you
                   13051: are using)). Also, the locale you prefer may not be available in other
                   13052: operating systems. Hopefully, Unicode will solve these problems one day.
                   13053: 
                   13054: @item conditions under which control characters match a space delimiter:
                   13055: @cindex space delimiters
                   13056: @cindex control characters as delimiters
1.117     anton    13057: If @code{word} is called with the space character as a delimiter, all
1.1       anton    13058: white-space characters (as identified by the C macro @code{isspace()})
1.117     anton    13059: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138     anton    13060: delimiters.  @code{Parse-name}, which is used by the outer
1.1       anton    13061: interpreter (aka text interpreter) by default, treats all white-space
                   13062: characters as delimiters.
                   13063: 
1.26      crook    13064: @item format of the control-flow stack:
                   13065: @cindex control-flow stack, format
                   13066: The data stack is used as control-flow stack. The size of a control-flow
1.1       anton    13067: stack item in cells is given by the constant @code{cs-item-size}. At the
                   13068: time of this writing, an item consists of a (pointer to a) locals list
                   13069: (third), an address in the code (second), and a tag for identifying the
                   13070: item (TOS). The following tags are used: @code{defstart},
                   13071: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   13072: @code{scopestart}.
                   13073: 
                   13074: @item conversion of digits > 35
                   13075: @cindex digits > 35
                   13076: The characters @code{[\]^_'} are the digits with the decimal value
                   13077: 36@minus{}41. There is no way to input many of the larger digits.
                   13078: 
                   13079: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   13080: @cindex @code{EXPECT}, display after end of input
                   13081: @cindex @code{ACCEPT}, display after end of input
                   13082: The cursor is moved to the end of the entered string. If the input is
                   13083: terminated using the @kbd{Return} key, a space is typed.
                   13084: 
                   13085: @item exception abort sequence of @code{ABORT"}:
                   13086: @cindex exception abort sequence of @code{ABORT"}
                   13087: @cindex @code{ABORT"}, exception abort sequence
                   13088: The error string is stored into the variable @code{"error} and a
                   13089: @code{-2 throw} is performed.
                   13090: 
                   13091: @item input line terminator:
                   13092: @cindex input line terminator
                   13093: @cindex line terminator on input
1.26      crook    13094: @cindex newline character on input
1.1       anton    13095: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   13096: lines. One of these characters is typically produced when you type the
                   13097: @kbd{Enter} or @kbd{Return} key.
                   13098: 
                   13099: @item maximum size of a counted string:
                   13100: @cindex maximum size of a counted string
                   13101: @cindex counted string, maximum size
                   13102: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79      anton    13103: on all platforms, but this may change.
1.1       anton    13104: 
                   13105: @item maximum size of a parsed string:
                   13106: @cindex maximum size of a parsed string
                   13107: @cindex parsed string, maximum size
                   13108: Given by the constant @code{/line}. Currently 255 characters.
                   13109: 
                   13110: @item maximum size of a definition name, in characters:
                   13111: @cindex maximum size of a definition name, in characters
                   13112: @cindex name, maximum length
1.113     anton    13113: MAXU/8
1.1       anton    13114: 
                   13115: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   13116: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   13117: @cindex @code{ENVIRONMENT?} string length, maximum
1.113     anton    13118: MAXU/8
1.1       anton    13119: 
                   13120: @item method of selecting the user input device:
                   13121: @cindex user input device, method of selecting
                   13122: The user input device is the standard input. There is currently no way to
                   13123: change it from within Gforth. However, the input can typically be
                   13124: redirected in the command line that starts Gforth.
                   13125: 
                   13126: @item method of selecting the user output device:
                   13127: @cindex user output device, method of selecting
                   13128: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    13129: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   13130: output when the user output device is a terminal, otherwise the output
                   13131: is buffered.
1.1       anton    13132: 
                   13133: @item methods of dictionary compilation:
                   13134: What are we expected to document here?
                   13135: 
                   13136: @item number of bits in one address unit:
                   13137: @cindex number of bits in one address unit
                   13138: @cindex address unit, size in bits
                   13139: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79      anton    13140: platforms.
1.1       anton    13141: 
                   13142: @item number representation and arithmetic:
                   13143: @cindex number representation and arithmetic
1.79      anton    13144: Processor-dependent. Binary two's complement on all current platforms.
1.1       anton    13145: 
                   13146: @item ranges for integer types:
                   13147: @cindex ranges for integer types
                   13148: @cindex integer types, ranges
                   13149: Installation-dependent. Make environmental queries for @code{MAX-N},
                   13150: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   13151: unsigned (and positive) types is 0. The lower bound for signed types on
                   13152: two's complement and one's complement machines machines can be computed
                   13153: by adding 1 to the upper bound.
                   13154: 
                   13155: @item read-only data space regions:
                   13156: @cindex read-only data space regions
                   13157: @cindex data-space, read-only regions
                   13158: The whole Forth data space is writable.
                   13159: 
                   13160: @item size of buffer at @code{WORD}:
                   13161: @cindex size of buffer at @code{WORD}
                   13162: @cindex @code{WORD} buffer size
                   13163: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   13164: shared with the pictured numeric output string. If overwriting
                   13165: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   13166: space, although only as much can be sensibly used as fits in a counted
                   13167: string.
                   13168: 
                   13169: @item size of one cell in address units:
                   13170: @cindex cell size
                   13171: @code{1 cells .}.
                   13172: 
                   13173: @item size of one character in address units:
                   13174: @cindex char size
1.79      anton    13175: @code{1 chars .}. 1 on all current platforms.
1.1       anton    13176: 
                   13177: @item size of the keyboard terminal buffer:
                   13178: @cindex size of the keyboard terminal buffer
                   13179: @cindex terminal buffer, size
                   13180: Varies. You can determine the size at a specific time using @code{lp@@
                   13181: tib - .}. It is shared with the locals stack and TIBs of files that
                   13182: include the current file. You can change the amount of space for TIBs
                   13183: and locals stack at Gforth startup with the command line option
                   13184: @code{-l}.
                   13185: 
                   13186: @item size of the pictured numeric output buffer:
                   13187: @cindex size of the pictured numeric output buffer
                   13188: @cindex pictured numeric output buffer, size
                   13189: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   13190: shared with @code{WORD}.
                   13191: 
                   13192: @item size of the scratch area returned by @code{PAD}:
                   13193: @cindex size of the scratch area returned by @code{PAD}
                   13194: @cindex @code{PAD} size
                   13195: The remainder of dictionary space. @code{unused pad here - - .}.
                   13196: 
                   13197: @item system case-sensitivity characteristics:
                   13198: @cindex case-sensitivity characteristics
1.26      crook    13199: Dictionary searches are case-insensitive (except in
1.1       anton    13200: @code{TABLE}s). However, as explained above under @i{character-set
                   13201: extensions}, the matching for non-ASCII characters is determined by the
                   13202: locale you are using. In the default @code{C} locale all non-ASCII
                   13203: characters are matched case-sensitively.
                   13204: 
                   13205: @item system prompt:
                   13206: @cindex system prompt
                   13207: @cindex prompt
                   13208: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   13209: 
                   13210: @item division rounding:
                   13211: @cindex division rounding
1.166     anton    13212: The ordinary division words @code{/ mod /mod */ */mod} perform floored
                   13213: division (with the default installation of Gforth).  You can check
                   13214: this with @code{s" floored" environment? drop .}.  If you write
                   13215: programs that need a specific division rounding, best use
                   13216: @code{fm/mod} or @code{sm/rem} for portability.
1.1       anton    13217: 
                   13218: @item values of @code{STATE} when true:
                   13219: @cindex @code{STATE} values
                   13220: -1.
                   13221: 
                   13222: @item values returned after arithmetic overflow:
                   13223: On two's complement machines, arithmetic is performed modulo
                   13224: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.164     anton    13225: arithmetic (with appropriate mapping for signed types). Division by
                   13226: zero typically results in a @code{-55 throw} (Floating-point
                   13227: unidentified fault) or @code{-10 throw} (divide by zero).  Integer
1.166     anton    13228: division overflow can result in these throws, or in @code{-11 throw};
                   13229: in @code{gforth-fast} division overflow and divide by zero may also
                   13230: result in returning bogus results without producing an exception.
1.1       anton    13231: 
                   13232: @item whether the current definition can be found after @t{DOES>}:
                   13233: @cindex @t{DOES>}, visibility of current definition
                   13234: No.
                   13235: 
                   13236: @end table
                   13237: 
                   13238: @c ---------------------------------------------------------------------
                   13239: @node core-ambcond, core-other, core-idef, The Core Words
                   13240: @subsection Ambiguous conditions
                   13241: @c ---------------------------------------------------------------------
                   13242: @cindex core words, ambiguous conditions
                   13243: @cindex ambiguous conditions, core words
                   13244: 
                   13245: @table @i
                   13246: 
                   13247: @item a name is neither a word nor a number:
                   13248: @cindex name not found
1.26      crook    13249: @cindex undefined word
1.80      anton    13250: @code{-13 throw} (Undefined word).
1.1       anton    13251: 
                   13252: @item a definition name exceeds the maximum length allowed:
1.26      crook    13253: @cindex word name too long
1.1       anton    13254: @code{-19 throw} (Word name too long)
                   13255: 
                   13256: @item addressing a region not inside the various data spaces of the forth system:
                   13257: @cindex Invalid memory address
1.32      anton    13258: The stacks, code space and header space are accessible. Machine code space is
1.1       anton    13259: typically readable. Accessing other addresses gives results dependent on
                   13260: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   13261: address).
                   13262: 
                   13263: @item argument type incompatible with parameter:
1.26      crook    13264: @cindex argument type mismatch
1.1       anton    13265: This is usually not caught. Some words perform checks, e.g., the control
                   13266: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   13267: mismatch).
                   13268: 
                   13269: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   13270: @cindex Interpreting a compile-only word, for @code{'} etc.
                   13271: @cindex execution token of words with undefined execution semantics
                   13272: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   13273: get an execution token for @code{compile-only-error} (which performs a
                   13274: @code{-14 throw} when executed).
                   13275: 
                   13276: @item dividing by zero:
                   13277: @cindex dividing by zero
                   13278: @cindex floating point unidentified fault, integer division
1.80      anton    13279: On some platforms, this produces a @code{-10 throw} (Division by
1.24      anton    13280: zero); on other systems, this typically results in a @code{-55 throw}
                   13281: (Floating-point unidentified fault).
1.1       anton    13282: 
                   13283: @item insufficient data stack or return stack space:
                   13284: @cindex insufficient data stack or return stack space
                   13285: @cindex stack overflow
1.26      crook    13286: @cindex address alignment exception, stack overflow
1.1       anton    13287: @cindex Invalid memory address, stack overflow
                   13288: Depending on the operating system, the installation, and the invocation
                   13289: of Gforth, this is either checked by the memory management hardware, or
1.24      anton    13290: it is not checked. If it is checked, you typically get a @code{-3 throw}
                   13291: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
                   13292: throw} (Invalid memory address) (depending on the platform and how you
                   13293: achieved the overflow) as soon as the overflow happens. If it is not
                   13294: checked, overflows typically result in mysterious illegal memory
                   13295: accesses, producing @code{-9 throw} (Invalid memory address) or
                   13296: @code{-23 throw} (Address alignment exception); they might also destroy
                   13297: the internal data structure of @code{ALLOCATE} and friends, resulting in
                   13298: various errors in these words.
1.1       anton    13299: 
                   13300: @item insufficient space for loop control parameters:
                   13301: @cindex insufficient space for loop control parameters
1.80      anton    13302: Like other return stack overflows.
1.1       anton    13303: 
                   13304: @item insufficient space in the dictionary:
                   13305: @cindex insufficient space in the dictionary
                   13306: @cindex dictionary overflow
1.12      anton    13307: If you try to allot (either directly with @code{allot}, or indirectly
                   13308: with @code{,}, @code{create} etc.) more memory than available in the
                   13309: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   13310: to access memory beyond the end of the dictionary, the results are
                   13311: similar to stack overflows.
1.1       anton    13312: 
                   13313: @item interpreting a word with undefined interpretation semantics:
                   13314: @cindex interpreting a word with undefined interpretation semantics
                   13315: @cindex Interpreting a compile-only word
                   13316: For some words, we have defined interpretation semantics. For the
                   13317: others: @code{-14 throw} (Interpreting a compile-only word).
                   13318: 
                   13319: @item modifying the contents of the input buffer or a string literal:
                   13320: @cindex modifying the contents of the input buffer or a string literal
                   13321: These are located in writable memory and can be modified.
                   13322: 
                   13323: @item overflow of the pictured numeric output string:
                   13324: @cindex overflow of the pictured numeric output string
                   13325: @cindex pictured numeric output string, overflow
1.24      anton    13326: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1       anton    13327: 
                   13328: @item parsed string overflow:
                   13329: @cindex parsed string overflow
                   13330: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   13331: 
                   13332: @item producing a result out of range:
                   13333: @cindex result out of range
                   13334: On two's complement machines, arithmetic is performed modulo
                   13335: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.166     anton    13336: arithmetic (with appropriate mapping for signed types). Division by
                   13337: zero typically results in a @code{-10 throw} (divide by zero) or
                   13338: @code{-55 throw} (floating point unidentified fault). Overflow on
                   13339: division may result in these errors or in @code{-11 throw} (result out
                   13340: of range).  @code{Gforth-fast} may silently produce bogus results on
                   13341: division overflow or division by zero.  @code{Convert} and
1.24      anton    13342: @code{>number} currently overflow silently.
1.1       anton    13343: 
                   13344: @item reading from an empty data or return stack:
                   13345: @cindex stack empty
                   13346: @cindex stack underflow
1.24      anton    13347: @cindex return stack underflow
1.1       anton    13348: The data stack is checked by the outer (aka text) interpreter after
                   13349: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   13350: underflow) is performed. Apart from that, stacks may be checked or not,
1.24      anton    13351: depending on operating system, installation, and invocation. If they are
                   13352: caught by a check, they typically result in @code{-4 throw} (Stack
                   13353: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
                   13354: (Invalid memory address), depending on the platform and which stack
                   13355: underflows and by how much. Note that even if the system uses checking
                   13356: (through the MMU), your program may have to underflow by a significant
                   13357: number of stack items to trigger the reaction (the reason for this is
                   13358: that the MMU, and therefore the checking, works with a page-size
                   13359: granularity).  If there is no checking, the symptoms resulting from an
                   13360: underflow are similar to those from an overflow.  Unbalanced return
1.80      anton    13361: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24      anton    13362: (Invalid memory address) and Illegal Instruction (typically @code{-260
                   13363: throw}).
1.1       anton    13364: 
                   13365: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   13366: @cindex unexpected end of the input buffer
                   13367: @cindex zero-length string as a name
                   13368: @cindex Attempt to use zero-length string as a name
                   13369: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   13370: use zero-length string as a name). Words like @code{'} probably will not
                   13371: find what they search. Note that it is possible to create zero-length
                   13372: names with @code{nextname} (should it not?).
                   13373: 
                   13374: @item @code{>IN} greater than input buffer:
                   13375: @cindex @code{>IN} greater than input buffer
                   13376: The next invocation of a parsing word returns a string with length 0.
                   13377: 
                   13378: @item @code{RECURSE} appears after @code{DOES>}:
                   13379: @cindex @code{RECURSE} appears after @code{DOES>}
                   13380: Compiles a recursive call to the defining word, not to the defined word.
                   13381: 
                   13382: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   13383: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26      crook    13384: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1       anton    13385: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   13386: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   13387: the end of the file was reached), its source-id may be
                   13388: reused. Therefore, restoring an input source specification referencing a
                   13389: closed file may lead to unpredictable results instead of a @code{-12
                   13390: THROW}.
                   13391: 
                   13392: In the future, Gforth may be able to restore input source specifications
                   13393: from other than the current input source.
                   13394: 
                   13395: @item data space containing definitions gets de-allocated:
                   13396: @cindex data space containing definitions gets de-allocated
                   13397: Deallocation with @code{allot} is not checked. This typically results in
                   13398: memory access faults or execution of illegal instructions.
                   13399: 
                   13400: @item data space read/write with incorrect alignment:
                   13401: @cindex data space read/write with incorrect alignment
                   13402: @cindex alignment faults
1.26      crook    13403: @cindex address alignment exception
1.1       anton    13404: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    13405: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    13406: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   13407: (Invalid memory address). There are reportedly some processors with
1.12      anton    13408: alignment restrictions that do not report violations.
1.1       anton    13409: 
                   13410: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   13411: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   13412: Like other alignment errors.
                   13413: 
                   13414: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   13415: Like other stack underflows.
                   13416: 
                   13417: @item loop control parameters not available:
                   13418: @cindex loop control parameters not available
                   13419: Not checked. The counted loop words simply assume that the top of return
                   13420: stack items are loop control parameters and behave accordingly.
                   13421: 
                   13422: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   13423: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   13424: @cindex last word was headerless
                   13425: @code{abort" last word was headerless"}.
                   13426: 
                   13427: @item name not defined by @code{VALUE} used by @code{TO}:
                   13428: @cindex name not defined by @code{VALUE} used by @code{TO}
                   13429: @cindex @code{TO} on non-@code{VALUE}s
                   13430: @cindex Invalid name argument, @code{TO}
                   13431: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   13432: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   13433: 
                   13434: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   13435: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26      crook    13436: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1       anton    13437: @code{-13 throw} (Undefined word)
                   13438: 
                   13439: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   13440: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   13441: Gforth behaves as if they were of the same type. I.e., you can predict
                   13442: the behaviour by interpreting all parameters as, e.g., signed.
                   13443: 
                   13444: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   13445: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   13446: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   13447: compilation semantics of @code{TO}.
                   13448: 
                   13449: @item String longer than a counted string returned by @code{WORD}:
1.26      crook    13450: @cindex string longer than a counted string returned by @code{WORD}
1.1       anton    13451: @cindex @code{WORD}, string overflow
                   13452: Not checked. The string will be ok, but the count will, of course,
                   13453: contain only the least significant bits of the length.
                   13454: 
                   13455: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   13456: @cindex @code{LSHIFT}, large shift counts
                   13457: @cindex @code{RSHIFT}, large shift counts
                   13458: Processor-dependent. Typical behaviours are returning 0 and using only
                   13459: the low bits of the shift count.
                   13460: 
                   13461: @item word not defined via @code{CREATE}:
                   13462: @cindex @code{>BODY} of non-@code{CREATE}d words
                   13463: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   13464: 
                   13465: @cindex @code{DOES>} of non-@code{CREATE}d words
                   13466: @code{DOES>} changes the execution semantics of the last defined word no
                   13467: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   13468: @code{CREATE , DOES>}.
                   13469: 
                   13470: @item words improperly used outside @code{<#} and @code{#>}:
                   13471: Not checked. As usual, you can expect memory faults.
                   13472: 
                   13473: @end table
                   13474: 
                   13475: 
                   13476: @c ---------------------------------------------------------------------
                   13477: @node core-other,  , core-ambcond, The Core Words
                   13478: @subsection Other system documentation
                   13479: @c ---------------------------------------------------------------------
                   13480: @cindex other system documentation, core words
                   13481: @cindex core words, other system documentation
                   13482: 
                   13483: @table @i
                   13484: @item nonstandard words using @code{PAD}:
                   13485: @cindex @code{PAD} use by nonstandard words
                   13486: None.
                   13487: 
                   13488: @item operator's terminal facilities available:
                   13489: @cindex operator's terminal facilities available
1.80      anton    13490: After processing the OS's command line, Gforth goes into interactive mode,
1.1       anton    13491: and you can give commands to Gforth interactively. The actual facilities
                   13492: available depend on how you invoke Gforth.
                   13493: 
                   13494: @item program data space available:
                   13495: @cindex program data space available
                   13496: @cindex data space available
                   13497: @code{UNUSED .} gives the remaining dictionary space. The total
                   13498: dictionary space can be specified with the @code{-m} switch
                   13499: (@pxref{Invoking Gforth}) when Gforth starts up.
                   13500: 
                   13501: @item return stack space available:
                   13502: @cindex return stack space available
                   13503: You can compute the total return stack space in cells with
                   13504: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   13505: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   13506: 
                   13507: @item stack space available:
                   13508: @cindex stack space available
                   13509: You can compute the total data stack space in cells with
                   13510: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   13511: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   13512: 
                   13513: @item system dictionary space required, in address units:
                   13514: @cindex system dictionary space required, in address units
                   13515: Type @code{here forthstart - .} after startup. At the time of this
                   13516: writing, this gives 80080 (bytes) on a 32-bit system.
                   13517: @end table
                   13518: 
                   13519: 
                   13520: @c =====================================================================
                   13521: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   13522: @section The optional Block word set
                   13523: @c =====================================================================
                   13524: @cindex system documentation, block words
                   13525: @cindex block words, system documentation
                   13526: 
                   13527: @menu
                   13528: * block-idef::                  Implementation Defined Options
                   13529: * block-ambcond::               Ambiguous Conditions               
                   13530: * block-other::                 Other System Documentation                 
                   13531: @end menu
                   13532: 
                   13533: 
                   13534: @c ---------------------------------------------------------------------
                   13535: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   13536: @subsection Implementation Defined Options
                   13537: @c ---------------------------------------------------------------------
                   13538: @cindex implementation-defined options, block words
                   13539: @cindex block words, implementation-defined options
                   13540: 
                   13541: @table @i
                   13542: @item the format for display by @code{LIST}:
                   13543: @cindex @code{LIST} display format
                   13544: First the screen number is displayed, then 16 lines of 64 characters,
                   13545: each line preceded by the line number.
                   13546: 
                   13547: @item the length of a line affected by @code{\}:
                   13548: @cindex length of a line affected by @code{\}
                   13549: @cindex @code{\}, line length in blocks
                   13550: 64 characters.
                   13551: @end table
                   13552: 
                   13553: 
                   13554: @c ---------------------------------------------------------------------
                   13555: @node block-ambcond, block-other, block-idef, The optional Block word set
                   13556: @subsection Ambiguous conditions
                   13557: @c ---------------------------------------------------------------------
                   13558: @cindex block words, ambiguous conditions
                   13559: @cindex ambiguous conditions, block words
                   13560: 
                   13561: @table @i
                   13562: @item correct block read was not possible:
                   13563: @cindex block read not possible
                   13564: Typically results in a @code{throw} of some OS-derived value (between
                   13565: -512 and -2048). If the blocks file was just not long enough, blanks are
                   13566: supplied for the missing portion.
                   13567: 
                   13568: @item I/O exception in block transfer:
                   13569: @cindex I/O exception in block transfer
                   13570: @cindex block transfer, I/O exception
                   13571: Typically results in a @code{throw} of some OS-derived value (between
                   13572: -512 and -2048).
                   13573: 
                   13574: @item invalid block number:
                   13575: @cindex invalid block number
                   13576: @cindex block number invalid
                   13577: @code{-35 throw} (Invalid block number)
                   13578: 
                   13579: @item a program directly alters the contents of @code{BLK}:
                   13580: @cindex @code{BLK}, altering @code{BLK}
                   13581: The input stream is switched to that other block, at the same
                   13582: position. If the storing to @code{BLK} happens when interpreting
                   13583: non-block input, the system will get quite confused when the block ends.
                   13584: 
                   13585: @item no current block buffer for @code{UPDATE}:
                   13586: @cindex @code{UPDATE}, no current block buffer
                   13587: @code{UPDATE} has no effect.
                   13588: 
                   13589: @end table
                   13590: 
                   13591: @c ---------------------------------------------------------------------
                   13592: @node block-other,  , block-ambcond, The optional Block word set
                   13593: @subsection Other system documentation
                   13594: @c ---------------------------------------------------------------------
                   13595: @cindex other system documentation, block words
                   13596: @cindex block words, other system documentation
                   13597: 
                   13598: @table @i
                   13599: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   13600: No restrictions (yet).
                   13601: 
                   13602: @item the number of blocks available for source and data:
                   13603: depends on your disk space.
                   13604: 
                   13605: @end table
                   13606: 
                   13607: 
                   13608: @c =====================================================================
                   13609: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   13610: @section The optional Double Number word set
                   13611: @c =====================================================================
                   13612: @cindex system documentation, double words
                   13613: @cindex double words, system documentation
                   13614: 
                   13615: @menu
                   13616: * double-ambcond::              Ambiguous Conditions              
                   13617: @end menu
                   13618: 
                   13619: 
                   13620: @c ---------------------------------------------------------------------
                   13621: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   13622: @subsection Ambiguous conditions
                   13623: @c ---------------------------------------------------------------------
                   13624: @cindex double words, ambiguous conditions
                   13625: @cindex ambiguous conditions, double words
                   13626: 
                   13627: @table @i
1.29      crook    13628: @item @i{d} outside of range of @i{n} in @code{D>S}:
                   13629: @cindex @code{D>S}, @i{d} out of range of @i{n} 
                   13630: The least significant cell of @i{d} is produced.
1.1       anton    13631: 
                   13632: @end table
                   13633: 
                   13634: 
                   13635: @c =====================================================================
                   13636: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   13637: @section The optional Exception word set
                   13638: @c =====================================================================
                   13639: @cindex system documentation, exception words
                   13640: @cindex exception words, system documentation
                   13641: 
                   13642: @menu
                   13643: * exception-idef::              Implementation Defined Options              
                   13644: @end menu
                   13645: 
                   13646: 
                   13647: @c ---------------------------------------------------------------------
                   13648: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   13649: @subsection Implementation Defined Options
                   13650: @c ---------------------------------------------------------------------
                   13651: @cindex implementation-defined options, exception words
                   13652: @cindex exception words, implementation-defined options
                   13653: 
                   13654: @table @i
                   13655: @item @code{THROW}-codes used in the system:
                   13656: @cindex @code{THROW}-codes used in the system
                   13657: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29      crook    13658: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1       anton    13659: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   13660: allocation operations). The mapping from OS error numbers to throw codes
                   13661: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   13662: undefined OS errors produce a message with a strange number; e.g.,
                   13663: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   13664: @end table
                   13665: 
                   13666: @c =====================================================================
                   13667: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   13668: @section The optional Facility word set
                   13669: @c =====================================================================
                   13670: @cindex system documentation, facility words
                   13671: @cindex facility words, system documentation
                   13672: 
                   13673: @menu
                   13674: * facility-idef::               Implementation Defined Options               
                   13675: * facility-ambcond::            Ambiguous Conditions            
                   13676: @end menu
                   13677: 
                   13678: 
                   13679: @c ---------------------------------------------------------------------
                   13680: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   13681: @subsection Implementation Defined Options
                   13682: @c ---------------------------------------------------------------------
                   13683: @cindex implementation-defined options, facility words
                   13684: @cindex facility words, implementation-defined options
                   13685: 
                   13686: @table @i
                   13687: @item encoding of keyboard events (@code{EKEY}):
                   13688: @cindex keyboard events, encoding in @code{EKEY}
                   13689: @cindex @code{EKEY}, encoding of keyboard events
1.40      anton    13690: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41      anton    13691: Other keys are encoded with the constants @code{k-left}, @code{k-right},
                   13692: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
                   13693: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
                   13694: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40      anton    13695: 
1.1       anton    13696: 
                   13697: @item duration of a system clock tick:
                   13698: @cindex duration of a system clock tick
                   13699: @cindex clock tick duration
                   13700: System dependent. With respect to @code{MS}, the time is specified in
                   13701: microseconds. How well the OS and the hardware implement this, is
                   13702: another question.
                   13703: 
                   13704: @item repeatability to be expected from the execution of @code{MS}:
                   13705: @cindex repeatability to be expected from the execution of @code{MS}
                   13706: @cindex @code{MS}, repeatability to be expected
                   13707: System dependent. On Unix, a lot depends on load. If the system is
                   13708: lightly loaded, and the delay is short enough that Gforth does not get
                   13709: swapped out, the performance should be acceptable. Under MS-DOS and
                   13710: other single-tasking systems, it should be good.
                   13711: 
                   13712: @end table
                   13713: 
                   13714: 
                   13715: @c ---------------------------------------------------------------------
                   13716: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   13717: @subsection Ambiguous conditions
                   13718: @c ---------------------------------------------------------------------
                   13719: @cindex facility words, ambiguous conditions
                   13720: @cindex ambiguous conditions, facility words
                   13721: 
                   13722: @table @i
                   13723: @item @code{AT-XY} can't be performed on user output device:
                   13724: @cindex @code{AT-XY} can't be performed on user output device
                   13725: Largely terminal dependent. No range checks are done on the arguments.
                   13726: No errors are reported. You may see some garbage appearing, you may see
                   13727: simply nothing happen.
                   13728: 
                   13729: @end table
                   13730: 
                   13731: 
                   13732: @c =====================================================================
                   13733: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   13734: @section The optional File-Access word set
                   13735: @c =====================================================================
                   13736: @cindex system documentation, file words
                   13737: @cindex file words, system documentation
                   13738: 
                   13739: @menu
                   13740: * file-idef::                   Implementation Defined Options
                   13741: * file-ambcond::                Ambiguous Conditions                
                   13742: @end menu
                   13743: 
                   13744: @c ---------------------------------------------------------------------
                   13745: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   13746: @subsection Implementation Defined Options
                   13747: @c ---------------------------------------------------------------------
                   13748: @cindex implementation-defined options, file words
                   13749: @cindex file words, implementation-defined options
                   13750: 
                   13751: @table @i
                   13752: @item file access methods used:
                   13753: @cindex file access methods used
                   13754: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   13755: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   13756: @code{wb}): The file is cleared, if it exists, and created, if it does
                   13757: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   13758: @code{create-file} creates a file with 666 permissions modified by your
                   13759: umask.
                   13760: 
                   13761: @item file exceptions:
                   13762: @cindex file exceptions
                   13763: The file words do not raise exceptions (except, perhaps, memory access
                   13764: faults when you pass illegal addresses or file-ids).
                   13765: 
                   13766: @item file line terminator:
                   13767: @cindex file line terminator
                   13768: System-dependent. Gforth uses C's newline character as line
                   13769: terminator. What the actual character code(s) of this are is
                   13770: system-dependent.
                   13771: 
                   13772: @item file name format:
                   13773: @cindex file name format
                   13774: System dependent. Gforth just uses the file name format of your OS.
                   13775: 
                   13776: @item information returned by @code{FILE-STATUS}:
                   13777: @cindex @code{FILE-STATUS}, returned information
                   13778: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   13779: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   13780: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   13781: along with the returned mode.
                   13782: 
                   13783: @item input file state after an exception when including source:
                   13784: @cindex exception when including source
                   13785: All files that are left via the exception are closed.
                   13786: 
1.29      crook    13787: @item @i{ior} values and meaning:
                   13788: @cindex @i{ior} values and meaning
1.68      anton    13789: @cindex @i{wior} values and meaning
1.29      crook    13790: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    13791: intended as throw codes. They typically are in the range
                   13792: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    13793: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    13794: 
                   13795: @item maximum depth of file input nesting:
                   13796: @cindex maximum depth of file input nesting
                   13797: @cindex file input nesting, maximum depth
                   13798: limited by the amount of return stack, locals/TIB stack, and the number
                   13799: of open files available. This should not give you troubles.
                   13800: 
                   13801: @item maximum size of input line:
                   13802: @cindex maximum size of input line
                   13803: @cindex input line size, maximum
                   13804: @code{/line}. Currently 255.
                   13805: 
                   13806: @item methods of mapping block ranges to files:
                   13807: @cindex mapping block ranges to files
                   13808: @cindex files containing blocks
                   13809: @cindex blocks in files
                   13810: By default, blocks are accessed in the file @file{blocks.fb} in the
                   13811: current working directory. The file can be switched with @code{USE}.
                   13812: 
                   13813: @item number of string buffers provided by @code{S"}:
                   13814: @cindex @code{S"}, number of string buffers
                   13815: 1
                   13816: 
                   13817: @item size of string buffer used by @code{S"}:
                   13818: @cindex @code{S"}, size of string buffer
                   13819: @code{/line}. currently 255.
                   13820: 
                   13821: @end table
                   13822: 
                   13823: @c ---------------------------------------------------------------------
                   13824: @node file-ambcond,  , file-idef, The optional File-Access word set
                   13825: @subsection Ambiguous conditions
                   13826: @c ---------------------------------------------------------------------
                   13827: @cindex file words, ambiguous conditions
                   13828: @cindex ambiguous conditions, file words
                   13829: 
                   13830: @table @i
                   13831: @item attempting to position a file outside its boundaries:
                   13832: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   13833: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   13834: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   13835: 
                   13836: @item attempting to read from file positions not yet written:
                   13837: @cindex reading from file positions not yet written
                   13838: End-of-file, i.e., zero characters are read and no error is reported.
                   13839: 
1.29      crook    13840: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
                   13841: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
1.1       anton    13842: An appropriate exception may be thrown, but a memory fault or other
                   13843: problem is more probable.
                   13844: 
1.29      crook    13845: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
                   13846: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
                   13847: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
                   13848: The @i{ior} produced by the operation, that discovered the problem, is
1.1       anton    13849: thrown.
                   13850: 
                   13851: @item named file cannot be opened (@code{INCLUDED}):
                   13852: @cindex @code{INCLUDED}, named file cannot be opened
1.29      crook    13853: The @i{ior} produced by @code{open-file} is thrown.
1.1       anton    13854: 
                   13855: @item requesting an unmapped block number:
                   13856: @cindex unmapped block numbers
                   13857: There are no unmapped legal block numbers. On some operating systems,
                   13858: writing a block with a large number may overflow the file system and
                   13859: have an error message as consequence.
                   13860: 
                   13861: @item using @code{source-id} when @code{blk} is non-zero:
                   13862: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   13863: @code{source-id} performs its function. Typically it will give the id of
                   13864: the source which loaded the block. (Better ideas?)
                   13865: 
                   13866: @end table
                   13867: 
                   13868: 
                   13869: @c =====================================================================
                   13870: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   13871: @section The optional Floating-Point word set
                   13872: @c =====================================================================
                   13873: @cindex system documentation, floating-point words
                   13874: @cindex floating-point words, system documentation
                   13875: 
                   13876: @menu
                   13877: * floating-idef::               Implementation Defined Options
                   13878: * floating-ambcond::            Ambiguous Conditions            
                   13879: @end menu
                   13880: 
                   13881: 
                   13882: @c ---------------------------------------------------------------------
                   13883: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   13884: @subsection Implementation Defined Options
                   13885: @c ---------------------------------------------------------------------
                   13886: @cindex implementation-defined options, floating-point words
                   13887: @cindex floating-point words, implementation-defined options
                   13888: 
                   13889: @table @i
                   13890: @item format and range of floating point numbers:
                   13891: @cindex format and range of floating point numbers
                   13892: @cindex floating point numbers, format and range
                   13893: System-dependent; the @code{double} type of C.
                   13894: 
1.29      crook    13895: @item results of @code{REPRESENT} when @i{float} is out of range:
                   13896: @cindex  @code{REPRESENT}, results when @i{float} is out of range
1.1       anton    13897: System dependent; @code{REPRESENT} is implemented using the C library
                   13898: function @code{ecvt()} and inherits its behaviour in this respect.
                   13899: 
                   13900: @item rounding or truncation of floating-point numbers:
                   13901: @cindex rounding of floating-point numbers
                   13902: @cindex truncation of floating-point numbers
                   13903: @cindex floating-point numbers, rounding or truncation
                   13904: System dependent; the rounding behaviour is inherited from the hosting C
                   13905: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   13906: nearest, and break ties by rounding to even (i.e., such that the last
                   13907: bit of the mantissa is 0).
                   13908: 
                   13909: @item size of floating-point stack:
                   13910: @cindex floating-point stack size
                   13911: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   13912: the floating-point stack (in floats). You can specify this on startup
                   13913: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   13914: 
                   13915: @item width of floating-point stack:
                   13916: @cindex floating-point stack width 
                   13917: @code{1 floats}.
                   13918: 
                   13919: @end table
                   13920: 
                   13921: 
                   13922: @c ---------------------------------------------------------------------
                   13923: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   13924: @subsection Ambiguous conditions
                   13925: @c ---------------------------------------------------------------------
                   13926: @cindex floating-point words, ambiguous conditions
                   13927: @cindex ambiguous conditions, floating-point words
                   13928: 
                   13929: @table @i
                   13930: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   13931: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   13932: System-dependent. Typically results in a @code{-23 THROW} like other
                   13933: alignment violations.
                   13934: 
                   13935: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   13936: @cindex @code{f@@} used with an address that is not float aligned
                   13937: @cindex @code{f!} used with an address that is not float aligned
                   13938: System-dependent. Typically results in a @code{-23 THROW} like other
                   13939: alignment violations.
                   13940: 
                   13941: @item floating-point result out of range:
                   13942: @cindex floating-point result out of range
1.80      anton    13943: System-dependent. Can result in a @code{-43 throw} (floating point
                   13944: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
                   13945: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1       anton    13946: unidentified fault), or can produce a special value representing, e.g.,
                   13947: Infinity.
                   13948: 
                   13949: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   13950: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   13951: System-dependent. Typically results in an alignment fault like other
                   13952: alignment violations.
                   13953: 
1.35      anton    13954: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   13955: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1       anton    13956: The floating-point number is converted into decimal nonetheless.
                   13957: 
                   13958: @item Both arguments are equal to zero (@code{FATAN2}):
                   13959: @cindex @code{FATAN2}, both arguments are equal to zero
                   13960: System-dependent. @code{FATAN2} is implemented using the C library
                   13961: function @code{atan2()}.
                   13962: 
1.29      crook    13963: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
                   13964: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
                   13965: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1       anton    13966: because of small errors and the tan will be a very large (or very small)
                   13967: but finite number.
                   13968: 
1.29      crook    13969: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
                   13970: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1       anton    13971: The result is rounded to the nearest float.
                   13972: 
                   13973: @item dividing by zero:
                   13974: @cindex dividing by zero, floating-point
                   13975: @cindex floating-point dividing by zero
                   13976: @cindex floating-point unidentified fault, FP divide-by-zero
1.80      anton    13977: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
                   13978: (floating point divide by zero) or @code{-55 throw} (Floating-point
                   13979: unidentified fault).
1.1       anton    13980: 
                   13981: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   13982: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   13983: System dependent. On IEEE-FP based systems the number is converted into
                   13984: an infinity.
                   13985: 
1.29      crook    13986: @item @i{float}<1 (@code{FACOSH}):
                   13987: @cindex @code{FACOSH}, @i{float}<1
1.1       anton    13988: @cindex floating-point unidentified fault, @code{FACOSH}
1.80      anton    13989: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1       anton    13990: 
1.29      crook    13991: @item @i{float}=<-1 (@code{FLNP1}):
                   13992: @cindex @code{FLNP1}, @i{float}=<-1
1.1       anton    13993: @cindex floating-point unidentified fault, @code{FLNP1}
1.80      anton    13994: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
                   13995: negative infinity for @i{float}=-1).
1.1       anton    13996: 
1.29      crook    13997: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
                   13998: @cindex @code{FLN}, @i{float}=<0
                   13999: @cindex @code{FLOG}, @i{float}=<0
1.1       anton    14000: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80      anton    14001: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
                   14002: negative infinity for @i{float}=0).
1.1       anton    14003: 
1.29      crook    14004: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
                   14005: @cindex @code{FASINH}, @i{float}<0
                   14006: @cindex @code{FSQRT}, @i{float}<0
1.1       anton    14007: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80      anton    14008: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
                   14009: @code{fasinh} some platforms produce a NaN, others a number (bug in the
                   14010: C library?).
1.1       anton    14011: 
1.29      crook    14012: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
                   14013: @cindex @code{FACOS}, |@i{float}|>1
                   14014: @cindex @code{FASIN}, |@i{float}|>1
                   14015: @cindex @code{FATANH}, |@i{float}|>1
1.1       anton    14016: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80      anton    14017: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1       anton    14018: 
1.29      crook    14019: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
                   14020: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1       anton    14021: @cindex floating-point unidentified fault, @code{F>D}
1.80      anton    14022: Platform-dependent; typically, some double number is produced and no
                   14023: error is reported.
1.1       anton    14024: 
                   14025: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   14026: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80      anton    14027: @code{Precision} characters of the numeric output area are used.  If
                   14028: @code{precision} is too high, these words will smash the data or code
                   14029: close to @code{here}.
1.1       anton    14030: @end table
                   14031: 
                   14032: @c =====================================================================
                   14033: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   14034: @section The optional Locals word set
                   14035: @c =====================================================================
                   14036: @cindex system documentation, locals words
                   14037: @cindex locals words, system documentation
                   14038: 
                   14039: @menu
                   14040: * locals-idef::                 Implementation Defined Options                 
                   14041: * locals-ambcond::              Ambiguous Conditions              
                   14042: @end menu
                   14043: 
                   14044: 
                   14045: @c ---------------------------------------------------------------------
                   14046: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   14047: @subsection Implementation Defined Options
                   14048: @c ---------------------------------------------------------------------
                   14049: @cindex implementation-defined options, locals words
                   14050: @cindex locals words, implementation-defined options
                   14051: 
                   14052: @table @i
                   14053: @item maximum number of locals in a definition:
                   14054: @cindex maximum number of locals in a definition
                   14055: @cindex locals, maximum number in a definition
                   14056: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   14057: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   14058: characters. The number of locals in a definition is bounded by the size
                   14059: of locals-buffer, which contains the names of the locals.
                   14060: 
                   14061: @end table
                   14062: 
                   14063: 
                   14064: @c ---------------------------------------------------------------------
                   14065: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   14066: @subsection Ambiguous conditions
                   14067: @c ---------------------------------------------------------------------
                   14068: @cindex locals words, ambiguous conditions
                   14069: @cindex ambiguous conditions, locals words
                   14070: 
                   14071: @table @i
                   14072: @item executing a named local in interpretation state:
                   14073: @cindex local in interpretation state
                   14074: @cindex Interpreting a compile-only word, for a local
                   14075: Locals have no interpretation semantics. If you try to perform the
                   14076: interpretation semantics, you will get a @code{-14 throw} somewhere
                   14077: (Interpreting a compile-only word). If you perform the compilation
                   14078: semantics, the locals access will be compiled (irrespective of state).
                   14079: 
1.29      crook    14080: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1       anton    14081: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   14082: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   14083: @cindex Invalid name argument, @code{TO}
                   14084: @code{-32 throw} (Invalid name argument)
                   14085: 
                   14086: @end table
                   14087: 
                   14088: 
                   14089: @c =====================================================================
                   14090: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   14091: @section The optional Memory-Allocation word set
                   14092: @c =====================================================================
                   14093: @cindex system documentation, memory-allocation words
                   14094: @cindex memory-allocation words, system documentation
                   14095: 
                   14096: @menu
                   14097: * memory-idef::                 Implementation Defined Options                 
                   14098: @end menu
                   14099: 
                   14100: 
                   14101: @c ---------------------------------------------------------------------
                   14102: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   14103: @subsection Implementation Defined Options
                   14104: @c ---------------------------------------------------------------------
                   14105: @cindex implementation-defined options, memory-allocation words
                   14106: @cindex memory-allocation words, implementation-defined options
                   14107: 
                   14108: @table @i
1.29      crook    14109: @item values and meaning of @i{ior}:
                   14110: @cindex  @i{ior} values and meaning
                   14111: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    14112: intended as throw codes. They typically are in the range
                   14113: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    14114: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    14115: 
                   14116: @end table
                   14117: 
                   14118: @c =====================================================================
                   14119: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   14120: @section The optional Programming-Tools word set
                   14121: @c =====================================================================
                   14122: @cindex system documentation, programming-tools words
                   14123: @cindex programming-tools words, system documentation
                   14124: 
                   14125: @menu
                   14126: * programming-idef::            Implementation Defined Options            
                   14127: * programming-ambcond::         Ambiguous Conditions         
                   14128: @end menu
                   14129: 
                   14130: 
                   14131: @c ---------------------------------------------------------------------
                   14132: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   14133: @subsection Implementation Defined Options
                   14134: @c ---------------------------------------------------------------------
                   14135: @cindex implementation-defined options, programming-tools words
                   14136: @cindex programming-tools words, implementation-defined options
                   14137: 
                   14138: @table @i
                   14139: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   14140: @cindex @code{;CODE} ending sequence
                   14141: @cindex @code{CODE} ending sequence
                   14142: @code{END-CODE}
                   14143: 
                   14144: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   14145: @cindex @code{;CODE}, processing input
                   14146: @cindex @code{CODE}, processing input
                   14147: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   14148: the input is processed by the text interpreter, (starting) in interpret
                   14149: state.
                   14150: 
                   14151: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   14152: @cindex @code{ASSEMBLER}, search order capability
                   14153: The ANS Forth search order word set.
                   14154: 
                   14155: @item source and format of display by @code{SEE}:
                   14156: @cindex @code{SEE}, source and format of output
1.80      anton    14157: The source for @code{see} is the executable code used by the inner
1.1       anton    14158: interpreter.  The current @code{see} tries to output Forth source code
1.80      anton    14159: (and on some platforms, assembly code for primitives) as well as
                   14160: possible.
1.1       anton    14161: 
                   14162: @end table
                   14163: 
                   14164: @c ---------------------------------------------------------------------
                   14165: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   14166: @subsection Ambiguous conditions
                   14167: @c ---------------------------------------------------------------------
                   14168: @cindex programming-tools words, ambiguous conditions
                   14169: @cindex ambiguous conditions, programming-tools words
                   14170: 
                   14171: @table @i
                   14172: 
1.21      crook    14173: @item deleting the compilation word list (@code{FORGET}):
                   14174: @cindex @code{FORGET}, deleting the compilation word list
1.1       anton    14175: Not implemented (yet).
                   14176: 
1.29      crook    14177: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
                   14178: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
                   14179: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1       anton    14180: @cindex control-flow stack underflow
                   14181: This typically results in an @code{abort"} with a descriptive error
                   14182: message (may change into a @code{-22 throw} (Control structure mismatch)
                   14183: in the future). You may also get a memory access error. If you are
                   14184: unlucky, this ambiguous condition is not caught.
                   14185: 
1.29      crook    14186: @item @i{name} can't be found (@code{FORGET}):
                   14187: @cindex @code{FORGET}, @i{name} can't be found
1.1       anton    14188: Not implemented (yet).
                   14189: 
1.29      crook    14190: @item @i{name} not defined via @code{CREATE}:
                   14191: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1       anton    14192: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   14193: the execution semantics of the last defined word no matter how it was
                   14194: defined.
                   14195: 
                   14196: @item @code{POSTPONE} applied to @code{[IF]}:
                   14197: @cindex @code{POSTPONE} applied to @code{[IF]}
                   14198: @cindex @code{[IF]} and @code{POSTPONE}
                   14199: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   14200: equivalent to @code{[IF]}.
                   14201: 
                   14202: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   14203: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   14204: Continue in the same state of conditional compilation in the next outer
                   14205: input source. Currently there is no warning to the user about this.
                   14206: 
                   14207: @item removing a needed definition (@code{FORGET}):
                   14208: @cindex @code{FORGET}, removing a needed definition
                   14209: Not implemented (yet).
                   14210: 
                   14211: @end table
                   14212: 
                   14213: 
                   14214: @c =====================================================================
                   14215: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   14216: @section The optional Search-Order word set
                   14217: @c =====================================================================
                   14218: @cindex system documentation, search-order words
                   14219: @cindex search-order words, system documentation
                   14220: 
                   14221: @menu
                   14222: * search-idef::                 Implementation Defined Options                 
                   14223: * search-ambcond::              Ambiguous Conditions              
                   14224: @end menu
                   14225: 
                   14226: 
                   14227: @c ---------------------------------------------------------------------
                   14228: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   14229: @subsection Implementation Defined Options
                   14230: @c ---------------------------------------------------------------------
                   14231: @cindex implementation-defined options, search-order words
                   14232: @cindex search-order words, implementation-defined options
                   14233: 
                   14234: @table @i
                   14235: @item maximum number of word lists in search order:
                   14236: @cindex maximum number of word lists in search order
                   14237: @cindex search order, maximum depth
                   14238: @code{s" wordlists" environment? drop .}. Currently 16.
                   14239: 
                   14240: @item minimum search order:
                   14241: @cindex minimum search order
                   14242: @cindex search order, minimum
                   14243: @code{root root}.
                   14244: 
                   14245: @end table
                   14246: 
                   14247: @c ---------------------------------------------------------------------
                   14248: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   14249: @subsection Ambiguous conditions
                   14250: @c ---------------------------------------------------------------------
                   14251: @cindex search-order words, ambiguous conditions
                   14252: @cindex ambiguous conditions, search-order words
                   14253: 
                   14254: @table @i
1.21      crook    14255: @item changing the compilation word list (during compilation):
                   14256: @cindex changing the compilation word list (during compilation)
                   14257: @cindex compilation word list, change before definition ends
                   14258: The word is entered into the word list that was the compilation word list
1.1       anton    14259: at the start of the definition. Any changes to the name field (e.g.,
                   14260: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116     anton    14261: are applied to the latest defined word (as reported by @code{latest} or
                   14262: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1       anton    14263: 
                   14264: @item search order empty (@code{previous}):
                   14265: @cindex @code{previous}, search order empty
1.26      crook    14266: @cindex vocstack empty, @code{previous}
1.1       anton    14267: @code{abort" Vocstack empty"}.
                   14268: 
                   14269: @item too many word lists in search order (@code{also}):
                   14270: @cindex @code{also}, too many word lists in search order
1.26      crook    14271: @cindex vocstack full, @code{also}
1.1       anton    14272: @code{abort" Vocstack full"}.
                   14273: 
                   14274: @end table
                   14275: 
                   14276: @c ***************************************************************
1.65      anton    14277: @node Standard vs Extensions, Model, ANS conformance, Top
                   14278: @chapter Should I use Gforth extensions?
                   14279: @cindex Gforth extensions
                   14280: 
                   14281: As you read through the rest of this manual, you will see documentation
                   14282: for @i{Standard} words, and documentation for some appealing Gforth
                   14283: @i{extensions}. You might ask yourself the question: @i{``Should I
                   14284: restrict myself to the standard, or should I use the extensions?''}
                   14285: 
                   14286: The answer depends on the goals you have for the program you are working
                   14287: on:
                   14288: 
                   14289: @itemize @bullet
                   14290: 
                   14291: @item Is it just for yourself or do you want to share it with others?
                   14292: 
                   14293: @item
                   14294: If you want to share it, do the others all use Gforth?
                   14295: 
                   14296: @item
                   14297: If it is just for yourself, do you want to restrict yourself to Gforth?
                   14298: 
                   14299: @end itemize
                   14300: 
                   14301: If restricting the program to Gforth is ok, then there is no reason not
                   14302: to use extensions.  It is still a good idea to keep to the standard
                   14303: where it is easy, in case you want to reuse these parts in another
                   14304: program that you want to be portable.
                   14305: 
                   14306: If you want to be able to port the program to other Forth systems, there
                   14307: are the following points to consider:
                   14308: 
                   14309: @itemize @bullet
                   14310: 
                   14311: @item
                   14312: Most Forth systems that are being maintained support the ANS Forth
                   14313: standard.  So if your program complies with the standard, it will be
                   14314: portable among many systems.
                   14315: 
                   14316: @item
                   14317: A number of the Gforth extensions can be implemented in ANS Forth using
                   14318: public-domain files provided in the @file{compat/} directory. These are
                   14319: mentioned in the text in passing.  There is no reason not to use these
                   14320: extensions, your program will still be ANS Forth compliant; just include
                   14321: the appropriate compat files with your program.
                   14322: 
                   14323: @item
                   14324: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
                   14325: analyse your program and determine what non-Standard words it relies
                   14326: upon.  However, it does not check whether you use standard words in a
                   14327: non-standard way.
                   14328: 
                   14329: @item
                   14330: Some techniques are not standardized by ANS Forth, and are hard or
                   14331: impossible to implement in a standard way, but can be implemented in
                   14332: most Forth systems easily, and usually in similar ways (e.g., accessing
                   14333: word headers).  Forth has a rich historical precedent for programmers
                   14334: taking advantage of implementation-dependent features of their tools
                   14335: (for example, relying on a knowledge of the dictionary
                   14336: structure). Sometimes these techniques are necessary to extract every
                   14337: last bit of performance from the hardware, sometimes they are just a
                   14338: programming shorthand.
                   14339: 
                   14340: @item
                   14341: Does using a Gforth extension save more work than the porting this part
                   14342: to other Forth systems (if any) will cost?
                   14343: 
                   14344: @item
                   14345: Is the additional functionality worth the reduction in portability and
                   14346: the additional porting problems?
                   14347: 
                   14348: @end itemize
                   14349: 
                   14350: In order to perform these consideratios, you need to know what's
                   14351: standard and what's not.  This manual generally states if something is
1.81      anton    14352: non-standard, but the authoritative source is the
                   14353: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65      anton    14354: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
                   14355: into the thought processes of the technical committee.
                   14356: 
                   14357: Note also that portability between Forth systems is not the only
                   14358: portability issue; there is also the issue of portability between
                   14359: different platforms (processor/OS combinations).
                   14360: 
                   14361: @c ***************************************************************
                   14362: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1       anton    14363: @chapter Model
                   14364: 
                   14365: This chapter has yet to be written. It will contain information, on
                   14366: which internal structures you can rely.
                   14367: 
                   14368: @c ***************************************************************
                   14369: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   14370: @chapter Integrating Gforth into C programs
                   14371: 
                   14372: This is not yet implemented.
                   14373: 
                   14374: Several people like to use Forth as scripting language for applications
                   14375: that are otherwise written in C, C++, or some other language.
                   14376: 
                   14377: The Forth system ATLAST provides facilities for embedding it into
                   14378: applications; unfortunately it has several disadvantages: most
                   14379: importantly, it is not based on ANS Forth, and it is apparently dead
                   14380: (i.e., not developed further and not supported). The facilities
1.21      crook    14381: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1       anton    14382: making the switch should not be hard.
                   14383: 
                   14384: We also tried to design the interface such that it can easily be
                   14385: implemented by other Forth systems, so that we may one day arrive at a
                   14386: standardized interface. Such a standard interface would allow you to
                   14387: replace the Forth system without having to rewrite C code.
                   14388: 
                   14389: You embed the Gforth interpreter by linking with the library
                   14390: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   14391: global symbols in this library that belong to the interface, have the
                   14392: prefix @code{forth_}. (Global symbols that are used internally have the
                   14393: prefix @code{gforth_}).
                   14394: 
                   14395: You can include the declarations of Forth types and the functions and
                   14396: variables of the interface with @code{#include <forth.h>}.
                   14397: 
                   14398: Types.
                   14399: 
                   14400: Variables.
                   14401: 
                   14402: Data and FP Stack pointer. Area sizes.
                   14403: 
                   14404: functions.
                   14405: 
                   14406: forth_init(imagefile)
                   14407: forth_evaluate(string) exceptions?
                   14408: forth_goto(address) (or forth_execute(xt)?)
                   14409: forth_continue() (a corountining mechanism)
                   14410: 
                   14411: Adding primitives.
                   14412: 
                   14413: No checking.
                   14414: 
                   14415: Signals?
                   14416: 
                   14417: Accessing the Stacks
                   14418: 
1.26      crook    14419: @c ******************************************************************
1.1       anton    14420: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   14421: @chapter Emacs and Gforth
                   14422: @cindex Emacs and Gforth
                   14423: 
                   14424: @cindex @file{gforth.el}
                   14425: @cindex @file{forth.el}
                   14426: @cindex Rydqvist, Goran
1.107     dvdkhlng 14427: @cindex Kuehling, David
1.1       anton    14428: @cindex comment editing commands
                   14429: @cindex @code{\}, editing with Emacs
                   14430: @cindex debug tracer editing commands
                   14431: @cindex @code{~~}, removal with Emacs
                   14432: @cindex Forth mode in Emacs
1.107     dvdkhlng 14433: 
1.1       anton    14434: Gforth comes with @file{gforth.el}, an improved version of
                   14435: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26      crook    14436: improvements are:
                   14437: 
                   14438: @itemize @bullet
                   14439: @item
1.107     dvdkhlng 14440: A better handling of indentation.
                   14441: @item
                   14442: A custom hilighting engine for Forth-code.
1.26      crook    14443: @item
                   14444: Comment paragraph filling (@kbd{M-q})
                   14445: @item
                   14446: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
                   14447: @item
                   14448: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41      anton    14449: @item
                   14450: Support of the @code{info-lookup} feature for looking up the
                   14451: documentation of a word.
1.107     dvdkhlng 14452: @item
                   14453: Support for reading and writing blocks files.
1.26      crook    14454: @end itemize
                   14455: 
1.107     dvdkhlng 14456: To get a basic description of these features, enter Forth mode and
                   14457: type @kbd{C-h m}.
1.1       anton    14458: 
                   14459: @cindex source location of error or debugging output in Emacs
                   14460: @cindex error output, finding the source location in Emacs
                   14461: @cindex debugging output, finding the source location in Emacs
                   14462: In addition, Gforth supports Emacs quite well: The source code locations
                   14463: given in error messages, debugging output (from @code{~~}) and failed
                   14464: assertion messages are in the right format for Emacs' compilation mode
                   14465: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   14466: Manual}) so the source location corresponding to an error or other
                   14467: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   14468: @kbd{C-c C-c} for the error under the cursor).
                   14469: 
1.107     dvdkhlng 14470: @cindex viewing the documentation of a word in Emacs
                   14471: @cindex context-sensitive help
                   14472: Moreover, for words documented in this manual, you can look up the
                   14473: glossary entry quickly by using @kbd{C-h TAB}
                   14474: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
                   14475: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
                   14476: later and does not work for words containing @code{:}.
                   14477: 
                   14478: @menu
                   14479: * Installing gforth.el::        Making Emacs aware of Forth.
                   14480: * Emacs Tags::                  Viewing the source of a word in Emacs.
                   14481: * Hilighting::                  Making Forth code look prettier.
                   14482: * Auto-Indentation::            Customizing auto-indentation.
                   14483: * Blocks Files::                Reading and writing blocks files.
                   14484: @end menu
                   14485: 
                   14486: @c ----------------------------------
1.109     anton    14487: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107     dvdkhlng 14488: @section Installing gforth.el
                   14489: @cindex @file{.emacs}
                   14490: @cindex @file{gforth.el}, installation
                   14491: To make the features from @file{gforth.el} available in Emacs, add
                   14492: the following lines to your @file{.emacs} file:
                   14493: 
                   14494: @example
                   14495: (autoload 'forth-mode "gforth.el")
                   14496: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) 
                   14497:                            auto-mode-alist))
                   14498: (autoload 'forth-block-mode "gforth.el")
                   14499: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode) 
                   14500:                            auto-mode-alist))
                   14501: (add-hook 'forth-mode-hook (function (lambda ()
                   14502:    ;; customize variables here:
                   14503:    (setq forth-indent-level 4)
                   14504:    (setq forth-minor-indent-level 2)
                   14505:    (setq forth-hilight-level 3)
                   14506:    ;;; ...
                   14507: )))
                   14508: @end example
                   14509: 
                   14510: @c ----------------------------------
                   14511: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
                   14512: @section Emacs Tags
1.1       anton    14513: @cindex @file{TAGS} file
                   14514: @cindex @file{etags.fs}
                   14515: @cindex viewing the source of a word in Emacs
1.43      anton    14516: @cindex @code{require}, placement in files
                   14517: @cindex @code{include}, placement in files
1.107     dvdkhlng 14518: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
                   14519: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1       anton    14520: contains the definitions of all words defined afterwards. You can then
1.107     dvdkhlng 14521: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1       anton    14522: several tags files at the same time (e.g., one for the Gforth sources
                   14523: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   14524: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   14525: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43      anton    14526: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
                   14527: with @file{etags.fs}, you should avoid putting definitions both before
                   14528: and after @code{require} etc., otherwise you will see the same file
                   14529: visited several times by commands like @code{tags-search}.
1.1       anton    14530: 
1.107     dvdkhlng 14531: @c ----------------------------------
                   14532: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
                   14533: @section Hilighting
                   14534: @cindex hilighting Forth code in Emacs
                   14535: @cindex highlighting Forth code in Emacs
                   14536: @file{gforth.el} comes with a custom source hilighting engine.  When
                   14537: you open a file in @code{forth-mode}, it will be completely parsed,
                   14538: assigning faces to keywords, comments, strings etc.  While you edit
                   14539: the file, modified regions get parsed and updated on-the-fly. 
                   14540: 
                   14541: Use the variable `forth-hilight-level' to change the level of
                   14542: decoration from 0 (no hilighting at all) to 3 (the default).  Even if
                   14543: you set the hilighting level to 0, the parser will still work in the
                   14544: background, collecting information about whether regions of text are
                   14545: ``compiled'' or ``interpreted''.  Those information are required for
                   14546: auto-indentation to work properly.  Set `forth-disable-parser' to
                   14547: non-nil if your computer is too slow to handle parsing.  This will
                   14548: have an impact on the smartness of the auto-indentation engine,
                   14549: though.
                   14550: 
                   14551: Sometimes Forth sources define new features that should be hilighted,
                   14552: new control structures, defining-words etc.  You can use the variable
                   14553: `forth-custom-words' to make @code{forth-mode} hilight additional
                   14554: words and constructs.  See the docstring of `forth-words' for details
                   14555: (in Emacs, type @kbd{C-h v forth-words}).
                   14556: 
                   14557: `forth-custom-words' is meant to be customized in your
                   14558: @file{.emacs} file.  To customize hilighing in a file-specific manner,
                   14559: set `forth-local-words' in a local-variables section at the end of
                   14560: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
                   14561: 
                   14562: Example:
                   14563: @example
                   14564: 0 [IF]
                   14565:    Local Variables:
                   14566:    forth-local-words:
                   14567:       ((("t:") definition-starter (font-lock-keyword-face . 1)
                   14568:         "[ \t\n]" t name (font-lock-function-name-face . 3))
                   14569:        ((";t") definition-ender (font-lock-keyword-face . 1)))
                   14570:    End:
                   14571: [THEN]
                   14572: @end example
                   14573: 
                   14574: @c ----------------------------------
                   14575: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
                   14576: @section Auto-Indentation
                   14577: @cindex auto-indentation of Forth code in Emacs
                   14578: @cindex indentation of Forth code in Emacs
                   14579: @code{forth-mode} automatically tries to indent lines in a smart way,
                   14580: whenever you type @key{TAB} or break a line with @kbd{C-m}.
                   14581: 
                   14582: Simple customization can be achieved by setting
                   14583: `forth-indent-level' and `forth-minor-indent-level' in your
                   14584: @file{.emacs} file. For historical reasons @file{gforth.el} indents
                   14585: per default by multiples of 4 columns.  To use the more traditional
                   14586: 3-column indentation, add the following lines to your @file{.emacs}:
                   14587: 
                   14588: @example
                   14589: (add-hook 'forth-mode-hook (function (lambda ()
                   14590:    ;; customize variables here:
                   14591:    (setq forth-indent-level 3)
                   14592:    (setq forth-minor-indent-level 1)
                   14593: )))
                   14594: @end example
                   14595: 
                   14596: If you want indentation to recognize non-default words, customize it
                   14597: by setting `forth-custom-indent-words' in your @file{.emacs}.  See the
                   14598: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
                   14599: v forth-indent-words}).
                   14600: 
                   14601: To customize indentation in a file-specific manner, set
                   14602: `forth-local-indent-words' in a local-variables section at the end of
                   14603: your source file (@pxref{Local Variables in Files, Variables,,emacs,
                   14604: Emacs Manual}).
                   14605: 
                   14606: Example:
                   14607: @example
                   14608: 0 [IF]
                   14609:    Local Variables:
                   14610:    forth-local-indent-words:
                   14611:       ((("t:") (0 . 2) (0 . 2))
                   14612:        ((";t") (-2 . 0) (0 . -2)))
                   14613:    End:
                   14614: [THEN]
                   14615: @end example
                   14616: 
                   14617: @c ----------------------------------
1.109     anton    14618: @node Blocks Files,  , Auto-Indentation, Emacs and Gforth
1.107     dvdkhlng 14619: @section Blocks Files
                   14620: @cindex blocks files, use with Emacs
                   14621: @code{forth-mode} Autodetects blocks files by checking whether the
                   14622: length of the first line exceeds 1023 characters.  It then tries to
                   14623: convert the file into normal text format.  When you save the file, it
                   14624: will be written to disk as normal stream-source file.
                   14625: 
                   14626: If you want to write blocks files, use @code{forth-blocks-mode}.  It
                   14627: inherits all the features from @code{forth-mode}, plus some additions:
1.41      anton    14628: 
1.107     dvdkhlng 14629: @itemize @bullet
                   14630: @item
                   14631: Files are written to disk in blocks file format.
                   14632: @item
                   14633: Screen numbers are displayed in the mode line (enumerated beginning
                   14634: with the value of `forth-block-base')
                   14635: @item
                   14636: Warnings are displayed when lines exceed 64 characters.
                   14637: @item
                   14638: The beginning of the currently edited block is marked with an
                   14639: overlay-arrow. 
                   14640: @end itemize
1.41      anton    14641: 
1.107     dvdkhlng 14642: There are some restrictions you should be aware of.  When you open a
                   14643: blocks file that contains tabulator or newline characters, these
                   14644: characters will be translated into spaces when the file is written
                   14645: back to disk.  If tabs or newlines are encountered during blocks file
                   14646: reading, an error is output to the echo area. So have a look at the
                   14647: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1       anton    14648: 
1.107     dvdkhlng 14649: Please consult the docstring of @code{forth-blocks-mode} for more
                   14650: information by typing @kbd{C-h v forth-blocks-mode}).
1.1       anton    14651: 
1.26      crook    14652: @c ******************************************************************
1.1       anton    14653: @node Image Files, Engine, Emacs and Gforth, Top
                   14654: @chapter Image Files
1.26      crook    14655: @cindex image file
                   14656: @cindex @file{.fi} files
1.1       anton    14657: @cindex precompiled Forth code
                   14658: @cindex dictionary in persistent form
                   14659: @cindex persistent form of dictionary
                   14660: 
                   14661: An image file is a file containing an image of the Forth dictionary,
                   14662: i.e., compiled Forth code and data residing in the dictionary.  By
                   14663: convention, we use the extension @code{.fi} for image files.
                   14664: 
                   14665: @menu
1.18      anton    14666: * Image Licensing Issues::      Distribution terms for images.
                   14667: * Image File Background::       Why have image files?
1.67      anton    14668: * Non-Relocatable Image Files::  don't always work.
1.18      anton    14669: * Data-Relocatable Image Files::  are better.
1.67      anton    14670: * Fully Relocatable Image Files::  better yet.
1.18      anton    14671: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.29      crook    14672: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.18      anton    14673: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    14674: @end menu
                   14675: 
1.18      anton    14676: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   14677: @section Image Licensing Issues
                   14678: @cindex license for images
                   14679: @cindex image license
                   14680: 
                   14681: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   14682: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   14683: original image; i.e., according to copyright law it is a derived work of
                   14684: the original image.
                   14685: 
                   14686: Since Gforth is distributed under the GNU GPL, the newly created image
                   14687: falls under the GNU GPL, too. In particular, this means that if you
                   14688: distribute the image, you have to make all of the sources for the image
1.113     anton    14689: available, including those you wrote.  For details see @ref{Copying, ,
1.18      anton    14690: GNU General Public License (Section 3)}.
                   14691: 
                   14692: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   14693: contains only code compiled from the sources you gave it; if none of
                   14694: these sources is under the GPL, the terms discussed above do not apply
                   14695: to the image. However, if your image needs an engine (a gforth binary)
                   14696: that is under the GPL, you should make sure that you distribute both in
                   14697: a way that is at most a @emph{mere aggregation}, if you don't want the
                   14698: terms of the GPL to apply to the image.
                   14699: 
                   14700: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    14701: @section Image File Background
                   14702: @cindex image file background
                   14703: 
1.80      anton    14704: Gforth consists not only of primitives (in the engine), but also of
1.1       anton    14705: definitions written in Forth. Since the Forth compiler itself belongs to
                   14706: those definitions, it is not possible to start the system with the
1.80      anton    14707: engine and the Forth source alone. Therefore we provide the Forth
1.26      crook    14708: code as an image file in nearly executable form. When Gforth starts up,
                   14709: a C routine loads the image file into memory, optionally relocates the
                   14710: addresses, then sets up the memory (stacks etc.) according to
                   14711: information in the image file, and (finally) starts executing Forth
                   14712: code.
1.1       anton    14713: 
                   14714: The image file variants represent different compromises between the
                   14715: goals of making it easy to generate image files and making them
                   14716: portable.
                   14717: 
                   14718: @cindex relocation at run-time
1.26      crook    14719: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1       anton    14720: run-time. This avoids many of the complications discussed below (image
                   14721: files are data relocatable without further ado), but costs performance
                   14722: (one addition per memory access).
                   14723: 
                   14724: @cindex relocation at load-time
1.26      crook    14725: By contrast, the Gforth loader performs relocation at image load time. The
                   14726: loader also has to replace tokens that represent primitive calls with the
1.1       anton    14727: appropriate code-field addresses (or code addresses in the case of
                   14728: direct threading).
                   14729: 
                   14730: There are three kinds of image files, with different degrees of
                   14731: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   14732: image files.
                   14733: 
                   14734: @cindex image file loader
                   14735: @cindex relocating loader
                   14736: @cindex loader for image files
                   14737: These image file variants have several restrictions in common; they are
                   14738: caused by the design of the image file loader:
                   14739: 
                   14740: @itemize @bullet
                   14741: @item
                   14742: There is only one segment; in particular, this means, that an image file
                   14743: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26      crook    14744: them). The contents of the stacks are not represented, either.
1.1       anton    14745: 
                   14746: @item
                   14747: The only kinds of relocation supported are: adding the same offset to
                   14748: all cells that represent data addresses; and replacing special tokens
                   14749: with code addresses or with pieces of machine code.
                   14750: 
                   14751: If any complex computations involving addresses are performed, the
                   14752: results cannot be represented in the image file. Several applications that
                   14753: use such computations come to mind:
                   14754: @itemize @minus
                   14755: @item
                   14756: Hashing addresses (or data structures which contain addresses) for table
                   14757: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   14758: purpose, you will have no problem, because the hash tables are
                   14759: recomputed automatically when the system is started. If you use your own
                   14760: hash tables, you will have to do something similar.
                   14761: 
                   14762: @item
                   14763: There's a cute implementation of doubly-linked lists that uses
                   14764: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   14765: in the image file, and restore the doubly-linked representation on
                   14766: startup.@footnote{In my opinion, though, you should think thrice before
                   14767: using a doubly-linked list (whatever implementation).}
                   14768: 
                   14769: @item
                   14770: The code addresses of run-time routines like @code{docol:} cannot be
                   14771: represented in the image file (because their tokens would be replaced by
                   14772: machine code in direct threaded implementations). As a workaround,
                   14773: compute these addresses at run-time with @code{>code-address} from the
                   14774: executions tokens of appropriate words (see the definitions of
1.80      anton    14775: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1       anton    14776: 
                   14777: @item
                   14778: On many architectures addresses are represented in machine code in some
                   14779: shifted or mangled form. You cannot put @code{CODE} words that contain
                   14780: absolute addresses in this form in a relocatable image file. Workarounds
                   14781: are representing the address in some relative form (e.g., relative to
                   14782: the CFA, which is present in some register), or loading the address from
                   14783: a place where it is stored in a non-mangled form.
                   14784: @end itemize
                   14785: @end itemize
                   14786: 
                   14787: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   14788: @section Non-Relocatable Image Files
                   14789: @cindex non-relocatable image files
1.26      crook    14790: @cindex image file, non-relocatable
1.1       anton    14791: 
                   14792: These files are simple memory dumps of the dictionary. They are specific
                   14793: to the executable (i.e., @file{gforth} file) they were created
                   14794: with. What's worse, they are specific to the place on which the
                   14795: dictionary resided when the image was created. Now, there is no
                   14796: guarantee that the dictionary will reside at the same place the next
                   14797: time you start Gforth, so there's no guarantee that a non-relocatable
                   14798: image will work the next time (Gforth will complain instead of crashing,
                   14799: though).
                   14800: 
                   14801: You can create a non-relocatable image file with
                   14802: 
1.44      crook    14803: 
1.1       anton    14804: doc-savesystem
                   14805: 
1.44      crook    14806: 
1.1       anton    14807: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   14808: @section Data-Relocatable Image Files
                   14809: @cindex data-relocatable image files
1.26      crook    14810: @cindex image file, data-relocatable
1.1       anton    14811: 
                   14812: These files contain relocatable data addresses, but fixed code addresses
                   14813: (instead of tokens). They are specific to the executable (i.e.,
                   14814: @file{gforth} file) they were created with. For direct threading on some
                   14815: architectures (e.g., the i386), data-relocatable images do not work. You
                   14816: get a data-relocatable image, if you use @file{gforthmi} with a
                   14817: Gforth binary that is not doubly indirect threaded (@pxref{Fully
                   14818: Relocatable Image Files}).
                   14819: 
                   14820: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   14821: @section Fully Relocatable Image Files
                   14822: @cindex fully relocatable image files
1.26      crook    14823: @cindex image file, fully relocatable
1.1       anton    14824: 
                   14825: @cindex @file{kern*.fi}, relocatability
                   14826: @cindex @file{gforth.fi}, relocatability
                   14827: These image files have relocatable data addresses, and tokens for code
                   14828: addresses. They can be used with different binaries (e.g., with and
                   14829: without debugging) on the same machine, and even across machines with
                   14830: the same data formats (byte order, cell size, floating point
                   14831: format). However, they are usually specific to the version of Gforth
                   14832: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
                   14833: are fully relocatable.
                   14834: 
                   14835: There are two ways to create a fully relocatable image file:
                   14836: 
                   14837: @menu
1.29      crook    14838: * gforthmi::                    The normal way
1.1       anton    14839: * cross.fs::                    The hard way
                   14840: @end menu
                   14841: 
                   14842: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   14843: @subsection @file{gforthmi}
                   14844: @cindex @file{comp-i.fs}
                   14845: @cindex @file{gforthmi}
                   14846: 
                   14847: You will usually use @file{gforthmi}. If you want to create an
1.29      crook    14848: image @i{file} that contains everything you would load by invoking
                   14849: Gforth with @code{gforth @i{options}}, you simply say:
1.1       anton    14850: @example
1.29      crook    14851: gforthmi @i{file} @i{options}
1.1       anton    14852: @end example
                   14853: 
                   14854: E.g., if you want to create an image @file{asm.fi} that has the file
                   14855: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   14856: like this:
                   14857: 
                   14858: @example
                   14859: gforthmi asm.fi asm.fs
                   14860: @end example
                   14861: 
1.27      crook    14862: @file{gforthmi} is implemented as a sh script and works like this: It
                   14863: produces two non-relocatable images for different addresses and then
                   14864: compares them. Its output reflects this: first you see the output (if
1.62      crook    14865: any) of the two Gforth invocations that produce the non-relocatable image
1.27      crook    14866: files, then you see the output of the comparing program: It displays the
                   14867: offset used for data addresses and the offset used for code addresses;
1.1       anton    14868: moreover, for each cell that cannot be represented correctly in the
1.44      crook    14869: image files, it displays a line like this:
1.1       anton    14870: 
                   14871: @example
                   14872:      78DC         BFFFFA50         BFFFFA40
                   14873: @end example
                   14874: 
                   14875: This means that at offset $78dc from @code{forthstart}, one input image
                   14876: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   14877: cannot be represented correctly in the output image, you should examine
                   14878: these places in the dictionary and verify that these cells are dead
                   14879: (i.e., not read before they are written).
1.39      anton    14880: 
                   14881: @cindex --application, @code{gforthmi} option
                   14882: If you insert the option @code{--application} in front of the image file
                   14883: name, you will get an image that uses the @code{--appl-image} option
                   14884: instead of the @code{--image-file} option (@pxref{Invoking
                   14885: Gforth}). When you execute such an image on Unix (by typing the image
                   14886: name as command), the Gforth engine will pass all options to the image
                   14887: instead of trying to interpret them as engine options.
1.1       anton    14888: 
1.27      crook    14889: If you type @file{gforthmi} with no arguments, it prints some usage
                   14890: instructions.
                   14891: 
1.1       anton    14892: @cindex @code{savesystem} during @file{gforthmi}
                   14893: @cindex @code{bye} during @file{gforthmi}
                   14894: @cindex doubly indirect threaded code
1.44      crook    14895: @cindex environment variables
                   14896: @cindex @code{GFORTHD} -- environment variable
                   14897: @cindex @code{GFORTH} -- environment variable
1.1       anton    14898: @cindex @code{gforth-ditc}
1.29      crook    14899: There are a few wrinkles: After processing the passed @i{options}, the
1.1       anton    14900: words @code{savesystem} and @code{bye} must be visible. A special doubly
                   14901: indirect threaded version of the @file{gforth} executable is used for
1.62      crook    14902: creating the non-relocatable images; you can pass the exact filename of
1.1       anton    14903: this executable through the environment variable @code{GFORTHD}
                   14904: (default: @file{gforth-ditc}); if you pass a version that is not doubly
                   14905: indirect threaded, you will not get a fully relocatable image, but a
1.27      crook    14906: data-relocatable image (because there is no code address offset). The
                   14907: normal @file{gforth} executable is used for creating the relocatable
                   14908: image; you can pass the exact filename of this executable through the
                   14909: environment variable @code{GFORTH}.
1.1       anton    14910: 
                   14911: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   14912: @subsection @file{cross.fs}
                   14913: @cindex @file{cross.fs}
                   14914: @cindex cross-compiler
                   14915: @cindex metacompiler
1.47      crook    14916: @cindex target compiler
1.1       anton    14917: 
                   14918: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47      crook    14919: programming language (@pxref{Cross Compiler}).
1.1       anton    14920: 
1.47      crook    14921: @code{cross} allows you to create image files for machines with
1.1       anton    14922: different data sizes and data formats than the one used for generating
                   14923: the image file. You can also use it to create an application image that
                   14924: does not contain a Forth compiler. These features are bought with
                   14925: restrictions and inconveniences in programming. E.g., addresses have to
                   14926: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   14927: order to make the code relocatable.
                   14928: 
                   14929: 
                   14930: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   14931: @section Stack and Dictionary Sizes
                   14932: @cindex image file, stack and dictionary sizes
                   14933: @cindex dictionary size default
                   14934: @cindex stack size default
                   14935: 
                   14936: If you invoke Gforth with a command line flag for the size
                   14937: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   14938: dictionary. If you save the dictionary with @code{savesystem} or create
                   14939: an image with @file{gforthmi}, this size will become the default
                   14940: for the resulting image file. E.g., the following will create a
1.21      crook    14941: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1       anton    14942: 
                   14943: @example
                   14944: gforthmi gforth.fi -m 1M
                   14945: @end example
                   14946: 
                   14947: In other words, if you want to set the default size for the dictionary
                   14948: and the stacks of an image, just invoke @file{gforthmi} with the
                   14949: appropriate options when creating the image.
                   14950: 
                   14951: @cindex stack size, cache-friendly
                   14952: Note: For cache-friendly behaviour (i.e., good performance), you should
                   14953: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   14954: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   14955: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   14956: 
                   14957: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   14958: @section Running Image Files
                   14959: @cindex running image files
                   14960: @cindex invoking image files
                   14961: @cindex image file invocation
                   14962: 
                   14963: @cindex -i, invoke image file
                   14964: @cindex --image file, invoke image file
1.29      crook    14965: You can invoke Gforth with an image file @i{image} instead of the
1.1       anton    14966: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   14967: @example
1.29      crook    14968: gforth -i @i{image}
1.1       anton    14969: @end example
                   14970: 
                   14971: @cindex executable image file
1.26      crook    14972: @cindex image file, executable
1.1       anton    14973: If your operating system supports starting scripts with a line of the
                   14974: form @code{#! ...}, you just have to type the image file name to start
                   14975: Gforth with this image file (note that the file extension @code{.fi} is
1.29      crook    14976: just a convention). I.e., to run Gforth with the image file @i{image},
                   14977: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27      crook    14978: This works because every @code{.fi} file starts with a line of this
                   14979: format:
                   14980: 
                   14981: @example
                   14982: #! /usr/local/bin/gforth-0.4.0 -i
                   14983: @end example
                   14984: 
                   14985: The file and pathname for the Gforth engine specified on this line is
                   14986: the specific Gforth executable that it was built against; i.e. the value
                   14987: of the environment variable @code{GFORTH} at the time that
                   14988: @file{gforthmi} was executed.
1.1       anton    14989: 
1.27      crook    14990: You can make use of the same shell capability to make a Forth source
                   14991: file into an executable. For example, if you place this text in a file:
1.26      crook    14992: 
                   14993: @example
                   14994: #! /usr/local/bin/gforth
                   14995: 
                   14996: ." Hello, world" CR
                   14997: bye
                   14998: @end example
                   14999: 
                   15000: @noindent
1.27      crook    15001: and then make the file executable (chmod +x in Unix), you can run it
1.26      crook    15002: directly from the command line. The sequence @code{#!} is used in two
                   15003: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29      crook    15004: system@footnote{The Unix kernel actually recognises two types of files:
                   15005: executable files and files of data, where the data is processed by an
                   15006: interpreter that is specified on the ``interpreter line'' -- the first
                   15007: line of the file, starting with the sequence #!. There may be a small
                   15008: limit (e.g., 32) on the number of characters that may be specified on
                   15009: the interpreter line.} secondly it is treated as a comment character by
                   15010: Gforth. Because of the second usage, a space is required between
1.80      anton    15011: @code{#!} and the path to the executable (moreover, some Unixes
                   15012: require the sequence @code{#! /}).
1.27      crook    15013: 
                   15014: The disadvantage of this latter technique, compared with using
1.80      anton    15015: @file{gforthmi}, is that it is slightly slower; the Forth source code is
                   15016: compiled on-the-fly, each time the program is invoked.
1.26      crook    15017: 
1.1       anton    15018: doc-#!
                   15019: 
1.44      crook    15020: 
1.1       anton    15021: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   15022: @section Modifying the Startup Sequence
                   15023: @cindex startup sequence for image file
                   15024: @cindex image file initialization sequence
                   15025: @cindex initialization sequence of image file
                   15026: 
1.120     anton    15027: You can add your own initialization to the startup sequence of an image
                   15028: through the deferred word @code{'cold}. @code{'cold} is invoked just
                   15029: before the image-specific command line processing (i.e., loading files
                   15030: and evaluating (@code{-e}) strings) starts.
1.1       anton    15031: 
                   15032: A sequence for adding your initialization usually looks like this:
                   15033: 
                   15034: @example
                   15035: :noname
                   15036:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   15037:     ... \ your stuff
                   15038: ; IS 'cold
                   15039: @end example
                   15040: 
1.157     anton    15041: After @code{'cold}, Gforth processes the image options
                   15042: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
                   15043: another deferred word.  This normally prints Gforth's startup message
                   15044: and does nothing else.
                   15045: 
1.1       anton    15046: @cindex turnkey image files
1.26      crook    15047: @cindex image file, turnkey applications
1.157     anton    15048: So, if you want to make a turnkey image (i.e., an image for an
                   15049: application instead of an extended Forth system), you can do this in
                   15050: two ways:
                   15051: 
                   15052: @itemize @bullet
                   15053: 
                   15054: @item
                   15055: If you want to do your interpretation of the OS command-line
                   15056: arguments, hook into @code{'cold}.  In that case you probably also
                   15057: want to build the image with @code{gforthmi --application}
                   15058: (@pxref{gforthmi}) to keep the engine from processing OS command line
                   15059: options.  You can then do your own command-line processing with
                   15060: @code{next-arg} 
                   15061: 
                   15062: @item
                   15063: If you want to have the normal Gforth processing of OS command-line
                   15064: arguments, hook into @code{bootmessage}.
                   15065: 
                   15066: @end itemize
                   15067: 
                   15068: In either case, you probably do not want the word that you execute in
                   15069: these hooks to exit normally, but use @code{bye} or @code{throw}.
                   15070: Otherwise the Gforth startup process would continue and eventually
                   15071: present the Forth command line to the user.
1.26      crook    15072: 
                   15073: doc-'cold
1.157     anton    15074: doc-bootmessage
1.44      crook    15075: 
1.1       anton    15076: @c ******************************************************************
1.113     anton    15077: @node Engine, Cross Compiler, Image Files, Top
1.1       anton    15078: @chapter Engine
                   15079: @cindex engine
                   15080: @cindex virtual machine
                   15081: 
1.26      crook    15082: Reading this chapter is not necessary for programming with Gforth. It
1.1       anton    15083: may be helpful for finding your way in the Gforth sources.
                   15084: 
1.109     anton    15085: The ideas in this section have also been published in the following
                   15086: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
                   15087: Forth-Tagung '93; M. Anton Ertl,
                   15088: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
                   15089: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
                   15090: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
                   15091: Threaded code variations and optimizations (extended version)}},
                   15092: Forth-Tagung '02.
1.1       anton    15093: 
                   15094: @menu
                   15095: * Portability::                 
                   15096: * Threading::                   
                   15097: * Primitives::                  
                   15098: * Performance::                 
                   15099: @end menu
                   15100: 
                   15101: @node Portability, Threading, Engine, Engine
                   15102: @section Portability
                   15103: @cindex engine portability
                   15104: 
1.26      crook    15105: An important goal of the Gforth Project is availability across a wide
                   15106: range of personal machines. fig-Forth, and, to a lesser extent, F83,
                   15107: achieved this goal by manually coding the engine in assembly language
                   15108: for several then-popular processors. This approach is very
                   15109: labor-intensive and the results are short-lived due to progress in
                   15110: computer architecture.
1.1       anton    15111: 
                   15112: @cindex C, using C for the engine
                   15113: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   15114: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   15115: particularly popular for UNIX-based Forths due to the large variety of
                   15116: architectures of UNIX machines. Unfortunately an implementation in C
                   15117: does not mix well with the goals of efficiency and with using
                   15118: traditional techniques: Indirect or direct threading cannot be expressed
                   15119: in C, and switch threading, the fastest technique available in C, is
                   15120: significantly slower. Another problem with C is that it is very
                   15121: cumbersome to express double integer arithmetic.
                   15122: 
                   15123: @cindex GNU C for the engine
                   15124: @cindex long long
                   15125: Fortunately, there is a portable language that does not have these
                   15126: limitations: GNU C, the version of C processed by the GNU C compiler
                   15127: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   15128: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   15129: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   15130: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   15131: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109     anton    15132: double numbers on many systems.  GNU C is freely available on all
1.1       anton    15133: important (and many unimportant) UNIX machines, VMS, 80386s running
                   15134: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   15135: on all these machines.
                   15136: 
                   15137: Writing in a portable language has the reputation of producing code that
                   15138: is slower than assembly. For our Forth engine we repeatedly looked at
                   15139: the code produced by the compiler and eliminated most compiler-induced
                   15140: inefficiencies by appropriate changes in the source code.
                   15141: 
                   15142: @cindex explicit register declarations
                   15143: @cindex --enable-force-reg, configuration flag
                   15144: @cindex -DFORCE_REG
                   15145: However, register allocation cannot be portably influenced by the
                   15146: programmer, leading to some inefficiencies on register-starved
                   15147: machines. We use explicit register declarations (@pxref{Explicit Reg
                   15148: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   15149: improve the speed on some machines. They are turned on by using the
                   15150: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   15151: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   15152: machine, but also on the compiler version: On some machines some
                   15153: compiler versions produce incorrect code when certain explicit register
                   15154: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   15155: 
                   15156: @node Threading, Primitives, Portability, Engine
                   15157: @section Threading
                   15158: @cindex inner interpreter implementation
                   15159: @cindex threaded code implementation
                   15160: 
                   15161: @cindex labels as values
                   15162: GNU C's labels as values extension (available since @code{gcc-2.0},
                   15163: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29      crook    15164: makes it possible to take the address of @i{label} by writing
                   15165: @code{&&@i{label}}.  This address can then be used in a statement like
                   15166: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1       anton    15167: @code{goto x}.
                   15168: 
1.26      crook    15169: @cindex @code{NEXT}, indirect threaded
1.1       anton    15170: @cindex indirect threaded inner interpreter
                   15171: @cindex inner interpreter, indirect threaded
1.26      crook    15172: With this feature an indirect threaded @code{NEXT} looks like:
1.1       anton    15173: @example
                   15174: cfa = *ip++;
                   15175: ca = *cfa;
                   15176: goto *ca;
                   15177: @end example
                   15178: @cindex instruction pointer
                   15179: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   15180: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   15181: execution token and points to the code field of the next word to be
                   15182: executed; The @code{ca} (code address) fetched from there points to some
                   15183: executable code, e.g., a primitive or the colon definition handler
                   15184: @code{docol}.
                   15185: 
1.26      crook    15186: @cindex @code{NEXT}, direct threaded
1.1       anton    15187: @cindex direct threaded inner interpreter
                   15188: @cindex inner interpreter, direct threaded
                   15189: Direct threading is even simpler:
                   15190: @example
                   15191: ca = *ip++;
                   15192: goto *ca;
                   15193: @end example
                   15194: 
                   15195: Of course we have packaged the whole thing neatly in macros called
1.26      crook    15196: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1       anton    15197: 
                   15198: @menu
                   15199: * Scheduling::                  
                   15200: * Direct or Indirect Threaded?::  
1.109     anton    15201: * Dynamic Superinstructions::   
1.1       anton    15202: * DOES>::                       
                   15203: @end menu
                   15204: 
                   15205: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   15206: @subsection Scheduling
                   15207: @cindex inner interpreter optimization
                   15208: 
                   15209: There is a little complication: Pipelined and superscalar processors,
                   15210: i.e., RISC and some modern CISC machines can process independent
                   15211: instructions while waiting for the results of an instruction. The
                   15212: compiler usually reorders (schedules) the instructions in a way that
                   15213: achieves good usage of these delay slots. However, on our first tries
                   15214: the compiler did not do well on scheduling primitives. E.g., for
                   15215: @code{+} implemented as
                   15216: @example
                   15217: n=sp[0]+sp[1];
                   15218: sp++;
                   15219: sp[0]=n;
                   15220: NEXT;
                   15221: @end example
1.81      anton    15222: the @code{NEXT} comes strictly after the other code, i.e., there is
                   15223: nearly no scheduling. After a little thought the problem becomes clear:
                   15224: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21      crook    15225: addresses (and the version of @code{gcc} we used would not know it even
                   15226: if it was possible), so it could not move the load of the cfa above the
                   15227: store to the TOS. Indeed the pointers could be the same, if code on or
                   15228: very near the top of stack were executed. In the interest of speed we
                   15229: chose to forbid this probably unused ``feature'' and helped the compiler
1.81      anton    15230: in scheduling: @code{NEXT} is divided into several parts:
                   15231: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
                   15232: like:
1.1       anton    15233: @example
1.81      anton    15234: NEXT_P0;
1.1       anton    15235: n=sp[0]+sp[1];
                   15236: sp++;
                   15237: NEXT_P1;
                   15238: sp[0]=n;
                   15239: NEXT_P2;
                   15240: @end example
                   15241: 
1.81      anton    15242: There are various schemes that distribute the different operations of
                   15243: NEXT between these parts in several ways; in general, different schemes
                   15244: perform best on different processors.  We use a scheme for most
                   15245: architectures that performs well for most processors of this
1.109     anton    15246: architecture; in the future we may switch to benchmarking and chosing
1.81      anton    15247: the scheme on installation time.
                   15248: 
1.1       anton    15249: 
1.109     anton    15250: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1       anton    15251: @subsection Direct or Indirect Threaded?
                   15252: @cindex threading, direct or indirect?
                   15253: 
1.109     anton    15254: Threaded forth code consists of references to primitives (simple machine
                   15255: code routines like @code{+}) and to non-primitives (e.g., colon
                   15256: definitions, variables, constants); for a specific class of
                   15257: non-primitives (e.g., variables) there is one code routine (e.g.,
                   15258: @code{dovar}), but each variable needs a separate reference to its data.
                   15259: 
                   15260: Traditionally Forth has been implemented as indirect threaded code,
                   15261: because this allows to use only one cell to reference a non-primitive
                   15262: (basically you point to the data, and find the code address there).
                   15263: 
                   15264: @cindex primitive-centric threaded code
                   15265: However, threaded code in Gforth (since 0.6.0) uses two cells for
                   15266: non-primitives, one for the code address, and one for the data address;
                   15267: the data pointer is an immediate argument for the virtual machine
                   15268: instruction represented by the code address.  We call this
                   15269: @emph{primitive-centric} threaded code, because all code addresses point
                   15270: to simple primitives.  E.g., for a variable, the code address is for
                   15271: @code{lit} (also used for integer literals like @code{99}).
                   15272: 
                   15273: Primitive-centric threaded code allows us to use (faster) direct
                   15274: threading as dispatch method, completely portably (direct threaded code
                   15275: in Gforth before 0.6.0 required architecture-specific code).  It also
                   15276: eliminates the performance problems related to I-cache consistency that
                   15277: 386 implementations have with direct threaded code, and allows
                   15278: additional optimizations.
                   15279: 
                   15280: @cindex hybrid direct/indirect threaded code
                   15281: There is a catch, however: the @var{xt} parameter of @code{execute} can
                   15282: occupy only one cell, so how do we pass non-primitives with their code
                   15283: @emph{and} data addresses to them?  Our answer is to use indirect
                   15284: threaded dispatch for @code{execute} and other words that use a
                   15285: single-cell xt.  So, normal threaded code in colon definitions uses
                   15286: direct threading, and @code{execute} and similar words, which dispatch
                   15287: to xts on the data stack, use indirect threaded code.  We call this
                   15288: @emph{hybrid direct/indirect} threaded code.
                   15289: 
                   15290: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
                   15291: @cindex gforth engine
                   15292: @cindex gforth-fast engine
                   15293: The engines @command{gforth} and @command{gforth-fast} use hybrid
                   15294: direct/indirect threaded code.  This means that with these engines you
                   15295: cannot use @code{,} to compile an xt.  Instead, you have to use
                   15296: @code{compile,}.
                   15297: 
                   15298: @cindex gforth-itc engine
1.115     anton    15299: If you want to compile xts with @code{,}, use @command{gforth-itc}.
                   15300: This engine uses plain old indirect threaded code.  It still compiles in
                   15301: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109     anton    15302: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115     anton    15303: ... [}).  If you want to do that, you have to use @command{gforth-itc}
1.109     anton    15304: and execute @code{' , is compile,}.  Your program can check if it is
                   15305: running on a hybrid direct/indirect threaded engine or a pure indirect
                   15306: threaded engine with @code{threading-method} (@pxref{Threading Words}).
                   15307: 
                   15308: 
                   15309: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
                   15310: @subsection Dynamic Superinstructions
                   15311: @cindex Dynamic superinstructions with replication
                   15312: @cindex Superinstructions
                   15313: @cindex Replication
                   15314: 
                   15315: The engines @command{gforth} and @command{gforth-fast} use another
                   15316: optimization: Dynamic superinstructions with replication.  As an
                   15317: example, consider the following colon definition:
                   15318: 
                   15319: @example
                   15320: : squared ( n1 -- n2 )
                   15321:   dup * ;
                   15322: @end example
                   15323: 
                   15324: Gforth compiles this into the threaded code sequence
                   15325: 
                   15326: @example
                   15327: dup
                   15328: *
                   15329: ;s
                   15330: @end example
                   15331: 
                   15332: In normal direct threaded code there is a code address occupying one
                   15333: cell for each of these primitives.  Each code address points to a
                   15334: machine code routine, and the interpreter jumps to this machine code in
                   15335: order to execute the primitive.  The routines for these three
                   15336: primitives are (in @command{gforth-fast} on the 386):
                   15337: 
                   15338: @example
                   15339: Code dup  
                   15340: ( $804B950 )  add     esi , # -4  \ $83 $C6 $FC 
                   15341: ( $804B953 )  add     ebx , # 4  \ $83 $C3 $4 
                   15342: ( $804B956 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
                   15343: ( $804B959 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   15344: end-code
                   15345: Code *  
                   15346: ( $804ACC4 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
                   15347: ( $804ACC7 )  add     esi , # 4  \ $83 $C6 $4 
                   15348: ( $804ACCA )  add     ebx , # 4  \ $83 $C3 $4 
                   15349: ( $804ACCD )  imul    ecx , eax  \ $F $AF $C8 
                   15350: ( $804ACD0 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   15351: end-code
                   15352: Code ;s  
                   15353: ( $804A693 )  mov     eax , dword ptr [edi]  \ $8B $7 
                   15354: ( $804A695 )  add     edi , # 4  \ $83 $C7 $4 
                   15355: ( $804A698 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
                   15356: ( $804A69B )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   15357: end-code
                   15358: @end example
                   15359: 
                   15360: With dynamic superinstructions and replication the compiler does not
                   15361: just lay down the threaded code, but also copies the machine code
                   15362: fragments, usually without the jump at the end.
                   15363: 
                   15364: @example
                   15365: ( $4057D27D )  add     esi , # -4  \ $83 $C6 $FC 
                   15366: ( $4057D280 )  add     ebx , # 4  \ $83 $C3 $4 
                   15367: ( $4057D283 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
                   15368: ( $4057D286 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
                   15369: ( $4057D289 )  add     esi , # 4  \ $83 $C6 $4 
                   15370: ( $4057D28C )  add     ebx , # 4  \ $83 $C3 $4 
                   15371: ( $4057D28F )  imul    ecx , eax  \ $F $AF $C8 
                   15372: ( $4057D292 )  mov     eax , dword ptr [edi]  \ $8B $7 
                   15373: ( $4057D294 )  add     edi , # 4  \ $83 $C7 $4 
                   15374: ( $4057D297 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
                   15375: ( $4057D29A )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   15376: @end example
                   15377: 
                   15378: Only when a threaded-code control-flow change happens (e.g., in
                   15379: @code{;s}), the jump is appended.  This optimization eliminates many of
                   15380: these jumps and makes the rest much more predictable.  The speedup
                   15381: depends on the processor and the application; on the Athlon and Pentium
                   15382: III this optimization typically produces a speedup by a factor of 2.
                   15383: 
                   15384: The code addresses in the direct-threaded code are set to point to the
                   15385: appropriate points in the copied machine code, in this example like
                   15386: this:
1.1       anton    15387: 
1.109     anton    15388: @example
                   15389: primitive  code address
                   15390:    dup       $4057D27D
                   15391:    *         $4057D286
                   15392:    ;s        $4057D292
                   15393: @end example
                   15394: 
                   15395: Thus there can be threaded-code jumps to any place in this piece of
                   15396: code.  This also simplifies decompilation quite a bit.
                   15397: 
                   15398: @cindex --no-dynamic command-line option
                   15399: @cindex --no-super command-line option
                   15400: You can disable this optimization with @option{--no-dynamic}.  You can
                   15401: use the copying without eliminating the jumps (i.e., dynamic
                   15402: replication, but without superinstructions) with @option{--no-super};
                   15403: this gives the branch prediction benefit alone; the effect on
1.110     anton    15404: performance depends on the CPU; on the Athlon and Pentium III the
                   15405: speedup is a little less than for dynamic superinstructions with
                   15406: replication.
                   15407: 
                   15408: @cindex patching threaded code
                   15409: One use of these options is if you want to patch the threaded code.
                   15410: With superinstructions, many of the dispatch jumps are eliminated, so
                   15411: patching often has no effect.  These options preserve all the dispatch
                   15412: jumps.
1.109     anton    15413: 
                   15414: @cindex --dynamic command-line option
1.110     anton    15415: On some machines dynamic superinstructions are disabled by default,
                   15416: because it is unsafe on these machines.  However, if you feel
                   15417: adventurous, you can enable it with @option{--dynamic}.
1.109     anton    15418: 
                   15419: @node DOES>,  , Dynamic Superinstructions, Threading
1.1       anton    15420: @subsection DOES>
                   15421: @cindex @code{DOES>} implementation
                   15422: 
1.26      crook    15423: @cindex @code{dodoes} routine
                   15424: @cindex @code{DOES>}-code
1.1       anton    15425: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   15426: the chunk of code executed by every word defined by a
1.109     anton    15427: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
                   15428: this is only needed if the xt of the word is @code{execute}d. The main
                   15429: problem here is: How to find the Forth code to be executed, i.e. the
                   15430: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
                   15431: solutions:
1.1       anton    15432: 
1.21      crook    15433: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109     anton    15434: @code{DOES>}-code address is stored in the cell after the code address
                   15435: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
                   15436: illegal in the Forth-79 and all later standards, because in fig-Forth
                   15437: this address lies in the body (which is illegal in these
                   15438: standards). However, by making the code field larger for all words this
                   15439: solution becomes legal again.  We use this approach.  Leaving a cell
                   15440: unused in most words is a bit wasteful, but on the machines we are
                   15441: targeting this is hardly a problem.
                   15442: 
1.1       anton    15443: 
                   15444: @node Primitives, Performance, Threading, Engine
                   15445: @section Primitives
                   15446: @cindex primitives, implementation
                   15447: @cindex virtual machine instructions, implementation
                   15448: 
                   15449: @menu
                   15450: * Automatic Generation::        
                   15451: * TOS Optimization::            
                   15452: * Produced code::               
                   15453: @end menu
                   15454: 
                   15455: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   15456: @subsection Automatic Generation
                   15457: @cindex primitives, automatic generation
                   15458: 
                   15459: @cindex @file{prims2x.fs}
1.109     anton    15460: 
1.1       anton    15461: Since the primitives are implemented in a portable language, there is no
                   15462: longer any need to minimize the number of primitives. On the contrary,
                   15463: having many primitives has an advantage: speed. In order to reduce the
                   15464: number of errors in primitives and to make programming them easier, we
1.109     anton    15465: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
                   15466: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
                   15467: generates most (and sometimes all) of the C code for a primitive from
                   15468: the stack effect notation.  The source for a primitive has the following
                   15469: form:
1.1       anton    15470: 
                   15471: @cindex primitive source format
                   15472: @format
1.58      anton    15473: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
1.29      crook    15474: [@code{""}@i{glossary entry}@code{""}]
                   15475: @i{C code}
1.1       anton    15476: [@code{:}
1.29      crook    15477: @i{Forth code}]
1.1       anton    15478: @end format
                   15479: 
                   15480: The items in brackets are optional. The category and glossary fields
                   15481: are there for generating the documentation, the Forth code is there
                   15482: for manual implementations on machines without GNU C. E.g., the source
                   15483: for the primitive @code{+} is:
                   15484: @example
1.58      anton    15485: +    ( n1 n2 -- n )   core    plus
1.1       anton    15486: n = n1+n2;
                   15487: @end example
                   15488: 
                   15489: This looks like a specification, but in fact @code{n = n1+n2} is C
                   15490: code. Our primitive generation tool extracts a lot of information from
                   15491: the stack effect notations@footnote{We use a one-stack notation, even
                   15492: though we have separate data and floating-point stacks; The separate
                   15493: notation can be generated easily from the unified notation.}: The number
                   15494: of items popped from and pushed on the stack, their type, and by what
                   15495: name they are referred to in the C code. It then generates a C code
                   15496: prelude and postlude for each primitive. The final C code for @code{+}
                   15497: looks like this:
                   15498: 
                   15499: @example
1.46      pazsan   15500: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
1.1       anton    15501: /*  */                          /* documentation */
1.81      anton    15502: NAME("+")                       /* debugging output (with -DDEBUG) */
1.1       anton    15503: @{
                   15504: DEF_CA                          /* definition of variable ca (indirect threading) */
                   15505: Cell n1;                        /* definitions of variables */
                   15506: Cell n2;
                   15507: Cell n;
1.81      anton    15508: NEXT_P0;                        /* NEXT part 0 */
1.1       anton    15509: n1 = (Cell) sp[1];              /* input */
                   15510: n2 = (Cell) TOS;
                   15511: sp += 1;                        /* stack adjustment */
                   15512: @{
                   15513: n = n1+n2;                      /* C code taken from the source */
                   15514: @}
                   15515: NEXT_P1;                        /* NEXT part 1 */
                   15516: TOS = (Cell)n;                  /* output */
                   15517: NEXT_P2;                        /* NEXT part 2 */
                   15518: @}
                   15519: @end example
                   15520: 
                   15521: This looks long and inefficient, but the GNU C compiler optimizes quite
                   15522: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   15523: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   15524: using them as intermediate storage also adds no cost.
                   15525: 
1.26      crook    15526: There are also other optimizations that are not illustrated by this
                   15527: example: assignments between simple variables are usually for free (copy
1.1       anton    15528: propagation). If one of the stack items is not used by the primitive
                   15529: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   15530: (dead code elimination). On the other hand, there are some things that
                   15531: the compiler does not do, therefore they are performed by
                   15532: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   15533: a stack item to the place where it just came from (e.g., @code{over}).
                   15534: 
                   15535: While programming a primitive is usually easy, there are a few cases
                   15536: where the programmer has to take the actions of the generator into
                   15537: account, most notably @code{?dup}, but also words that do not (always)
1.26      crook    15538: fall through to @code{NEXT}.
1.109     anton    15539: 
                   15540: For more information
1.1       anton    15541: 
                   15542: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   15543: @subsection TOS Optimization
                   15544: @cindex TOS optimization for primitives
                   15545: @cindex primitives, keeping the TOS in a register
                   15546: 
                   15547: An important optimization for stack machine emulators, e.g., Forth
                   15548: engines, is keeping  one or more of the top stack items in
1.29      crook    15549: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
                   15550: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1       anton    15551: @itemize @bullet
                   15552: @item
1.29      crook    15553: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1       anton    15554: due to fewer loads from and stores to the stack.
1.29      crook    15555: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
                   15556: @i{y<n}, due to additional moves between registers.
1.1       anton    15557: @end itemize
                   15558: 
                   15559: @cindex -DUSE_TOS
                   15560: @cindex -DUSE_NO_TOS
                   15561: In particular, keeping one item in a register is never a disadvantage,
                   15562: if there are enough registers. Keeping two items in registers is a
                   15563: disadvantage for frequent words like @code{?branch}, constants,
                   15564: variables, literals and @code{i}. Therefore our generator only produces
                   15565: code that keeps zero or one items in registers. The generated C code
                   15566: covers both cases; the selection between these alternatives is made at
                   15567: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   15568: code for @code{+} is just a simple variable name in the one-item case,
                   15569: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   15570: GNU C compiler tries to keep simple variables like @code{TOS} in
                   15571: registers, and it usually succeeds, if there are enough registers.
                   15572: 
                   15573: @cindex -DUSE_FTOS
                   15574: @cindex -DUSE_NO_FTOS
                   15575: The primitive generator performs the TOS optimization for the
                   15576: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   15577: operations the benefit of this optimization is even larger:
                   15578: floating-point operations take quite long on most processors, but can be
                   15579: performed in parallel with other operations as long as their results are
                   15580: not used. If the FP-TOS is kept in a register, this works. If
                   15581: it is kept on the stack, i.e., in memory, the store into memory has to
                   15582: wait for the result of the floating-point operation, lengthening the
                   15583: execution time of the primitive considerably.
                   15584: 
                   15585: The TOS optimization makes the automatic generation of primitives a
                   15586: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   15587: @code{TOS} is not sufficient. There are some special cases to
                   15588: consider:
                   15589: @itemize @bullet
                   15590: @item In the case of @code{dup ( w -- w w )} the generator must not
                   15591: eliminate the store to the original location of the item on the stack,
                   15592: if the TOS optimization is turned on.
                   15593: @item Primitives with stack effects of the form @code{--}
1.29      crook    15594: @i{out1}...@i{outy} must store the TOS to the stack at the start.
                   15595: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1       anton    15596: must load the TOS from the stack at the end. But for the null stack
                   15597: effect @code{--} no stores or loads should be generated.
                   15598: @end itemize
                   15599: 
                   15600: @node Produced code,  , TOS Optimization, Primitives
                   15601: @subsection Produced code
                   15602: @cindex primitives, assembly code listing
                   15603: 
                   15604: @cindex @file{engine.s}
                   15605: To see what assembly code is produced for the primitives on your machine
                   15606: with your compiler and your flag settings, type @code{make engine.s} and
1.81      anton    15607: look at the resulting file @file{engine.s}.  Alternatively, you can also
                   15608: disassemble the code of primitives with @code{see} on some architectures.
1.1       anton    15609: 
                   15610: @node  Performance,  , Primitives, Engine
                   15611: @section Performance
                   15612: @cindex performance of some Forth interpreters
                   15613: @cindex engine performance
                   15614: @cindex benchmarking Forth systems
                   15615: @cindex Gforth performance
                   15616: 
                   15617: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112     anton    15618: impossible to write a significantly faster threaded-code engine.
1.1       anton    15619: 
                   15620: On register-starved machines like the 386 architecture processors
                   15621: improvements are possible, because @code{gcc} does not utilize the
                   15622: registers as well as a human, even with explicit register declarations;
                   15623: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   15624: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   15625: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40      anton    15626: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
                   15627: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
                   15628: registers fit in real registers (and we can even afford to use the TOS
                   15629: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112     anton    15630: earlier results.  And dynamic superinstructions provide another speedup
                   15631: (but only around a factor 1.2 on the 486).
1.1       anton    15632: 
                   15633: @cindex Win32Forth performance
                   15634: @cindex NT Forth performance
                   15635: @cindex eforth performance
                   15636: @cindex ThisForth performance
                   15637: @cindex PFE performance
                   15638: @cindex TILE performance
1.81      anton    15639: The potential advantage of assembly language implementations is not
1.112     anton    15640: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81      anton    15641: (direct threaded, compiled with @code{gcc-2.95.1} and
                   15642: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
                   15643: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
                   15644: (with and without peephole (aka pinhole) optimization of the threaded
                   15645: code); all these systems were written in assembly language. We also
                   15646: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
                   15647: with @code{gcc-2.6.3} with the default configuration for Linux:
                   15648: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
                   15649: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
                   15650: employs peephole optimization of the threaded code) and TILE (compiled
                   15651: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
                   15652: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
                   15653: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
                   15654: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
                   15655: then extended it to run the benchmarks, added the peephole optimizer,
                   15656: ran the benchmarks and reported the results.
1.40      anton    15657: 
1.1       anton    15658: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   15659: matrix multiplication come from the Stanford integer benchmarks and have
                   15660: been translated into Forth by Martin Fraeman; we used the versions
                   15661: included in the TILE Forth package, but with bigger data set sizes; and
                   15662: a recursive Fibonacci number computation for benchmarking calling
                   15663: performance. The following table shows the time taken for the benchmarks
                   15664: scaled by the time taken by Gforth (in other words, it shows the speedup
                   15665: factor that Gforth achieved over the other systems).
                   15666: 
                   15667: @example
1.112     anton    15668: relative       Win32-    NT       eforth       This-      
                   15669: time     Gforth Forth Forth eforth  +opt   PFE Forth  TILE
                   15670: sieve      1.00  2.16  1.78   2.16  1.32  2.46  4.96 13.37
                   15671: bubble     1.00  1.93  2.07   2.18  1.29  2.21        5.70
                   15672: matmul     1.00  1.92  1.76   1.90  0.96  2.06        5.32
                   15673: fib        1.00  2.32  2.03   1.86  1.31  2.64  4.55  6.54
1.1       anton    15674: @end example
                   15675: 
1.26      crook    15676: You may be quite surprised by the good performance of Gforth when
                   15677: compared with systems written in assembly language. One important reason
                   15678: for the disappointing performance of these other systems is probably
                   15679: that they are not written optimally for the 486 (e.g., they use the
                   15680: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
                   15681: but costly method for relocating the Forth image: like @code{cforth}, it
                   15682: computes the actual addresses at run time, resulting in two address
                   15683: computations per @code{NEXT} (@pxref{Image File Background}).
                   15684: 
1.1       anton    15685: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   15686: explained with the self-imposed restriction of the latter systems to
                   15687: standard C, which makes efficient threading impossible (however, the
1.4       anton    15688: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    15689: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   15690: Moreover, current C compilers have a hard time optimizing other aspects
                   15691: of the ThisForth and the TILE source.
                   15692: 
1.26      crook    15693: The performance of Gforth on 386 architecture processors varies widely
                   15694: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
                   15695: allocate any of the virtual machine registers into real machine
                   15696: registers by itself and would not work correctly with explicit register
1.112     anton    15697: declarations, giving a significantly slower engine (on a 486DX2/66
                   15698: running the Sieve) than the one measured above.
1.1       anton    15699: 
1.26      crook    15700: Note that there have been several releases of Win32Forth since the
                   15701: release presented here, so the results presented above may have little
1.40      anton    15702: predictive value for the performance of Win32Forth today (results for
                   15703: the current release on an i486DX2/66 are welcome).
1.1       anton    15704: 
                   15705: @cindex @file{Benchres}
1.66      anton    15706: In
                   15707: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
                   15708: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1       anton    15709: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66      anton    15710: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
                   15711: several native code systems; that version of Gforth is slower on a 486
1.112     anton    15712: than the version used here. You can find a newer version of these
                   15713: measurements at
1.47      crook    15714: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1       anton    15715: find numbers for Gforth on various machines in @file{Benchres}.
                   15716: 
1.26      crook    15717: @c ******************************************************************
1.113     anton    15718: @c @node Binding to System Library, Cross Compiler, Engine, Top
                   15719: @c @chapter Binding to System Library
1.13      pazsan   15720: 
1.113     anton    15721: @c ****************************************************************
                   15722: @node Cross Compiler, Bugs, Engine, Top
1.14      pazsan   15723: @chapter Cross Compiler
1.47      crook    15724: @cindex @file{cross.fs}
                   15725: @cindex cross-compiler
                   15726: @cindex metacompiler
                   15727: @cindex target compiler
1.13      pazsan   15728: 
1.46      pazsan   15729: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
                   15730: mostly written in Forth, including crucial parts like the outer
                   15731: interpreter and compiler, it needs compiled Forth code to get
                   15732: started. The cross compiler allows to create new images for other
                   15733: architectures, even running under another Forth system.
1.13      pazsan   15734: 
                   15735: @menu
1.67      anton    15736: * Using the Cross Compiler::    
                   15737: * How the Cross Compiler Works::  
1.13      pazsan   15738: @end menu
                   15739: 
1.21      crook    15740: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14      pazsan   15741: @section Using the Cross Compiler
1.46      pazsan   15742: 
                   15743: The cross compiler uses a language that resembles Forth, but isn't. The
                   15744: main difference is that you can execute Forth code after definition,
                   15745: while you usually can't execute the code compiled by cross, because the
                   15746: code you are compiling is typically for a different computer than the
                   15747: one you are compiling on.
                   15748: 
1.81      anton    15749: @c anton: This chapter is somewhat different from waht I would expect: I
                   15750: @c would expect an explanation of the cross language and how to create an
                   15751: @c application image with it.  The section explains some aspects of
                   15752: @c creating a Gforth kernel.
                   15753: 
1.46      pazsan   15754: The Makefile is already set up to allow you to create kernels for new
                   15755: architectures with a simple make command. The generic kernels using the
                   15756: GCC compiled virtual machine are created in the normal build process
                   15757: with @code{make}. To create a embedded Gforth executable for e.g. the
                   15758: 8086 processor (running on a DOS machine), type
                   15759: 
                   15760: @example
                   15761: make kernl-8086.fi
                   15762: @end example
                   15763: 
                   15764: This will use the machine description from the @file{arch/8086}
                   15765: directory to create a new kernel. A machine file may look like that:
                   15766: 
                   15767: @example
                   15768: \ Parameter for target systems                         06oct92py
                   15769: 
                   15770:     4 Constant cell             \ cell size in bytes
                   15771:     2 Constant cell<<           \ cell shift to bytes
                   15772:     5 Constant cell>bit         \ cell shift to bits
                   15773:     8 Constant bits/char        \ bits per character
                   15774:     8 Constant bits/byte        \ bits per byte [default: 8]
                   15775:     8 Constant float            \ bytes per float
                   15776:     8 Constant /maxalign        \ maximum alignment in bytes
                   15777: false Constant bigendian        \ byte order
                   15778: ( true=big, false=little )
                   15779: 
                   15780: include machpc.fs               \ feature list
                   15781: @end example
                   15782: 
                   15783: This part is obligatory for the cross compiler itself, the feature list
                   15784: is used by the kernel to conditionally compile some features in and out,
                   15785: depending on whether the target supports these features.
                   15786: 
                   15787: There are some optional features, if you define your own primitives,
                   15788: have an assembler, or need special, nonstandard preparation to make the
1.81      anton    15789: boot process work. @code{asm-include} includes an assembler,
1.46      pazsan   15790: @code{prims-include} includes primitives, and @code{>boot} prepares for
                   15791: booting.
                   15792: 
                   15793: @example
                   15794: : asm-include    ." Include assembler" cr
                   15795:   s" arch/8086/asm.fs" included ;
                   15796: 
                   15797: : prims-include  ." Include primitives" cr
                   15798:   s" arch/8086/prim.fs" included ;
                   15799: 
                   15800: : >boot          ." Prepare booting" cr
                   15801:   s" ' boot >body into-forth 1+ !" evaluate ;
                   15802: @end example
                   15803: 
                   15804: These words are used as sort of macro during the cross compilation in
1.81      anton    15805: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46      pazsan   15806: be possible --- but more complicated --- to write a new kernel project
                   15807: file, too.
                   15808: 
                   15809: @file{kernel/main.fs} expects the machine description file name on the
                   15810: stack; the cross compiler itself (@file{cross.fs}) assumes that either
                   15811: @code{mach-file} leaves a counted string on the stack, or
                   15812: @code{machine-file} leaves an address, count pair of the filename on the
                   15813: stack.
                   15814: 
                   15815: The feature list is typically controlled using @code{SetValue}, generic
                   15816: files that are used by several projects can use @code{DefaultValue}
                   15817: instead. Both functions work like @code{Value}, when the value isn't
                   15818: defined, but @code{SetValue} works like @code{to} if the value is
                   15819: defined, and @code{DefaultValue} doesn't set anything, if the value is
                   15820: defined.
                   15821: 
                   15822: @example
                   15823: \ generic mach file for pc gforth                       03sep97jaw
                   15824: 
                   15825: true DefaultValue NIL  \ relocating
                   15826: 
                   15827: >ENVIRON
                   15828: 
                   15829: true DefaultValue file          \ controls the presence of the
                   15830:                                 \ file access wordset
                   15831: true DefaultValue OS            \ flag to indicate a operating system
                   15832: 
                   15833: true DefaultValue prims         \ true: primitives are c-code
                   15834: 
                   15835: true DefaultValue floating      \ floating point wordset is present
                   15836: 
                   15837: true DefaultValue glocals       \ gforth locals are present
                   15838:                                 \ will be loaded
                   15839: true DefaultValue dcomps        \ double number comparisons
                   15840: 
                   15841: true DefaultValue hash          \ hashing primitives are loaded/present
                   15842: 
                   15843: true DefaultValue xconds        \ used together with glocals,
                   15844:                                 \ special conditionals supporting gforths'
                   15845:                                 \ local variables
                   15846: true DefaultValue header        \ save a header information
                   15847: 
                   15848: true DefaultValue backtrace     \ enables backtrace code
                   15849: 
                   15850: false DefaultValue ec
                   15851: false DefaultValue crlf
                   15852: 
                   15853: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
                   15854: 
                   15855: &16 KB          DefaultValue stack-size
                   15856: &15 KB &512 +   DefaultValue fstack-size
                   15857: &15 KB          DefaultValue rstack-size
                   15858: &14 KB &512 +   DefaultValue lstack-size
                   15859: @end example
1.13      pazsan   15860: 
1.48      anton    15861: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
1.14      pazsan   15862: @section How the Cross Compiler Works
1.13      pazsan   15863: 
                   15864: @node Bugs, Origin, Cross Compiler, Top
1.21      crook    15865: @appendix Bugs
1.1       anton    15866: @cindex bug reporting
                   15867: 
1.21      crook    15868: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1       anton    15869: 
1.103     anton    15870: If you find a bug, please submit a bug report through
                   15871: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21      crook    15872: 
                   15873: @itemize @bullet
                   15874: @item
1.81      anton    15875: A program (or a sequence of keyboard commands) that reproduces the bug.
                   15876: @item
                   15877: A description of what you think constitutes the buggy behaviour.
                   15878: @item
1.21      crook    15879: The Gforth version used (it is announced at the start of an
                   15880: interactive Gforth session).
                   15881: @item
                   15882: The machine and operating system (on Unix
                   15883: systems @code{uname -a} will report this information).
                   15884: @item
1.81      anton    15885: The installation options (you can find the configure options at the
                   15886: start of @file{config.status}) and configuration (@code{configure}
                   15887: output or @file{config.cache}).
1.21      crook    15888: @item
                   15889: A complete list of changes (if any) you (or your installer) have made to the
                   15890: Gforth sources.
                   15891: @end itemize
1.1       anton    15892: 
                   15893: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   15894: to Report Bugs, gcc.info, GNU C Manual}.
                   15895: 
                   15896: 
1.21      crook    15897: @node Origin, Forth-related information, Bugs, Top
                   15898: @appendix Authors and Ancestors of Gforth
1.1       anton    15899: 
                   15900: @section Authors and Contributors
                   15901: @cindex authors of Gforth
                   15902: @cindex contributors to Gforth
                   15903: 
                   15904: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81      anton    15905: Ertl. The third major author was Jens Wilke.  Neal Crook contributed a
                   15906: lot to the manual.  Assemblers and disassemblers were contributed by
1.161     anton    15907: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
                   15908: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
                   15909: and Stuart Ramsden inspired us with their continuous feedback. Lennart
                   15910: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
                   15911: working on automatic support for calling C libraries. Helpful comments
                   15912: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
                   15913: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
                   15914: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
                   15915: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
                   15916: comments from many others; thank you all, sorry for not listing you
                   15917: here (but digging through my mailbox to extract your names is on my
                   15918: to-do list).
1.1       anton    15919: 
                   15920: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   15921: and autoconf, among others), and to the creators of the Internet: Gforth
1.21      crook    15922: was developed across the Internet, and its authors did not meet
1.20      pazsan   15923: physically for the first 4 years of development.
1.1       anton    15924: 
                   15925: @section Pedigree
1.26      crook    15926: @cindex pedigree of Gforth
1.1       anton    15927: 
1.81      anton    15928: Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
                   15929: significant part of the design of Gforth was prescribed by ANS Forth.
1.1       anton    15930: 
1.20      pazsan   15931: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1       anton    15932: 32 bit native code version of VolksForth for the Atari ST, written
                   15933: mostly by Dietrich Weineck.
                   15934: 
1.81      anton    15935: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
                   15936: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147     anton    15937: the mid-80s and ported to the Atari ST in 1986.  It descends from fig-Forth.
1.1       anton    15938: 
1.147     anton    15939: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   15940: @c Forth-83 standard. !! Pedigree? When?
1.1       anton    15941: 
                   15942: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   15943: 1979. Robert Selzer and Bill Ragsdale developed the original
                   15944: implementation of fig-Forth for the 6502 based on microForth.
                   15945: 
                   15946: The principal architect of microForth was Dean Sanderson. microForth was
                   15947: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   15948: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   15949: Z80.
                   15950: 
                   15951: All earlier Forth systems were custom-made, usually by Charles Moore,
                   15952: who discovered (as he puts it) Forth during the late 60s. The first full
                   15953: Forth existed in 1971.
                   15954: 
1.81      anton    15955: A part of the information in this section comes from
                   15956: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
                   15957: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147     anton    15958: Charles H. Moore, presented at the HOPL-II conference and preprinted
                   15959: in SIGPLAN Notices 28(3), 1993.  You can find more historical and
                   15960: genealogical information about Forth there.  For a more general (and
                   15961: graphical) Forth family tree look see
                   15962: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
                   15963: Forth Family Tree and Timeline}.
1.1       anton    15964: 
1.81      anton    15965: @c ------------------------------------------------------------------
1.113     anton    15966: @node Forth-related information, Licenses, Origin, Top
1.21      crook    15967: @appendix Other Forth-related information
                   15968: @cindex Forth-related information
                   15969: 
1.81      anton    15970: @c anton: I threw most of this stuff out, because it can be found through
                   15971: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21      crook    15972: 
                   15973: @cindex comp.lang.forth
                   15974: @cindex frequently asked questions
1.81      anton    15975: There is an active news group (comp.lang.forth) discussing Forth
                   15976: (including Gforth) and Forth-related issues. Its
                   15977: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
                   15978: (frequently asked questions and their answers) contains a lot of
                   15979: information on Forth.  You should read it before posting to
                   15980: comp.lang.forth.
1.21      crook    15981: 
1.81      anton    15982: The ANS Forth standard is most usable in its
                   15983: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21      crook    15984: 
1.113     anton    15985: @c ---------------------------------------------------
                   15986: @node  Licenses, Word Index, Forth-related information, Top
                   15987: @appendix Licenses
                   15988: 
                   15989: @menu
                   15990: * GNU Free Documentation License::  License for copying this manual.
                   15991: * Copying::                         GPL (for copying this software).
                   15992: @end menu
                   15993: 
                   15994: @include fdl.texi
                   15995: 
                   15996: @include gpl.texi
                   15997: 
                   15998: 
                   15999: 
1.81      anton    16000: @c ------------------------------------------------------------------
1.113     anton    16001: @node Word Index, Concept Index, Licenses, Top
1.1       anton    16002: @unnumbered Word Index
                   16003: 
1.26      crook    16004: This index is a list of Forth words that have ``glossary'' entries
                   16005: within this manual. Each word is listed with its stack effect and
                   16006: wordset.
1.1       anton    16007: 
                   16008: @printindex fn
                   16009: 
1.81      anton    16010: @c anton: the name index seems superfluous given the word and concept indices.
                   16011: 
                   16012: @c @node Name Index, Concept Index, Word Index, Top
                   16013: @c @unnumbered Name Index
1.41      anton    16014: 
1.81      anton    16015: @c This index is a list of Forth words that have ``glossary'' entries
                   16016: @c within this manual.
1.41      anton    16017: 
1.81      anton    16018: @c @printindex ky
1.41      anton    16019: 
1.113     anton    16020: @c -------------------------------------------------------
1.81      anton    16021: @node Concept Index,  , Word Index, Top
1.1       anton    16022: @unnumbered Concept and Word Index
                   16023: 
1.26      crook    16024: Not all entries listed in this index are present verbatim in the
                   16025: text. This index also duplicates, in abbreviated form, all of the words
                   16026: listed in the Word Index (only the names are listed for the words here).
1.1       anton    16027: 
                   16028: @printindex cp
                   16029: 
                   16030: @bye
1.81      anton    16031: 
                   16032: 
1.1       anton    16033: 

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