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

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.32      anton     334: * Input::                       Input
1.112     anton     335: * Pipes::                       How to create your own pipes
1.149     pazsan    336: * Xchars and Unicode::          Non-ASCII characters
1.26      crook     337: 
                    338: Locals
                    339: 
                    340: * Gforth locals::               
                    341: * ANS Forth locals::            
                    342: 
                    343: Gforth locals
                    344: 
                    345: * Where are locals visible by name?::  
                    346: * How long do locals live?::    
1.78      anton     347: * Locals programming style::    
                    348: * Locals implementation::       
1.26      crook     349: 
1.12      anton     350: Structures
                    351: 
                    352: * Why explicit structure support?::  
                    353: * Structure Usage::             
                    354: * Structure Naming Convention::  
                    355: * Structure Implementation::    
                    356: * Structure Glossary::          
                    357: 
                    358: Object-oriented Forth
                    359: 
1.48      anton     360: * Why object-oriented programming?::  
                    361: * Object-Oriented Terminology::  
                    362: * Objects::                     
                    363: * OOF::                         
                    364: * Mini-OOF::                    
1.23      crook     365: * Comparison with other object models::  
1.12      anton     366: 
1.24      anton     367: The @file{objects.fs} model
1.12      anton     368: 
                    369: * Properties of the Objects model::  
                    370: * Basic Objects Usage::         
1.41      anton     371: * The Objects base class::      
1.12      anton     372: * Creating objects::            
                    373: * Object-Oriented Programming Style::  
                    374: * Class Binding::               
                    375: * Method conveniences::         
                    376: * Classes and Scoping::         
1.41      anton     377: * Dividing classes::            
1.12      anton     378: * Object Interfaces::           
                    379: * Objects Implementation::      
                    380: * Objects Glossary::            
                    381: 
1.24      anton     382: The @file{oof.fs} model
1.12      anton     383: 
1.67      anton     384: * Properties of the OOF model::  
                    385: * Basic OOF Usage::             
                    386: * The OOF base class::          
                    387: * Class Declaration::           
                    388: * Class Implementation::        
1.12      anton     389: 
1.24      anton     390: The @file{mini-oof.fs} model
1.23      crook     391: 
1.48      anton     392: * Basic Mini-OOF Usage::        
                    393: * Mini-OOF Example::            
                    394: * Mini-OOF Implementation::     
1.23      crook     395: 
1.78      anton     396: Programming Tools
                    397: 
1.150     anton     398: * Examining::                   Data and Code.
                    399: * Forgetting words::            Usually before reloading.
1.78      anton     400: * Debugging::                   Simple and quick.
                    401: * Assertions::                  Making your programs self-checking.
                    402: * Singlestep Debugger::         Executing your program word by word.
                    403: 
1.155     anton     404: C Interface
                    405: 
                    406: * Calling C Functions::         
                    407: * Declaring C Functions::       
                    408: * Callbacks::                   
                    409: * Low-Level C Interface Words::  
                    410: 
1.78      anton     411: Assembler and Code Words
                    412: 
                    413: * Code and ;code::              
                    414: * Common Assembler::            Assembler Syntax
                    415: * Common Disassembler::         
                    416: * 386 Assembler::               Deviations and special cases
                    417: * Alpha Assembler::             Deviations and special cases
                    418: * MIPS assembler::              Deviations and special cases
1.167     anton     419: * PowerPC assembler::           Deviations and special cases
1.78      anton     420: * Other assemblers::            How to write them
                    421: 
1.12      anton     422: Tools
                    423: 
                    424: * ANS Report::                  Report the words used, sorted by wordset.
1.127     anton     425: * Stack depth changes::         Where does this stack item come from?
1.12      anton     426: 
                    427: ANS conformance
                    428: 
                    429: * The Core Words::              
                    430: * The optional Block word set::  
                    431: * The optional Double Number word set::  
                    432: * The optional Exception word set::  
                    433: * The optional Facility word set::  
                    434: * The optional File-Access word set::  
                    435: * The optional Floating-Point word set::  
                    436: * The optional Locals word set::  
                    437: * The optional Memory-Allocation word set::  
                    438: * The optional Programming-Tools word set::  
                    439: * The optional Search-Order word set::  
                    440: 
                    441: The Core Words
                    442: 
                    443: * core-idef::                   Implementation Defined Options                   
                    444: * core-ambcond::                Ambiguous Conditions                
                    445: * core-other::                  Other System Documentation                  
                    446: 
                    447: The optional Block word set
                    448: 
                    449: * block-idef::                  Implementation Defined Options
                    450: * block-ambcond::               Ambiguous Conditions               
                    451: * block-other::                 Other System Documentation                 
                    452: 
                    453: The optional Double Number word set
                    454: 
                    455: * double-ambcond::              Ambiguous Conditions              
                    456: 
                    457: The optional Exception word set
                    458: 
                    459: * exception-idef::              Implementation Defined Options              
                    460: 
                    461: The optional Facility word set
                    462: 
                    463: * facility-idef::               Implementation Defined Options               
                    464: * facility-ambcond::            Ambiguous Conditions            
                    465: 
                    466: The optional File-Access word set
                    467: 
                    468: * file-idef::                   Implementation Defined Options
                    469: * file-ambcond::                Ambiguous Conditions                
                    470: 
                    471: The optional Floating-Point word set
                    472: 
                    473: * floating-idef::               Implementation Defined Options
                    474: * floating-ambcond::            Ambiguous Conditions            
                    475: 
                    476: The optional Locals word set
                    477: 
                    478: * locals-idef::                 Implementation Defined Options                 
                    479: * locals-ambcond::              Ambiguous Conditions              
                    480: 
                    481: The optional Memory-Allocation word set
                    482: 
                    483: * memory-idef::                 Implementation Defined Options                 
                    484: 
                    485: The optional Programming-Tools word set
                    486: 
                    487: * programming-idef::            Implementation Defined Options            
                    488: * programming-ambcond::         Ambiguous Conditions         
                    489: 
                    490: The optional Search-Order word set
                    491: 
                    492: * search-idef::                 Implementation Defined Options                 
                    493: * search-ambcond::              Ambiguous Conditions              
                    494: 
1.109     anton     495: Emacs and Gforth
                    496: 
                    497: * Installing gforth.el::        Making Emacs aware of Forth.
                    498: * Emacs Tags::                  Viewing the source of a word in Emacs.
                    499: * Hilighting::                  Making Forth code look prettier.
                    500: * Auto-Indentation::            Customizing auto-indentation.
                    501: * Blocks Files::                Reading and writing blocks files.
                    502: 
1.12      anton     503: Image Files
                    504: 
1.24      anton     505: * Image Licensing Issues::      Distribution terms for images.
                    506: * Image File Background::       Why have image files?
1.67      anton     507: * Non-Relocatable Image Files::  don't always work.
1.24      anton     508: * Data-Relocatable Image Files::  are better.
1.67      anton     509: * Fully Relocatable Image Files::  better yet.
1.24      anton     510: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.32      anton     511: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.24      anton     512: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     513: 
                    514: Fully Relocatable Image Files
                    515: 
1.27      crook     516: * gforthmi::                    The normal way
1.12      anton     517: * cross.fs::                    The hard way
                    518: 
                    519: Engine
                    520: 
                    521: * Portability::                 
                    522: * Threading::                   
                    523: * Primitives::                  
                    524: * Performance::                 
                    525: 
                    526: Threading
                    527: 
                    528: * Scheduling::                  
                    529: * Direct or Indirect Threaded?::  
1.109     anton     530: * Dynamic Superinstructions::   
1.12      anton     531: * DOES>::                       
                    532: 
                    533: Primitives
                    534: 
                    535: * Automatic Generation::        
                    536: * TOS Optimization::            
                    537: * Produced code::               
1.13      pazsan    538: 
                    539: Cross Compiler
                    540: 
1.67      anton     541: * Using the Cross Compiler::    
                    542: * How the Cross Compiler Works::  
1.13      pazsan    543: 
1.113     anton     544: Licenses
                    545: 
                    546: * GNU Free Documentation License::  License for copying this manual.
                    547: * Copying::                         GPL (for copying this software).
                    548: 
1.24      anton     549: @end detailmenu
1.1       anton     550: @end menu
                    551: 
1.113     anton     552: @c ----------------------------------------------------------
1.1       anton     553: @iftex
                    554: @unnumbered Preface
                    555: @cindex Preface
1.21      crook     556: This manual documents Gforth. Some introductory material is provided for
                    557: readers who are unfamiliar with Forth or who are migrating to Gforth
                    558: from other Forth compilers. However, this manual is primarily a
                    559: reference manual.
1.1       anton     560: @end iftex
                    561: 
1.28      crook     562: @comment TODO much more blurb here.
1.26      crook     563: 
                    564: @c ******************************************************************
1.113     anton     565: @node Goals, Gforth Environment, Top, Top
1.26      crook     566: @comment node-name,     next,           previous, up
                    567: @chapter Goals of Gforth
                    568: @cindex goals of the Gforth project
                    569: The goal of the Gforth Project is to develop a standard model for
                    570: ANS Forth. This can be split into several subgoals:
                    571: 
                    572: @itemize @bullet
                    573: @item
                    574: Gforth should conform to the ANS Forth Standard.
                    575: @item
                    576: It should be a model, i.e. it should define all the
                    577: implementation-dependent things.
                    578: @item
                    579: It should become standard, i.e. widely accepted and used. This goal
                    580: is the most difficult one.
                    581: @end itemize
                    582: 
                    583: To achieve these goals Gforth should be
                    584: @itemize @bullet
                    585: @item
                    586: Similar to previous models (fig-Forth, F83)
                    587: @item
                    588: Powerful. It should provide for all the things that are considered
                    589: necessary today and even some that are not yet considered necessary.
                    590: @item
                    591: Efficient. It should not get the reputation of being exceptionally
                    592: slow.
                    593: @item
                    594: Free.
                    595: @item
                    596: Available on many machines/easy to port.
                    597: @end itemize
                    598: 
                    599: Have we achieved these goals? Gforth conforms to the ANS Forth
                    600: standard. It may be considered a model, but we have not yet documented
                    601: which parts of the model are stable and which parts we are likely to
                    602: change. It certainly has not yet become a de facto standard, but it
                    603: appears to be quite popular. It has some similarities to and some
                    604: differences from previous models. It has some powerful features, but not
                    605: yet everything that we envisioned. We certainly have achieved our
1.65      anton     606: execution speed goals (@pxref{Performance})@footnote{However, in 1998
                    607: the bar was raised when the major commercial Forth vendors switched to
                    608: native code compilers.}.  It is free and available on many machines.
1.29      crook     609: 
1.26      crook     610: @c ******************************************************************
1.48      anton     611: @node Gforth Environment, Tutorial, Goals, Top
1.29      crook     612: @chapter Gforth Environment
                    613: @cindex Gforth environment
1.21      crook     614: 
1.45      crook     615: Note: ultimately, the Gforth man page will be auto-generated from the
1.29      crook     616: material in this chapter.
1.21      crook     617: 
                    618: @menu
1.29      crook     619: * Invoking Gforth::             Getting in
                    620: * Leaving Gforth::              Getting out
                    621: * Command-line editing::        
1.48      anton     622: * Environment variables::       that affect how Gforth starts up
1.29      crook     623: * Gforth Files::                What gets installed and where
1.112     anton     624: * Gforth in pipes::             
1.48      anton     625: * Startup speed::               When 35ms is not fast enough ...
1.21      crook     626: @end menu
                    627: 
1.49      anton     628: For related information about the creation of images see @ref{Image Files}.
1.29      crook     629: 
1.21      crook     630: @comment ----------------------------------------------
1.48      anton     631: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29      crook     632: @section Invoking Gforth
                    633: @cindex invoking Gforth
                    634: @cindex running Gforth
                    635: @cindex command-line options
                    636: @cindex options on the command line
                    637: @cindex flags on the command line
1.21      crook     638: 
1.30      anton     639: Gforth is made up of two parts; an executable ``engine'' (named
1.109     anton     640: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30      anton     641: will usually just say @code{gforth} -- this automatically loads the
                    642: default image file @file{gforth.fi}. In many other cases the default
                    643: Gforth image will be invoked like this:
1.21      crook     644: @example
1.30      anton     645: gforth [file | -e forth-code] ...
1.21      crook     646: @end example
1.29      crook     647: @noindent
                    648: This interprets the contents of the files and the Forth code in the order they
                    649: are given.
1.21      crook     650: 
1.109     anton     651: In addition to the @command{gforth} engine, there is also an engine
                    652: called @command{gforth-fast}, which is faster, but gives less
                    653: informative error messages (@pxref{Error messages}) and may catch some
1.166     anton     654: errors (in particular, stack underflows and integer division errors)
                    655: later or not at all.  You should use it for debugged,
1.109     anton     656: performance-critical programs.
                    657: 
                    658: Moreover, there is an engine called @command{gforth-itc}, which is
                    659: useful in some backwards-compatibility situations (@pxref{Direct or
                    660: Indirect Threaded?}).
1.30      anton     661: 
1.29      crook     662: In general, the command line looks like this:
1.21      crook     663: 
                    664: @example
1.30      anton     665: gforth[-fast] [engine options] [image options]
1.21      crook     666: @end example
                    667: 
1.30      anton     668: The engine options must come before the rest of the command
1.29      crook     669: line. They are:
1.26      crook     670: 
1.29      crook     671: @table @code
                    672: @cindex -i, command-line option
                    673: @cindex --image-file, command-line option
                    674: @item --image-file @i{file}
                    675: @itemx -i @i{file}
                    676: Loads the Forth image @i{file} instead of the default
                    677: @file{gforth.fi} (@pxref{Image Files}).
1.21      crook     678: 
1.39      anton     679: @cindex --appl-image, command-line option
                    680: @item --appl-image @i{file}
                    681: Loads the image @i{file} and leaves all further command-line arguments
1.65      anton     682: to the image (instead of processing them as engine options).  This is
                    683: useful for building executable application images on Unix, built with
1.39      anton     684: @code{gforthmi --application ...}.
                    685: 
1.29      crook     686: @cindex --path, command-line option
                    687: @cindex -p, command-line option
                    688: @item --path @i{path}
                    689: @itemx -p @i{path}
                    690: Uses @i{path} for searching the image file and Forth source code files
                    691: instead of the default in the environment variable @code{GFORTHPATH} or
                    692: the path specified at installation time (e.g.,
                    693: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                    694: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook     695: 
1.29      crook     696: @cindex --dictionary-size, command-line option
                    697: @cindex -m, command-line option
                    698: @cindex @i{size} parameters for command-line options
                    699: @cindex size of the dictionary and the stacks
                    700: @item --dictionary-size @i{size}
                    701: @itemx -m @i{size}
                    702: Allocate @i{size} space for the Forth dictionary space instead of
                    703: using the default specified in the image (typically 256K). The
                    704: @i{size} specification for this and subsequent options consists of
                    705: an integer and a unit (e.g.,
                    706: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
                    707: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                    708: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                    709: @code{e} is used.
1.21      crook     710: 
1.29      crook     711: @cindex --data-stack-size, command-line option
                    712: @cindex -d, command-line option
                    713: @item --data-stack-size @i{size}
                    714: @itemx -d @i{size}
                    715: Allocate @i{size} space for the data stack instead of using the
                    716: default specified in the image (typically 16K).
1.21      crook     717: 
1.29      crook     718: @cindex --return-stack-size, command-line option
                    719: @cindex -r, command-line option
                    720: @item --return-stack-size @i{size}
                    721: @itemx -r @i{size}
                    722: Allocate @i{size} space for the return stack instead of using the
                    723: default specified in the image (typically 15K).
1.21      crook     724: 
1.29      crook     725: @cindex --fp-stack-size, command-line option
                    726: @cindex -f, command-line option
                    727: @item --fp-stack-size @i{size}
                    728: @itemx -f @i{size}
                    729: Allocate @i{size} space for the floating point stack instead of
                    730: using the default specified in the image (typically 15.5K). In this case
                    731: the unit specifier @code{e} refers to floating point numbers.
1.21      crook     732: 
1.48      anton     733: @cindex --locals-stack-size, command-line option
                    734: @cindex -l, command-line option
                    735: @item --locals-stack-size @i{size}
                    736: @itemx -l @i{size}
                    737: Allocate @i{size} space for the locals stack instead of using the
                    738: default specified in the image (typically 14.5K).
                    739: 
                    740: @cindex -h, command-line option
                    741: @cindex --help, command-line option
                    742: @item --help
                    743: @itemx -h
                    744: Print a message about the command-line options
                    745: 
                    746: @cindex -v, command-line option
                    747: @cindex --version, command-line option
                    748: @item --version
                    749: @itemx -v
                    750: Print version and exit
                    751: 
                    752: @cindex --debug, command-line option
                    753: @item --debug
                    754: Print some information useful for debugging on startup.
                    755: 
                    756: @cindex --offset-image, command-line option
                    757: @item --offset-image
                    758: Start the dictionary at a slightly different position than would be used
                    759: otherwise (useful for creating data-relocatable images,
                    760: @pxref{Data-Relocatable Image Files}).
                    761: 
                    762: @cindex --no-offset-im, command-line option
                    763: @item --no-offset-im
                    764: Start the dictionary at the normal position.
                    765: 
                    766: @cindex --clear-dictionary, command-line option
                    767: @item --clear-dictionary
                    768: Initialize all bytes in the dictionary to 0 before loading the image
                    769: (@pxref{Data-Relocatable Image Files}).
                    770: 
                    771: @cindex --die-on-signal, command-line-option
                    772: @item --die-on-signal
                    773: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                    774: or the segmentation violation SIGSEGV) by translating it into a Forth
                    775: @code{THROW}. With this option, Gforth exits if it receives such a
                    776: signal. This option is useful when the engine and/or the image might be
                    777: severely broken (such that it causes another signal before recovering
                    778: from the first); this option avoids endless loops in such cases.
1.109     anton     779: 
1.119     anton     780: @cindex --no-dynamic, command-line option
                    781: @cindex --dynamic, command-line option
1.109     anton     782: @item --no-dynamic
                    783: @item --dynamic
                    784: Disable or enable dynamic superinstructions with replication
                    785: (@pxref{Dynamic Superinstructions}).
                    786: 
1.119     anton     787: @cindex --no-super, command-line option
1.109     anton     788: @item --no-super
1.110     anton     789: Disable dynamic superinstructions, use just dynamic replication; this is
                    790: useful if you want to patch threaded code (@pxref{Dynamic
                    791: Superinstructions}).
1.119     anton     792: 
                    793: @cindex --ss-number, command-line option
                    794: @item --ss-number=@var{N}
                    795: Use only the first @var{N} static superinstructions compiled into the
                    796: engine (default: use them all; note that only @code{gforth-fast} has
                    797: any).  This option is useful for measuring the performance impact of
                    798: static superinstructions.
                    799: 
                    800: @cindex --ss-min-..., command-line options
                    801: @item --ss-min-codesize
                    802: @item --ss-min-ls
                    803: @item --ss-min-lsu
                    804: @item --ss-min-nexts
                    805: Use specified metric for determining the cost of a primitive or static
                    806: superinstruction for static superinstruction selection.  @code{Codesize}
                    807: is the native code size of the primive or static superinstruction,
                    808: @code{ls} is the number of loads and stores, @code{lsu} is the number of
                    809: loads, stores, and updates, and @code{nexts} is the number of dispatches
                    810: (not taking dynamic superinstructions into account), i.e. every
                    811: primitive or static superinstruction has cost 1. Default:
                    812: @code{codesize} if you use dynamic code generation, otherwise
                    813: @code{nexts}.
                    814: 
                    815: @cindex --ss-greedy, command-line option
                    816: @item --ss-greedy
                    817: This option is useful for measuring the performance impact of static
                    818: superinstructions.  By default, an optimal shortest-path algorithm is
                    819: used for selecting static superinstructions.  With @option{--ss-greedy}
                    820: this algorithm is modified to assume that anything after the static
                    821: superinstruction currently under consideration is not combined into
                    822: static superinstructions.  With @option{--ss-min-nexts} this produces
                    823: the same result as a greedy algorithm that always selects the longest
                    824: superinstruction available at the moment.  E.g., if there are
                    825: superinstructions AB and BCD, then for the sequence A B C D the optimal
                    826: algorithm will select A BCD and the greedy algorithm will select AB C D.
                    827: 
                    828: @cindex --print-metrics, command-line option
                    829: @item --print-metrics
                    830: Prints some metrics used during static superinstruction selection:
                    831: @code{code size} is the actual size of the dynamically generated code.
                    832: @code{Metric codesize} is the sum of the codesize metrics as seen by
                    833: static superinstruction selection; there is a difference from @code{code
                    834: size}, because not all primitives and static superinstructions are
                    835: compiled into dynamically generated code, and because of markers.  The
                    836: other metrics correspond to the @option{ss-min-...} options.  This
                    837: option is useful for evaluating the effects of the @option{--ss-...}
                    838: options.
1.109     anton     839: 
1.48      anton     840: @end table
                    841: 
                    842: @cindex loading files at startup
                    843: @cindex executing code on startup
                    844: @cindex batch processing with Gforth
                    845: As explained above, the image-specific command-line arguments for the
                    846: default image @file{gforth.fi} consist of a sequence of filenames and
                    847: @code{-e @var{forth-code}} options that are interpreted in the sequence
                    848: in which they are given. The @code{-e @var{forth-code}} or
1.121     anton     849: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
                    850: option takes only one argument; if you want to evaluate more Forth
                    851: words, you have to quote them or use @code{-e} several times. To exit
1.48      anton     852: after processing the command line (instead of entering interactive mode)
1.121     anton     853: append @code{-e bye} to the command line.  You can also process the
                    854: command-line arguments with a Forth program (@pxref{OS command line
                    855: arguments}).
1.48      anton     856: 
                    857: @cindex versions, invoking other versions of Gforth
                    858: If you have several versions of Gforth installed, @code{gforth} will
                    859: invoke the version that was installed last. @code{gforth-@i{version}}
                    860: invokes a specific version. If your environment contains the variable
                    861: @code{GFORTHPATH}, you may want to override it by using the
                    862: @code{--path} option.
                    863: 
                    864: Not yet implemented:
                    865: On startup the system first executes the system initialization file
                    866: (unless the option @code{--no-init-file} is given; note that the system
                    867: resulting from using this option may not be ANS Forth conformant). Then
                    868: the user initialization file @file{.gforth.fs} is executed, unless the
1.62      crook     869: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48      anton     870: then in @file{~}, then in the normal path (see above).
                    871: 
                    872: 
                    873: 
                    874: @comment ----------------------------------------------
                    875: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
                    876: @section Leaving Gforth
                    877: @cindex Gforth - leaving
                    878: @cindex leaving Gforth
                    879: 
                    880: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
                    881: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
                    882: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49      anton     883: data are discarded.  For ways of saving the state of the system before
                    884: leaving Gforth see @ref{Image Files}.
1.48      anton     885: 
                    886: doc-bye
                    887: 
                    888: 
                    889: @comment ----------------------------------------------
1.65      anton     890: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48      anton     891: @section Command-line editing
                    892: @cindex command-line editing
                    893: 
                    894: Gforth maintains a history file that records every line that you type to
                    895: the text interpreter. This file is preserved between sessions, and is
                    896: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
                    897: repeatedly you can recall successively older commands from this (or
                    898: previous) session(s). The full list of command-line editing facilities is:
                    899: 
                    900: @itemize @bullet
                    901: @item
                    902: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
                    903: commands from the history buffer.
                    904: @item
                    905: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
                    906: from the history buffer.
                    907: @item
                    908: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
                    909: @item
                    910: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
                    911: @item
                    912: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
                    913: closing up the line.
                    914: @item
                    915: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
                    916: @item
                    917: @kbd{Ctrl-a} to move the cursor to the start of the line.
                    918: @item
                    919: @kbd{Ctrl-e} to move the cursor to the end of the line.
                    920: @item
                    921: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
                    922: line.
                    923: @item
                    924: @key{TAB} to step through all possible full-word completions of the word
                    925: currently being typed.
                    926: @item
1.65      anton     927: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
                    928: using @code{bye}). 
                    929: @item
                    930: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
                    931: character under the cursor.
1.48      anton     932: @end itemize
                    933: 
                    934: When editing, displayable characters are inserted to the left of the
                    935: cursor position; the line is always in ``insert'' (as opposed to
                    936: ``overstrike'') mode.
                    937: 
                    938: @cindex history file
                    939: @cindex @file{.gforth-history}
                    940: On Unix systems, the history file is @file{~/.gforth-history} by
                    941: default@footnote{i.e. it is stored in the user's home directory.}. You
                    942: can find out the name and location of your history file using:
                    943: 
                    944: @example 
                    945: history-file type \ Unix-class systems
                    946: 
                    947: history-file type \ Other systems
                    948: history-dir  type
                    949: @end example
                    950: 
                    951: If you enter long definitions by hand, you can use a text editor to
                    952: paste them out of the history file into a Forth source file for reuse at
                    953: a later time.
                    954: 
                    955: Gforth never trims the size of the history file, so you should do this
                    956: periodically, if necessary.
                    957: 
                    958: @comment this is all defined in history.fs
                    959: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
                    960: @comment chosen?
                    961: 
                    962: 
                    963: @comment ----------------------------------------------
1.65      anton     964: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48      anton     965: @section Environment variables
                    966: @cindex environment variables
                    967: 
                    968: Gforth uses these environment variables:
                    969: 
                    970: @itemize @bullet
                    971: @item
                    972: @cindex @code{GFORTHHIST} -- environment variable
                    973: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
                    974: open/create the history file, @file{.gforth-history}. Default:
                    975: @code{$HOME}.
                    976: 
                    977: @item
                    978: @cindex @code{GFORTHPATH} -- environment variable
                    979: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
                    980: for Forth source-code files.
                    981: 
                    982: @item
1.147     anton     983: @cindex @code{LANG} -- environment variable
                    984: @code{LANG} -- see @code{LC_CTYPE}
                    985: 
                    986: @item
                    987: @cindex @code{LC_ALL} -- environment variable
                    988: @code{LC_ALL} -- see @code{LC_CTYPE}
                    989: 
                    990: @item
                    991: @cindex @code{LC_CTYPE} -- environment variable
                    992: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
                    993: startup, Gforth uses the UTF-8 encoding for strings internally and
                    994: expects its input and produces its output in UTF-8 encoding, otherwise
                    995: the encoding is 8bit (see @pxref{Xchars and Unicode}).  If this
                    996: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
                    997: that is unset, in @code{LANG}.
                    998: 
                    999: @item
1.129     anton    1000: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
                   1001: 
                   1002: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
                   1003: of @code{system} before passing it to C's @code{system()}.  Default:
1.130     anton    1004: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs.  The prefix
1.129     anton    1005: and the command are directly concatenated, so if a space between them is
                   1006: necessary, append it to the prefix.
                   1007: 
                   1008: @item
1.48      anton    1009: @cindex @code{GFORTH} -- environment variable
1.49      anton    1010: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1011: 
                   1012: @item
                   1013: @cindex @code{GFORTHD} -- environment variable
1.62      crook    1014: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1015: 
                   1016: @item
                   1017: @cindex @code{TMP}, @code{TEMP} - environment variable
                   1018: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
                   1019: location for the history file.
                   1020: @end itemize
                   1021: 
                   1022: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
                   1023: @comment mentioning these.
                   1024: 
                   1025: All the Gforth environment variables default to sensible values if they
                   1026: are not set.
                   1027: 
                   1028: 
                   1029: @comment ----------------------------------------------
1.112     anton    1030: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48      anton    1031: @section Gforth files
                   1032: @cindex Gforth files
                   1033: 
                   1034: When you install Gforth on a Unix system, it installs files in these
                   1035: locations by default:
                   1036: 
                   1037: @itemize @bullet
                   1038: @item
                   1039: @file{/usr/local/bin/gforth}
                   1040: @item
                   1041: @file{/usr/local/bin/gforthmi}
                   1042: @item
                   1043: @file{/usr/local/man/man1/gforth.1} - man page.
                   1044: @item
                   1045: @file{/usr/local/info} - the Info version of this manual.
                   1046: @item
                   1047: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
                   1048: @item
                   1049: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
                   1050: @item
                   1051: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
                   1052: @item
                   1053: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
                   1054: @end itemize
                   1055: 
                   1056: You can select different places for installation by using
                   1057: @code{configure} options (listed with @code{configure --help}).
                   1058: 
                   1059: @comment ----------------------------------------------
1.112     anton    1060: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
                   1061: @section Gforth in pipes
                   1062: @cindex pipes, Gforth as part of
                   1063: 
                   1064: Gforth can be used in pipes created elsewhere (described here).  It can
                   1065: also create pipes on its own (@pxref{Pipes}).
                   1066: 
                   1067: @cindex input from pipes
                   1068: If you pipe into Gforth, your program should read with @code{read-file}
                   1069: or @code{read-line} from @code{stdin} (@pxref{General files}).
                   1070: @code{Key} does not recognize the end of input.  Words like
                   1071: @code{accept} echo the input and are therefore usually not useful for
                   1072: reading from a pipe.  You have to invoke the Forth program with an OS
                   1073: command-line option, as you have no chance to use the Forth command line
                   1074: (the text interpreter would try to interpret the pipe input).
                   1075: 
                   1076: @cindex output in pipes
                   1077: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
                   1078: 
                   1079: @cindex silent exiting from Gforth
                   1080: When you write to a pipe that has been closed at the other end, Gforth
                   1081: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
                   1082: into the exception @code{broken-pipe-error}.  If your application does
                   1083: not catch that exception, the system catches it and exits, usually
                   1084: silently (unless you were working on the Forth command line; then it
                   1085: prints an error message and exits).  This is usually the desired
                   1086: behaviour.
                   1087: 
                   1088: If you do not like this behaviour, you have to catch the exception
                   1089: yourself, and react to it.
                   1090: 
                   1091: Here's an example of an invocation of Gforth that is usable in a pipe:
                   1092: 
                   1093: @example
                   1094: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
                   1095:  type repeat ; foo bye"
                   1096: @end example
                   1097: 
                   1098: This example just copies the input verbatim to the output.  A very
                   1099: simple pipe containing this example looks like this:
                   1100: 
                   1101: @example
                   1102: cat startup.fs |
                   1103: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
                   1104:  type repeat ; foo bye"|
                   1105: head
                   1106: @end example
                   1107: 
                   1108: @cindex stderr and pipes
                   1109: Pipes involving Gforth's @code{stderr} output do not work.
                   1110: 
                   1111: @comment ----------------------------------------------
                   1112: @node Startup speed,  , Gforth in pipes, Gforth Environment
1.48      anton    1113: @section Startup speed
                   1114: @cindex Startup speed
                   1115: @cindex speed, startup
                   1116: 
                   1117: If Gforth is used for CGI scripts or in shell scripts, its startup
                   1118: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
                   1119: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
                   1120: system time.
                   1121: 
                   1122: If startup speed is a problem, you may consider the following ways to
                   1123: improve it; or you may consider ways to reduce the number of startups
1.62      crook    1124: (for example, by using Fast-CGI).
1.48      anton    1125: 
1.112     anton    1126: An easy step that influences Gforth startup speed is the use of the
                   1127: @option{--no-dynamic} option; this decreases image loading speed, but
                   1128: increases compile-time and run-time.
                   1129: 
                   1130: Another step to improve startup speed is to statically link Gforth, by
1.48      anton    1131: building it with @code{XLDFLAGS=-static}.  This requires more memory for
                   1132: the code and will therefore slow down the first invocation, but
                   1133: subsequent invocations avoid the dynamic linking overhead.  Another
                   1134: disadvantage is that Gforth won't profit from library upgrades.  As a
                   1135: result, @code{gforth-static -e bye} takes about 17.1ms user and
                   1136: 8.2ms system time.
                   1137: 
                   1138: The next step to improve startup speed is to use a non-relocatable image
1.65      anton    1139: (@pxref{Non-Relocatable Image Files}).  You can create this image with
1.48      anton    1140: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
                   1141: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
                   1142: and a part of the copy-on-write overhead.  The disadvantage is that the
1.62      crook    1143: non-relocatable image does not work if the OS gives Gforth a different
1.48      anton    1144: address for the dictionary, for whatever reason; so you better provide a
                   1145: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
                   1146: bye} takes about 15.3ms user and 7.5ms system time.
                   1147: 
                   1148: The final step is to disable dictionary hashing in Gforth.  Gforth
                   1149: builds the hash table on startup, which takes much of the startup
                   1150: overhead. You can do this by commenting out the @code{include hash.fs}
                   1151: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
                   1152: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
                   1153: The disadvantages are that functionality like @code{table} and
                   1154: @code{ekey} is missing and that text interpretation (e.g., compiling)
                   1155: now takes much longer. So, you should only use this method if there is
                   1156: no significant text interpretation to perform (the script should be
1.62      crook    1157: compiled into the image, amongst other things).  @code{gforth-static -i
1.48      anton    1158: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
                   1159: 
                   1160: @c ******************************************************************
                   1161: @node Tutorial, Introduction, Gforth Environment, Top
                   1162: @chapter Forth Tutorial
                   1163: @cindex Tutorial
                   1164: @cindex Forth Tutorial
                   1165: 
1.67      anton    1166: @c Topics from nac's Introduction that could be mentioned:
                   1167: @c press <ret> after each line
                   1168: @c Prompt
                   1169: @c numbers vs. words in dictionary on text interpretation
                   1170: @c what happens on redefinition
                   1171: @c parsing words (in particular, defining words)
                   1172: 
1.83      anton    1173: The difference of this chapter from the Introduction
                   1174: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
                   1175: be used while sitting in front of a computer, and covers much more
                   1176: material, but does not explain how the Forth system works.
                   1177: 
1.62      crook    1178: This tutorial can be used with any ANS-compliant Forth; any
                   1179: Gforth-specific features are marked as such and you can skip them if you
                   1180: work with another Forth.  This tutorial does not explain all features of
                   1181: Forth, just enough to get you started and give you some ideas about the
                   1182: facilities available in Forth.  Read the rest of the manual and the
                   1183: standard when you are through this.
1.48      anton    1184: 
                   1185: The intended way to use this tutorial is that you work through it while
                   1186: sitting in front of the console, take a look at the examples and predict
                   1187: what they will do, then try them out; if the outcome is not as expected,
                   1188: find out why (e.g., by trying out variations of the example), so you
                   1189: understand what's going on.  There are also some assignments that you
                   1190: should solve.
                   1191: 
                   1192: This tutorial assumes that you have programmed before and know what,
                   1193: e.g., a loop is.
                   1194: 
                   1195: @c !! explain compat library
                   1196: 
                   1197: @menu
                   1198: * Starting Gforth Tutorial::    
                   1199: * Syntax Tutorial::             
                   1200: * Crash Course Tutorial::       
                   1201: * Stack Tutorial::              
                   1202: * Arithmetics Tutorial::        
                   1203: * Stack Manipulation Tutorial::  
                   1204: * Using files for Forth code Tutorial::  
                   1205: * Comments Tutorial::           
                   1206: * Colon Definitions Tutorial::  
                   1207: * Decompilation Tutorial::      
                   1208: * Stack-Effect Comments Tutorial::  
                   1209: * Types Tutorial::              
                   1210: * Factoring Tutorial::          
                   1211: * Designing the stack effect Tutorial::  
                   1212: * Local Variables Tutorial::    
                   1213: * Conditional execution Tutorial::  
                   1214: * Flags and Comparisons Tutorial::  
                   1215: * General Loops Tutorial::      
                   1216: * Counted loops Tutorial::      
                   1217: * Recursion Tutorial::          
                   1218: * Leaving definitions or loops Tutorial::  
                   1219: * Return Stack Tutorial::       
                   1220: * Memory Tutorial::             
                   1221: * Characters and Strings Tutorial::  
                   1222: * Alignment Tutorial::          
1.87      anton    1223: * Files Tutorial::              
1.48      anton    1224: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                   1225: * Execution Tokens Tutorial::   
                   1226: * Exceptions Tutorial::         
                   1227: * Defining Words Tutorial::     
                   1228: * Arrays and Records Tutorial::  
                   1229: * POSTPONE Tutorial::           
                   1230: * Literal Tutorial::            
                   1231: * Advanced macros Tutorial::    
                   1232: * Compilation Tokens Tutorial::  
                   1233: * Wordlists and Search Order Tutorial::  
                   1234: @end menu
                   1235: 
                   1236: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
                   1237: @section Starting Gforth
1.66      anton    1238: @cindex starting Gforth tutorial
1.48      anton    1239: You can start Gforth by typing its name:
                   1240: 
                   1241: @example
                   1242: gforth
                   1243: @end example
                   1244: 
                   1245: That puts you into interactive mode; you can leave Gforth by typing
                   1246: @code{bye}.  While in Gforth, you can edit the command line and access
                   1247: the command line history with cursor keys, similar to bash.
                   1248: 
                   1249: 
                   1250: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
                   1251: @section Syntax
1.66      anton    1252: @cindex syntax tutorial
1.48      anton    1253: 
1.171     anton    1254: A @dfn{word} is a sequence of arbitrary characters (except white
1.48      anton    1255: space).  Words are separated by white space.  E.g., each of the
                   1256: following lines contains exactly one word:
                   1257: 
                   1258: @example
                   1259: word
                   1260: !@@#$%^&*()
                   1261: 1234567890
                   1262: 5!a
                   1263: @end example
                   1264: 
                   1265: A frequent beginner's error is to leave away necessary white space,
                   1266: resulting in an error like @samp{Undefined word}; so if you see such an
                   1267: error, check if you have put spaces wherever necessary.
                   1268: 
                   1269: @example
                   1270: ." hello, world" \ correct
                   1271: ."hello, world"  \ gives an "Undefined word" error
                   1272: @end example
                   1273: 
1.65      anton    1274: Gforth and most other Forth systems ignore differences in case (they are
1.48      anton    1275: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
                   1276: your system is case-sensitive, you may have to type all the examples
                   1277: given here in upper case.
                   1278: 
                   1279: 
                   1280: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
                   1281: @section Crash Course
                   1282: 
                   1283: Type
                   1284: 
                   1285: @example
                   1286: 0 0 !
                   1287: here execute
                   1288: ' catch >body 20 erase abort
                   1289: ' (quit) >body 20 erase
                   1290: @end example
                   1291: 
                   1292: The last two examples are guaranteed to destroy parts of Gforth (and
                   1293: most other systems), so you better leave Gforth afterwards (if it has
                   1294: not finished by itself).  On some systems you may have to kill gforth
                   1295: from outside (e.g., in Unix with @code{kill}).
                   1296: 
                   1297: Now that you know how to produce crashes (and that there's not much to
                   1298: them), let's learn how to produce meaningful programs.
                   1299: 
                   1300: 
                   1301: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
                   1302: @section Stack
1.66      anton    1303: @cindex stack tutorial
1.48      anton    1304: 
                   1305: The most obvious feature of Forth is the stack.  When you type in a
                   1306: number, it is pushed on the stack.  You can display the content of the
                   1307: stack with @code{.s}.
                   1308: 
                   1309: @example
                   1310: 1 2 .s
                   1311: 3 .s
                   1312: @end example
                   1313: 
                   1314: @code{.s} displays the top-of-stack to the right, i.e., the numbers
                   1315: appear in @code{.s} output as they appeared in the input.
                   1316: 
                   1317: You can print the top of stack element with @code{.}.
                   1318: 
                   1319: @example
                   1320: 1 2 3 . . .
                   1321: @end example
                   1322: 
                   1323: In general, words consume their stack arguments (@code{.s} is an
                   1324: exception).
                   1325: 
1.141     anton    1326: @quotation Assignment
1.48      anton    1327: What does the stack contain after @code{5 6 7 .}?
1.141     anton    1328: @end quotation
1.48      anton    1329: 
                   1330: 
                   1331: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
                   1332: @section Arithmetics
1.66      anton    1333: @cindex arithmetics tutorial
1.48      anton    1334: 
                   1335: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
                   1336: operate on the top two stack items:
                   1337: 
                   1338: @example
1.67      anton    1339: 2 2 .s
                   1340: + .s
                   1341: .
1.48      anton    1342: 2 1 - .
                   1343: 7 3 mod .
                   1344: @end example
                   1345: 
                   1346: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
                   1347: as in the corresponding infix expression (this is generally the case in
                   1348: Forth).
                   1349: 
                   1350: Parentheses are superfluous (and not available), because the order of
                   1351: the words unambiguously determines the order of evaluation and the
                   1352: operands:
                   1353: 
                   1354: @example
                   1355: 3 4 + 5 * .
                   1356: 3 4 5 * + .
                   1357: @end example
                   1358: 
1.141     anton    1359: @quotation Assignment
1.48      anton    1360: What are the infix expressions corresponding to the Forth code above?
                   1361: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
                   1362: known as Postfix or RPN (Reverse Polish Notation).}.
1.141     anton    1363: @end quotation
1.48      anton    1364: 
                   1365: To change the sign, use @code{negate}:
                   1366: 
                   1367: @example
                   1368: 2 negate .
                   1369: @end example
                   1370: 
1.141     anton    1371: @quotation Assignment
1.48      anton    1372: Convert -(-3)*4-5 to Forth.
1.141     anton    1373: @end quotation
1.48      anton    1374: 
                   1375: @code{/mod} performs both @code{/} and @code{mod}.
                   1376: 
                   1377: @example
                   1378: 7 3 /mod . .
                   1379: @end example
                   1380: 
1.66      anton    1381: Reference: @ref{Arithmetic}.
                   1382: 
                   1383: 
1.48      anton    1384: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
                   1385: @section Stack Manipulation
1.66      anton    1386: @cindex stack manipulation tutorial
1.48      anton    1387: 
                   1388: Stack manipulation words rearrange the data on the stack.
                   1389: 
                   1390: @example
                   1391: 1 .s drop .s
                   1392: 1 .s dup .s drop drop .s
                   1393: 1 2 .s over .s drop drop drop
                   1394: 1 2 .s swap .s drop drop
                   1395: 1 2 3 .s rot .s drop drop drop
                   1396: @end example
                   1397: 
                   1398: These are the most important stack manipulation words.  There are also
                   1399: variants that manipulate twice as many stack items:
                   1400: 
                   1401: @example
                   1402: 1 2 3 4 .s 2swap .s 2drop 2drop
                   1403: @end example
                   1404: 
                   1405: Two more stack manipulation words are:
                   1406: 
                   1407: @example
                   1408: 1 2 .s nip .s drop
                   1409: 1 2 .s tuck .s 2drop drop
                   1410: @end example
                   1411: 
1.141     anton    1412: @quotation Assignment
1.48      anton    1413: Replace @code{nip} and @code{tuck} with combinations of other stack
                   1414: manipulation words.
                   1415: 
                   1416: @example
                   1417: Given:          How do you get:
                   1418: 1 2 3           3 2 1           
                   1419: 1 2 3           1 2 3 2                 
                   1420: 1 2 3           1 2 3 3                 
                   1421: 1 2 3           1 3 3           
                   1422: 1 2 3           2 1 3           
                   1423: 1 2 3 4         4 3 2 1         
                   1424: 1 2 3           1 2 3 1 2 3             
                   1425: 1 2 3 4         1 2 3 4 1 2             
                   1426: 1 2 3
                   1427: 1 2 3           1 2 3 4                 
                   1428: 1 2 3           1 3             
                   1429: @end example
1.141     anton    1430: @end quotation
1.48      anton    1431: 
                   1432: @example
                   1433: 5 dup * .
                   1434: @end example
                   1435: 
1.141     anton    1436: @quotation Assignment
1.48      anton    1437: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
                   1438: Write a piece of Forth code that expects two numbers on the stack
                   1439: (@var{a} and @var{b}, with @var{b} on top) and computes
                   1440: @code{(a-b)(a+1)}.
1.141     anton    1441: @end quotation
1.48      anton    1442: 
1.66      anton    1443: Reference: @ref{Stack Manipulation}.
                   1444: 
                   1445: 
1.48      anton    1446: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
                   1447: @section Using files for Forth code
1.66      anton    1448: @cindex loading Forth code, tutorial
                   1449: @cindex files containing Forth code, tutorial
1.48      anton    1450: 
                   1451: While working at the Forth command line is convenient for one-line
                   1452: examples and short one-off code, you probably want to store your source
                   1453: code in files for convenient editing and persistence.  You can use your
                   1454: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102     anton    1455: Gforth}) to create @var{file.fs} and use
1.48      anton    1456: 
                   1457: @example
1.102     anton    1458: s" @var{file.fs}" included
1.48      anton    1459: @end example
                   1460: 
                   1461: to load it into your Forth system.  The file name extension I use for
                   1462: Forth files is @samp{.fs}.
                   1463: 
                   1464: You can easily start Gforth with some files loaded like this:
                   1465: 
                   1466: @example
1.102     anton    1467: gforth @var{file1.fs} @var{file2.fs}
1.48      anton    1468: @end example
                   1469: 
                   1470: If an error occurs during loading these files, Gforth terminates,
                   1471: whereas an error during @code{INCLUDED} within Gforth usually gives you
                   1472: a Gforth command line.  Starting the Forth system every time gives you a
                   1473: clean start every time, without interference from the results of earlier
                   1474: tries.
                   1475: 
                   1476: I often put all the tests in a file, then load the code and run the
                   1477: tests with
                   1478: 
                   1479: @example
1.102     anton    1480: gforth @var{code.fs} @var{tests.fs} -e bye
1.48      anton    1481: @end example
                   1482: 
                   1483: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
                   1484: @code{-e bye} ensures that Gforth terminates afterwards so that I can
                   1485: restart this command without ado.
                   1486: 
                   1487: The advantage of this approach is that the tests can be repeated easily
                   1488: every time the program ist changed, making it easy to catch bugs
                   1489: introduced by the change.
                   1490: 
1.66      anton    1491: Reference: @ref{Forth source files}.
                   1492: 
1.48      anton    1493: 
                   1494: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
                   1495: @section Comments
1.66      anton    1496: @cindex comments tutorial
1.48      anton    1497: 
                   1498: @example
                   1499: \ That's a comment; it ends at the end of the line
                   1500: ( Another comment; it ends here: )  .s
                   1501: @end example
                   1502: 
                   1503: @code{\} and @code{(} are ordinary Forth words and therefore have to be
                   1504: separated with white space from the following text.
                   1505: 
                   1506: @example
                   1507: \This gives an "Undefined word" error
                   1508: @end example
                   1509: 
                   1510: The first @code{)} ends a comment started with @code{(}, so you cannot
                   1511: nest @code{(}-comments; and you cannot comment out text containing a
                   1512: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
                   1513: avoid @code{)} in word names.}.
                   1514: 
                   1515: I use @code{\}-comments for descriptive text and for commenting out code
                   1516: of one or more line; I use @code{(}-comments for describing the stack
                   1517: effect, the stack contents, or for commenting out sub-line pieces of
                   1518: code.
                   1519: 
                   1520: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
                   1521: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
                   1522: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
                   1523: with @kbd{M-q}.
                   1524: 
1.66      anton    1525: Reference: @ref{Comments}.
                   1526: 
1.48      anton    1527: 
                   1528: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
                   1529: @section Colon Definitions
1.66      anton    1530: @cindex colon definitions, tutorial
                   1531: @cindex definitions, tutorial
                   1532: @cindex procedures, tutorial
                   1533: @cindex functions, tutorial
1.48      anton    1534: 
                   1535: are similar to procedures and functions in other programming languages.
                   1536: 
                   1537: @example
                   1538: : squared ( n -- n^2 )
                   1539:    dup * ;
                   1540: 5 squared .
                   1541: 7 squared .
                   1542: @end example
                   1543: 
                   1544: @code{:} starts the colon definition; its name is @code{squared}.  The
                   1545: following comment describes its stack effect.  The words @code{dup *}
                   1546: are not executed, but compiled into the definition.  @code{;} ends the
                   1547: colon definition.
                   1548: 
                   1549: The newly-defined word can be used like any other word, including using
                   1550: it in other definitions:
                   1551: 
                   1552: @example
                   1553: : cubed ( n -- n^3 )
                   1554:    dup squared * ;
                   1555: -5 cubed .
                   1556: : fourth-power ( n -- n^4 )
                   1557:    squared squared ;
                   1558: 3 fourth-power .
                   1559: @end example
                   1560: 
1.141     anton    1561: @quotation Assignment
1.48      anton    1562: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
                   1563: @code{/mod} in terms of other Forth words, and check if they work (hint:
                   1564: test your tests on the originals first).  Don't let the
                   1565: @samp{redefined}-Messages spook you, they are just warnings.
1.141     anton    1566: @end quotation
1.48      anton    1567: 
1.66      anton    1568: Reference: @ref{Colon Definitions}.
                   1569: 
1.48      anton    1570: 
                   1571: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
                   1572: @section Decompilation
1.66      anton    1573: @cindex decompilation tutorial
                   1574: @cindex see tutorial
1.48      anton    1575: 
                   1576: You can decompile colon definitions with @code{see}:
                   1577: 
                   1578: @example
                   1579: see squared
                   1580: see cubed
                   1581: @end example
                   1582: 
                   1583: In Gforth @code{see} shows you a reconstruction of the source code from
                   1584: the executable code.  Informations that were present in the source, but
                   1585: not in the executable code, are lost (e.g., comments).
                   1586: 
1.65      anton    1587: You can also decompile the predefined words:
                   1588: 
                   1589: @example
                   1590: see .
                   1591: see +
                   1592: @end example
                   1593: 
                   1594: 
1.48      anton    1595: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
                   1596: @section Stack-Effect Comments
1.66      anton    1597: @cindex stack-effect comments, tutorial
                   1598: @cindex --, tutorial
1.48      anton    1599: By convention the comment after the name of a definition describes the
1.171     anton    1600: stack effect: The part in front of the @samp{--} describes the state of
1.48      anton    1601: the stack before the execution of the definition, i.e., the parameters
                   1602: that are passed into the colon definition; the part behind the @samp{--}
                   1603: is the state of the stack after the execution of the definition, i.e.,
                   1604: the results of the definition.  The stack comment only shows the top
                   1605: stack items that the definition accesses and/or changes.
                   1606: 
                   1607: You should put a correct stack effect on every definition, even if it is
                   1608: just @code{( -- )}.  You should also add some descriptive comment to
                   1609: more complicated words (I usually do this in the lines following
                   1610: @code{:}).  If you don't do this, your code becomes unreadable (because
1.117     anton    1611: you have to work through every definition before you can understand
1.48      anton    1612: any).
                   1613: 
1.141     anton    1614: @quotation Assignment
1.48      anton    1615: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
                   1616: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
                   1617: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
1.65      anton    1618: are done, you can compare your stack effects to those in this manual
1.48      anton    1619: (@pxref{Word Index}).
1.141     anton    1620: @end quotation
1.48      anton    1621: 
                   1622: Sometimes programmers put comments at various places in colon
                   1623: definitions that describe the contents of the stack at that place (stack
                   1624: comments); i.e., they are like the first part of a stack-effect
                   1625: comment. E.g.,
                   1626: 
                   1627: @example
                   1628: : cubed ( n -- n^3 )
                   1629:    dup squared  ( n n^2 ) * ;
                   1630: @end example
                   1631: 
                   1632: In this case the stack comment is pretty superfluous, because the word
                   1633: is simple enough.  If you think it would be a good idea to add such a
                   1634: comment to increase readability, you should also consider factoring the
                   1635: word into several simpler words (@pxref{Factoring Tutorial,,
1.60      anton    1636: Factoring}), which typically eliminates the need for the stack comment;
1.48      anton    1637: however, if you decide not to refactor it, then having such a comment is
                   1638: better than not having it.
                   1639: 
                   1640: The names of the stack items in stack-effect and stack comments in the
                   1641: standard, in this manual, and in many programs specify the type through
                   1642: a type prefix, similar to Fortran and Hungarian notation.  The most
                   1643: frequent prefixes are:
                   1644: 
                   1645: @table @code
                   1646: @item n
                   1647: signed integer
                   1648: @item u
                   1649: unsigned integer
                   1650: @item c
                   1651: character
                   1652: @item f
                   1653: Boolean flags, i.e. @code{false} or @code{true}.
                   1654: @item a-addr,a-
                   1655: Cell-aligned address
                   1656: @item c-addr,c-
                   1657: Char-aligned address (note that a Char may have two bytes in Windows NT)
                   1658: @item xt
                   1659: Execution token, same size as Cell
                   1660: @item w,x
                   1661: Cell, can contain an integer or an address.  It usually takes 32, 64 or
                   1662: 16 bits (depending on your platform and Forth system). A cell is more
                   1663: commonly known as machine word, but the term @emph{word} already means
                   1664: something different in Forth.
                   1665: @item d
                   1666: signed double-cell integer
                   1667: @item ud
                   1668: unsigned double-cell integer
                   1669: @item r
                   1670: Float (on the FP stack)
                   1671: @end table
                   1672: 
                   1673: You can find a more complete list in @ref{Notation}.
                   1674: 
1.141     anton    1675: @quotation Assignment
1.48      anton    1676: Write stack-effect comments for all definitions you have written up to
                   1677: now.
1.141     anton    1678: @end quotation
1.48      anton    1679: 
                   1680: 
                   1681: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
                   1682: @section Types
1.66      anton    1683: @cindex types tutorial
1.48      anton    1684: 
                   1685: In Forth the names of the operations are not overloaded; so similar
                   1686: operations on different types need different names; e.g., @code{+} adds
                   1687: integers, and you have to use @code{f+} to add floating-point numbers.
                   1688: The following prefixes are often used for related operations on
                   1689: different types:
                   1690: 
                   1691: @table @code
                   1692: @item (none)
                   1693: signed integer
                   1694: @item u
                   1695: unsigned integer
                   1696: @item c
                   1697: character
                   1698: @item d
                   1699: signed double-cell integer
                   1700: @item ud, du
                   1701: unsigned double-cell integer
                   1702: @item 2
                   1703: two cells (not-necessarily double-cell numbers)
                   1704: @item m, um
                   1705: mixed single-cell and double-cell operations
                   1706: @item f
                   1707: floating-point (note that in stack comments @samp{f} represents flags,
1.66      anton    1708: and @samp{r} represents FP numbers).
1.48      anton    1709: @end table
                   1710: 
                   1711: If there are no differences between the signed and the unsigned variant
                   1712: (e.g., for @code{+}), there is only the prefix-less variant.
                   1713: 
                   1714: Forth does not perform type checking, neither at compile time, nor at
                   1715: run time.  If you use the wrong oeration, the data are interpreted
                   1716: incorrectly:
                   1717: 
                   1718: @example
                   1719: -1 u.
                   1720: @end example
                   1721: 
                   1722: If you have only experience with type-checked languages until now, and
                   1723: have heard how important type-checking is, don't panic!  In my
                   1724: experience (and that of other Forthers), type errors in Forth code are
                   1725: usually easy to find (once you get used to it), the increased vigilance
                   1726: of the programmer tends to catch some harder errors in addition to most
                   1727: type errors, and you never have to work around the type system, so in
                   1728: most situations the lack of type-checking seems to be a win (projects to
                   1729: add type checking to Forth have not caught on).
                   1730: 
                   1731: 
                   1732: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
                   1733: @section Factoring
1.66      anton    1734: @cindex factoring tutorial
1.48      anton    1735: 
                   1736: If you try to write longer definitions, you will soon find it hard to
                   1737: keep track of the stack contents.  Therefore, good Forth programmers
                   1738: tend to write only short definitions (e.g., three lines).  The art of
                   1739: finding meaningful short definitions is known as factoring (as in
                   1740: factoring polynomials).
                   1741: 
                   1742: Well-factored programs offer additional advantages: smaller, more
                   1743: general words, are easier to test and debug and can be reused more and
                   1744: better than larger, specialized words.
                   1745: 
                   1746: So, if you run into difficulties with stack management, when writing
                   1747: code, try to define meaningful factors for the word, and define the word
                   1748: in terms of those.  Even if a factor contains only two words, it is
                   1749: often helpful.
                   1750: 
1.65      anton    1751: Good factoring is not easy, and it takes some practice to get the knack
                   1752: for it; but even experienced Forth programmers often don't find the
                   1753: right solution right away, but only when rewriting the program.  So, if
                   1754: you don't come up with a good solution immediately, keep trying, don't
                   1755: despair.
1.48      anton    1756: 
                   1757: @c example !!
                   1758: 
                   1759: 
                   1760: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
                   1761: @section Designing the stack effect
1.66      anton    1762: @cindex Stack effect design, tutorial
                   1763: @cindex design of stack effects, tutorial
1.48      anton    1764: 
                   1765: In other languages you can use an arbitrary order of parameters for a
1.65      anton    1766: function; and since there is only one result, you don't have to deal with
1.48      anton    1767: the order of results, either.
                   1768: 
1.117     anton    1769: In Forth (and other stack-based languages, e.g., PostScript) the
1.48      anton    1770: parameter and result order of a definition is important and should be
                   1771: designed well.  The general guideline is to design the stack effect such
                   1772: that the word is simple to use in most cases, even if that complicates
                   1773: the implementation of the word.  Some concrete rules are:
                   1774: 
                   1775: @itemize @bullet
                   1776: 
                   1777: @item
                   1778: Words consume all of their parameters (e.g., @code{.}).
                   1779: 
                   1780: @item
                   1781: If there is a convention on the order of parameters (e.g., from
                   1782: mathematics or another programming language), stick with it (e.g.,
                   1783: @code{-}).
                   1784: 
                   1785: @item
                   1786: If one parameter usually requires only a short computation (e.g., it is
                   1787: a constant), pass it on the top of the stack.  Conversely, parameters
                   1788: that usually require a long sequence of code to compute should be passed
                   1789: as the bottom (i.e., first) parameter.  This makes the code easier to
1.171     anton    1790: read, because the reader does not need to keep track of the bottom item
1.48      anton    1791: through a long sequence of code (or, alternatively, through stack
1.49      anton    1792: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48      anton    1793: address on top of the stack because it is usually simpler to compute
                   1794: than the stored value (often the address is just a variable).
                   1795: 
                   1796: @item
                   1797: Similarly, results that are usually consumed quickly should be returned
                   1798: on the top of stack, whereas a result that is often used in long
                   1799: computations should be passed as bottom result.  E.g., the file words
                   1800: like @code{open-file} return the error code on the top of stack, because
                   1801: it is usually consumed quickly by @code{throw}; moreover, the error code
                   1802: has to be checked before doing anything with the other results.
                   1803: 
                   1804: @end itemize
                   1805: 
                   1806: These rules are just general guidelines, don't lose sight of the overall
                   1807: goal to make the words easy to use.  E.g., if the convention rule
                   1808: conflicts with the computation-length rule, you might decide in favour
                   1809: of the convention if the word will be used rarely, and in favour of the
                   1810: computation-length rule if the word will be used frequently (because
                   1811: with frequent use the cost of breaking the computation-length rule would
                   1812: be quite high, and frequent use makes it easier to remember an
                   1813: unconventional order).
                   1814: 
                   1815: @c example !! structure package
                   1816: 
1.65      anton    1817: 
1.48      anton    1818: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
                   1819: @section Local Variables
1.66      anton    1820: @cindex local variables, tutorial
1.48      anton    1821: 
                   1822: You can define local variables (@emph{locals}) in a colon definition:
                   1823: 
                   1824: @example
                   1825: : swap @{ a b -- b a @}
                   1826:   b a ;
                   1827: 1 2 swap .s 2drop
                   1828: @end example
                   1829: 
                   1830: (If your Forth system does not support this syntax, include
                   1831: @file{compat/anslocals.fs} first).
                   1832: 
                   1833: In this example @code{@{ a b -- b a @}} is the locals definition; it
                   1834: takes two cells from the stack, puts the top of stack in @code{b} and
                   1835: the next stack element in @code{a}.  @code{--} starts a comment ending
                   1836: with @code{@}}.  After the locals definition, using the name of the
                   1837: local will push its value on the stack.  You can leave the comment
                   1838: part (@code{-- b a}) away:
                   1839: 
                   1840: @example
                   1841: : swap ( x1 x2 -- x2 x1 )
                   1842:   @{ a b @} b a ;
                   1843: @end example
                   1844: 
                   1845: In Gforth you can have several locals definitions, anywhere in a colon
                   1846: definition; in contrast, in a standard program you can have only one
                   1847: locals definition per colon definition, and that locals definition must
1.163     anton    1848: be outside any control structure.
1.48      anton    1849: 
                   1850: With locals you can write slightly longer definitions without running
                   1851: into stack trouble.  However, I recommend trying to write colon
                   1852: definitions without locals for exercise purposes to help you gain the
                   1853: essential factoring skills.
                   1854: 
1.141     anton    1855: @quotation Assignment
1.48      anton    1856: Rewrite your definitions until now with locals
1.141     anton    1857: @end quotation
1.48      anton    1858: 
1.66      anton    1859: Reference: @ref{Locals}.
                   1860: 
1.48      anton    1861: 
                   1862: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
                   1863: @section Conditional execution
1.66      anton    1864: @cindex conditionals, tutorial
                   1865: @cindex if, tutorial
1.48      anton    1866: 
                   1867: In Forth you can use control structures only inside colon definitions.
                   1868: An @code{if}-structure looks like this:
                   1869: 
                   1870: @example
                   1871: : abs ( n1 -- +n2 )
                   1872:     dup 0 < if
                   1873:         negate
                   1874:     endif ;
                   1875: 5 abs .
                   1876: -5 abs .
                   1877: @end example
                   1878: 
                   1879: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
                   1880: the following code is performed, otherwise execution continues after the
1.51      pazsan   1881: @code{endif} (or @code{else}).  @code{<} compares the top two stack
1.171     anton    1882: elements and produces a flag:
1.48      anton    1883: 
                   1884: @example
                   1885: 1 2 < .
                   1886: 2 1 < .
                   1887: 1 1 < .
                   1888: @end example
                   1889: 
                   1890: Actually the standard name for @code{endif} is @code{then}.  This
                   1891: tutorial presents the examples using @code{endif}, because this is often
                   1892: less confusing for people familiar with other programming languages
                   1893: where @code{then} has a different meaning.  If your system does not have
                   1894: @code{endif}, define it with
                   1895: 
                   1896: @example
                   1897: : endif postpone then ; immediate
                   1898: @end example
                   1899: 
                   1900: You can optionally use an @code{else}-part:
                   1901: 
                   1902: @example
                   1903: : min ( n1 n2 -- n )
                   1904:   2dup < if
                   1905:     drop
                   1906:   else
                   1907:     nip
                   1908:   endif ;
                   1909: 2 3 min .
                   1910: 3 2 min .
                   1911: @end example
                   1912: 
1.141     anton    1913: @quotation Assignment
1.48      anton    1914: Write @code{min} without @code{else}-part (hint: what's the definition
                   1915: of @code{nip}?).
1.141     anton    1916: @end quotation
1.48      anton    1917: 
1.66      anton    1918: Reference: @ref{Selection}.
                   1919: 
1.48      anton    1920: 
                   1921: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
                   1922: @section Flags and Comparisons
1.66      anton    1923: @cindex flags tutorial
                   1924: @cindex comparison tutorial
1.48      anton    1925: 
                   1926: In a false-flag all bits are clear (0 when interpreted as integer).  In
                   1927: a canonical true-flag all bits are set (-1 as a twos-complement signed
                   1928: integer); in many contexts (e.g., @code{if}) any non-zero value is
                   1929: treated as true flag.
                   1930: 
                   1931: @example
                   1932: false .
                   1933: true .
                   1934: true hex u. decimal
                   1935: @end example
                   1936: 
                   1937: Comparison words produce canonical flags:
                   1938: 
                   1939: @example
                   1940: 1 1 = .
                   1941: 1 0= .
                   1942: 0 1 < .
                   1943: 0 0 < .
                   1944: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
                   1945: -1 1 < .
                   1946: @end example
                   1947: 
1.66      anton    1948: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
                   1949: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
                   1950: these combinations are standard (for details see the standard,
                   1951: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48      anton    1952: 
1.171     anton    1953: You can use @code{and or xor invert} as operations on canonical flags.
                   1954: Actually they are bitwise operations:
1.48      anton    1955: 
                   1956: @example
                   1957: 1 2 and .
                   1958: 1 2 or .
                   1959: 1 3 xor .
                   1960: 1 invert .
                   1961: @end example
                   1962: 
                   1963: You can convert a zero/non-zero flag into a canonical flag with
                   1964: @code{0<>} (and complement it on the way with @code{0=}).
                   1965: 
                   1966: @example
                   1967: 1 0= .
                   1968: 1 0<> .
                   1969: @end example
                   1970: 
1.65      anton    1971: You can use the all-bits-set feature of canonical flags and the bitwise
1.48      anton    1972: operation of the Boolean operations to avoid @code{if}s:
                   1973: 
                   1974: @example
                   1975: : foo ( n1 -- n2 )
                   1976:   0= if
                   1977:     14
                   1978:   else
                   1979:     0
                   1980:   endif ;
                   1981: 0 foo .
                   1982: 1 foo .
                   1983: 
                   1984: : foo ( n1 -- n2 )
                   1985:   0= 14 and ;
                   1986: 0 foo .
                   1987: 1 foo .
                   1988: @end example
                   1989: 
1.141     anton    1990: @quotation Assignment
1.48      anton    1991: Write @code{min} without @code{if}.
1.141     anton    1992: @end quotation
1.48      anton    1993: 
1.66      anton    1994: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
                   1995: @ref{Bitwise operations}.
                   1996: 
1.48      anton    1997: 
                   1998: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
                   1999: @section General Loops
1.66      anton    2000: @cindex loops, indefinite, tutorial
1.48      anton    2001: 
                   2002: The endless loop is the most simple one:
                   2003: 
                   2004: @example
                   2005: : endless ( -- )
                   2006:   0 begin
                   2007:     dup . 1+
                   2008:   again ;
                   2009: endless
                   2010: @end example
                   2011: 
                   2012: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
                   2013: does nothing at run-time, @code{again} jumps back to @code{begin}.
                   2014: 
                   2015: A loop with one exit at any place looks like this:
                   2016: 
                   2017: @example
                   2018: : log2 ( +n1 -- n2 )
                   2019: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2020:   assert( dup 0> )
                   2021:   2/ 0 begin
                   2022:     over 0> while
                   2023:       1+ swap 2/ swap
                   2024:   repeat
                   2025:   nip ;
                   2026: 7 log2 .
                   2027: 8 log2 .
                   2028: @end example
                   2029: 
                   2030: At run-time @code{while} consumes a flag; if it is 0, execution
1.51      pazsan   2031: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48      anton    2032: continues behind the @code{while}.  @code{Repeat} jumps back to
                   2033: @code{begin}, just like @code{again}.
                   2034: 
                   2035: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90      anton    2036: However, @code{2/} is not one of them; it shifts its argument right by
1.48      anton    2037: one bit (arithmetic shift right):
                   2038: 
                   2039: @example
                   2040: -5 2 / .
                   2041: -5 2/ .
                   2042: @end example
                   2043: 
                   2044: @code{assert(} is no standard word, but you can get it on systems other
                   2045: then Gforth by including @file{compat/assert.fs}.  You can see what it
                   2046: does by trying
                   2047: 
                   2048: @example
                   2049: 0 log2 .
                   2050: @end example
                   2051: 
                   2052: Here's a loop with an exit at the end:
                   2053: 
                   2054: @example
                   2055: : log2 ( +n1 -- n2 )
                   2056: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2057:   assert( dup 0 > )
                   2058:   -1 begin
                   2059:     1+ swap 2/ swap
                   2060:     over 0 <=
                   2061:   until
                   2062:   nip ;
                   2063: @end example
                   2064: 
                   2065: @code{Until} consumes a flag; if it is non-zero, execution continues at
                   2066: the @code{begin}, otherwise after the @code{until}.
                   2067: 
1.141     anton    2068: @quotation Assignment
1.48      anton    2069: Write a definition for computing the greatest common divisor.
1.141     anton    2070: @end quotation
1.48      anton    2071: 
1.66      anton    2072: Reference: @ref{Simple Loops}.
                   2073: 
1.48      anton    2074: 
                   2075: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
                   2076: @section Counted loops
1.66      anton    2077: @cindex loops, counted, tutorial
1.48      anton    2078: 
                   2079: @example
                   2080: : ^ ( n1 u -- n )
1.171     anton    2081: \ n = the uth power of n1
1.48      anton    2082:   1 swap 0 u+do
                   2083:     over *
                   2084:   loop
                   2085:   nip ;
                   2086: 3 2 ^ .
                   2087: 4 3 ^ .
                   2088: @end example
                   2089: 
                   2090: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
                   2091: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
                   2092: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
                   2093: times (or not at all, if @code{u3-u4<0}).
                   2094: 
                   2095: You can see the stack effect design rules at work in the stack effect of
                   2096: the loop start words: Since the start value of the loop is more
                   2097: frequently constant than the end value, the start value is passed on
                   2098: the top-of-stack.
                   2099: 
                   2100: You can access the counter of a counted loop with @code{i}:
                   2101: 
                   2102: @example
                   2103: : fac ( u -- u! )
                   2104:   1 swap 1+ 1 u+do
                   2105:     i *
                   2106:   loop ;
                   2107: 5 fac .
                   2108: 7 fac .
                   2109: @end example
                   2110: 
                   2111: There is also @code{+do}, which expects signed numbers (important for
                   2112: deciding whether to enter the loop).
                   2113: 
1.141     anton    2114: @quotation Assignment
1.48      anton    2115: Write a definition for computing the nth Fibonacci number.
1.141     anton    2116: @end quotation
1.48      anton    2117: 
1.65      anton    2118: You can also use increments other than 1:
                   2119: 
                   2120: @example
                   2121: : up2 ( n1 n2 -- )
                   2122:   +do
                   2123:     i .
                   2124:   2 +loop ;
                   2125: 10 0 up2
                   2126: 
                   2127: : down2 ( n1 n2 -- )
                   2128:   -do
                   2129:     i .
                   2130:   2 -loop ;
                   2131: 0 10 down2
                   2132: @end example
1.48      anton    2133: 
1.66      anton    2134: Reference: @ref{Counted Loops}.
                   2135: 
1.48      anton    2136: 
                   2137: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
                   2138: @section Recursion
1.66      anton    2139: @cindex recursion tutorial
1.48      anton    2140: 
                   2141: Usually the name of a definition is not visible in the definition; but
                   2142: earlier definitions are usually visible:
                   2143: 
                   2144: @example
1.166     anton    2145: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
1.48      anton    2146: : / ( n1 n2 -- n )
                   2147:   dup 0= if
                   2148:     -10 throw \ report division by zero
                   2149:   endif
                   2150:   /           \ old version
                   2151: ;
                   2152: 1 0 /
                   2153: @end example
                   2154: 
                   2155: For recursive definitions you can use @code{recursive} (non-standard) or
                   2156: @code{recurse}:
                   2157: 
                   2158: @example
                   2159: : fac1 ( n -- n! ) recursive
                   2160:  dup 0> if
                   2161:    dup 1- fac1 *
                   2162:  else
                   2163:    drop 1
                   2164:  endif ;
                   2165: 7 fac1 .
                   2166: 
                   2167: : fac2 ( n -- n! )
                   2168:  dup 0> if
                   2169:    dup 1- recurse *
                   2170:  else
                   2171:    drop 1
                   2172:  endif ;
                   2173: 8 fac2 .
                   2174: @end example
                   2175: 
1.141     anton    2176: @quotation Assignment
1.48      anton    2177: Write a recursive definition for computing the nth Fibonacci number.
1.141     anton    2178: @end quotation
1.48      anton    2179: 
1.66      anton    2180: Reference (including indirect recursion): @xref{Calls and returns}.
                   2181: 
1.48      anton    2182: 
                   2183: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
                   2184: @section Leaving definitions or loops
1.66      anton    2185: @cindex leaving definitions, tutorial
                   2186: @cindex leaving loops, tutorial
1.48      anton    2187: 
                   2188: @code{EXIT} exits the current definition right away.  For every counted
                   2189: loop that is left in this way, an @code{UNLOOP} has to be performed
                   2190: before the @code{EXIT}:
                   2191: 
                   2192: @c !! real examples
                   2193: @example
                   2194: : ...
                   2195:  ... u+do
                   2196:    ... if
                   2197:      ... unloop exit
                   2198:    endif
                   2199:    ...
                   2200:  loop
                   2201:  ... ;
                   2202: @end example
                   2203: 
                   2204: @code{LEAVE} leaves the innermost counted loop right away:
                   2205: 
                   2206: @example
                   2207: : ...
                   2208:  ... u+do
                   2209:    ... if
                   2210:      ... leave
                   2211:    endif
                   2212:    ...
                   2213:  loop
                   2214:  ... ;
                   2215: @end example
                   2216: 
1.65      anton    2217: @c !! example
1.48      anton    2218: 
1.66      anton    2219: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
                   2220: 
                   2221: 
1.48      anton    2222: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
                   2223: @section Return Stack
1.66      anton    2224: @cindex return stack tutorial
1.48      anton    2225: 
                   2226: In addition to the data stack Forth also has a second stack, the return
                   2227: stack; most Forth systems store the return addresses of procedure calls
                   2228: there (thus its name).  Programmers can also use this stack:
                   2229: 
                   2230: @example
                   2231: : foo ( n1 n2 -- )
                   2232:  .s
                   2233:  >r .s
1.50      anton    2234:  r@@ .
1.48      anton    2235:  >r .s
1.50      anton    2236:  r@@ .
1.48      anton    2237:  r> .
1.50      anton    2238:  r@@ .
1.48      anton    2239:  r> . ;
                   2240: 1 2 foo
                   2241: @end example
                   2242: 
                   2243: @code{>r} takes an element from the data stack and pushes it onto the
                   2244: return stack; conversely, @code{r>} moves an elementm from the return to
                   2245: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148     anton    2246: on the data stack.
1.48      anton    2247: 
                   2248: Forth programmers usually use the return stack for storing data
                   2249: temporarily, if using the data stack alone would be too complex, and
                   2250: factoring and locals are not an option:
                   2251: 
                   2252: @example
                   2253: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
                   2254:  rot >r rot r> ;
                   2255: @end example
                   2256: 
                   2257: The return address of the definition and the loop control parameters of
                   2258: counted loops usually reside on the return stack, so you have to take
                   2259: all items, that you have pushed on the return stack in a colon
                   2260: definition or counted loop, from the return stack before the definition
                   2261: or loop ends.  You cannot access items that you pushed on the return
                   2262: stack outside some definition or loop within the definition of loop.
                   2263: 
                   2264: If you miscount the return stack items, this usually ends in a crash:
                   2265: 
                   2266: @example
                   2267: : crash ( n -- )
                   2268:   >r ;
                   2269: 5 crash
                   2270: @end example
                   2271: 
                   2272: You cannot mix using locals and using the return stack (according to the
                   2273: standard; Gforth has no problem).  However, they solve the same
                   2274: problems, so this shouldn't be an issue.
                   2275: 
1.141     anton    2276: @quotation Assignment
1.48      anton    2277: Can you rewrite any of the definitions you wrote until now in a better
                   2278: way using the return stack?
1.141     anton    2279: @end quotation
1.48      anton    2280: 
1.66      anton    2281: Reference: @ref{Return stack}.
                   2282: 
1.48      anton    2283: 
                   2284: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
                   2285: @section Memory
1.66      anton    2286: @cindex memory access/allocation tutorial
1.48      anton    2287: 
                   2288: You can create a global variable @code{v} with
                   2289: 
                   2290: @example
                   2291: variable v ( -- addr )
                   2292: @end example
                   2293: 
                   2294: @code{v} pushes the address of a cell in memory on the stack.  This cell
                   2295: was reserved by @code{variable}.  You can use @code{!} (store) to store
                   2296: values into this cell and @code{@@} (fetch) to load the value from the
                   2297: stack into memory:
                   2298: 
                   2299: @example
                   2300: v .
                   2301: 5 v ! .s
1.50      anton    2302: v @@ .
1.48      anton    2303: @end example
                   2304: 
1.65      anton    2305: You can see a raw dump of memory with @code{dump}:
                   2306: 
                   2307: @example
                   2308: v 1 cells .s dump
                   2309: @end example
                   2310: 
                   2311: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
                   2312: generally, address units (aus)) that @code{n1 cells} occupy.  You can
                   2313: also reserve more memory:
1.48      anton    2314: 
                   2315: @example
                   2316: create v2 20 cells allot
1.65      anton    2317: v2 20 cells dump
1.48      anton    2318: @end example
                   2319: 
1.65      anton    2320: creates a word @code{v2} and reserves 20 uninitialized cells; the
                   2321: address pushed by @code{v2} points to the start of these 20 cells.  You
                   2322: can use address arithmetic to access these cells:
1.48      anton    2323: 
                   2324: @example
                   2325: 3 v2 5 cells + !
1.65      anton    2326: v2 20 cells dump
1.48      anton    2327: @end example
                   2328: 
                   2329: You can reserve and initialize memory with @code{,}:
                   2330: 
                   2331: @example
                   2332: create v3
                   2333:   5 , 4 , 3 , 2 , 1 ,
1.50      anton    2334: v3 @@ .
                   2335: v3 cell+ @@ .
                   2336: v3 2 cells + @@ .
1.65      anton    2337: v3 5 cells dump
1.48      anton    2338: @end example
                   2339: 
1.141     anton    2340: @quotation Assignment
1.48      anton    2341: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
                   2342: @code{u} cells, with the first of these cells at @code{addr}, the next
                   2343: one at @code{addr cell+} etc.
1.141     anton    2344: @end quotation
1.48      anton    2345: 
                   2346: You can also reserve memory without creating a new word:
                   2347: 
                   2348: @example
1.60      anton    2349: here 10 cells allot .
                   2350: here .
1.48      anton    2351: @end example
                   2352: 
                   2353: @code{Here} pushes the start address of the memory area.  You should
                   2354: store it somewhere, or you will have a hard time finding the memory area
                   2355: again.
                   2356: 
                   2357: @code{Allot} manages dictionary memory.  The dictionary memory contains
                   2358: the system's data structures for words etc. on Gforth and most other
                   2359: Forth systems.  It is managed like a stack: You can free the memory that
                   2360: you have just @code{allot}ed with
                   2361: 
                   2362: @example
                   2363: -10 cells allot
1.60      anton    2364: here .
1.48      anton    2365: @end example
                   2366: 
                   2367: Note that you cannot do this if you have created a new word in the
                   2368: meantime (because then your @code{allot}ed memory is no longer on the
                   2369: top of the dictionary ``stack'').
                   2370: 
                   2371: Alternatively, you can use @code{allocate} and @code{free} which allow
                   2372: freeing memory in any order:
                   2373: 
                   2374: @example
                   2375: 10 cells allocate throw .s
                   2376: 20 cells allocate throw .s
                   2377: swap
                   2378: free throw
                   2379: free throw
                   2380: @end example
                   2381: 
                   2382: The @code{throw}s deal with errors (e.g., out of memory).
                   2383: 
1.65      anton    2384: And there is also a
                   2385: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   2386: garbage collector}, which eliminates the need to @code{free} memory
                   2387: explicitly.
1.48      anton    2388: 
1.66      anton    2389: Reference: @ref{Memory}.
                   2390: 
1.48      anton    2391: 
                   2392: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
                   2393: @section Characters and Strings
1.66      anton    2394: @cindex strings tutorial
                   2395: @cindex characters tutorial
1.48      anton    2396: 
                   2397: On the stack characters take up a cell, like numbers.  In memory they
                   2398: have their own size (one 8-bit byte on most systems), and therefore
                   2399: require their own words for memory access:
                   2400: 
                   2401: @example
                   2402: create v4 
                   2403:   104 c, 97 c, 108 c, 108 c, 111 c,
1.50      anton    2404: v4 4 chars + c@@ .
1.65      anton    2405: v4 5 chars dump
1.48      anton    2406: @end example
                   2407: 
                   2408: The preferred representation of strings on the stack is @code{addr
                   2409: u-count}, where @code{addr} is the address of the first character and
                   2410: @code{u-count} is the number of characters in the string.
                   2411: 
                   2412: @example
                   2413: v4 5 type
                   2414: @end example
                   2415: 
                   2416: You get a string constant with
                   2417: 
                   2418: @example
                   2419: s" hello, world" .s
                   2420: type
                   2421: @end example
                   2422: 
                   2423: Make sure you have a space between @code{s"} and the string; @code{s"}
                   2424: is a normal Forth word and must be delimited with white space (try what
                   2425: happens when you remove the space).
                   2426: 
                   2427: However, this interpretive use of @code{s"} is quite restricted: the
                   2428: string exists only until the next call of @code{s"} (some Forth systems
                   2429: keep more than one of these strings, but usually they still have a
1.62      crook    2430: limited lifetime).
1.48      anton    2431: 
                   2432: @example
                   2433: s" hello," s" world" .s
                   2434: type
                   2435: type
                   2436: @end example
                   2437: 
1.62      crook    2438: You can also use @code{s"} in a definition, and the resulting
                   2439: strings then live forever (well, for as long as the definition):
1.48      anton    2440: 
                   2441: @example
                   2442: : foo s" hello," s" world" ;
                   2443: foo .s
                   2444: type
                   2445: type
                   2446: @end example
                   2447: 
1.141     anton    2448: @quotation Assignment
1.48      anton    2449: @code{Emit ( c -- )} types @code{c} as character (not a number).
                   2450: Implement @code{type ( addr u -- )}.
1.141     anton    2451: @end quotation
1.48      anton    2452: 
1.66      anton    2453: Reference: @ref{Memory Blocks}.
                   2454: 
                   2455: 
1.84      pazsan   2456: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48      anton    2457: @section Alignment
1.66      anton    2458: @cindex alignment tutorial
                   2459: @cindex memory alignment tutorial
1.48      anton    2460: 
                   2461: On many processors cells have to be aligned in memory, if you want to
                   2462: access them with @code{@@} and @code{!} (and even if the processor does
1.62      crook    2463: not require alignment, access to aligned cells is faster).
1.48      anton    2464: 
                   2465: @code{Create} aligns @code{here} (i.e., the place where the next
                   2466: allocation will occur, and that the @code{create}d word points to).
                   2467: Likewise, the memory produced by @code{allocate} starts at an aligned
                   2468: address.  Adding a number of @code{cells} to an aligned address produces
                   2469: another aligned address.
                   2470: 
                   2471: However, address arithmetic involving @code{char+} and @code{chars} can
                   2472: create an address that is not cell-aligned.  @code{Aligned ( addr --
                   2473: a-addr )} produces the next aligned address:
                   2474: 
                   2475: @example
1.50      anton    2476: v3 char+ aligned .s @@ .
                   2477: v3 char+ .s @@ .
1.48      anton    2478: @end example
                   2479: 
                   2480: Similarly, @code{align} advances @code{here} to the next aligned
                   2481: address:
                   2482: 
                   2483: @example
                   2484: create v5 97 c,
                   2485: here .
                   2486: align here .
                   2487: 1000 ,
                   2488: @end example
                   2489: 
                   2490: Note that you should use aligned addresses even if your processor does
                   2491: not require them, if you want your program to be portable.
                   2492: 
1.66      anton    2493: Reference: @ref{Address arithmetic}.
                   2494: 
1.48      anton    2495: 
1.84      pazsan   2496: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
                   2497: @section Files
                   2498: @cindex files tutorial
                   2499: 
                   2500: This section gives a short introduction into how to use files inside
                   2501: Forth. It's broken up into five easy steps:
                   2502: 
                   2503: @enumerate 1
                   2504: @item Opened an ASCII text file for input
                   2505: @item Opened a file for output
                   2506: @item Read input file until string matched (or some other condition matched)
                   2507: @item Wrote some lines from input ( modified or not) to output
                   2508: @item Closed the files.
                   2509: @end enumerate
                   2510: 
1.153     anton    2511: Reference: @ref{General files}.
                   2512: 
1.84      pazsan   2513: @subsection Open file for input
                   2514: 
                   2515: @example
                   2516: s" foo.in"  r/o open-file throw Value fd-in
                   2517: @end example
                   2518: 
                   2519: @subsection Create file for output
                   2520: 
                   2521: @example
                   2522: s" foo.out" w/o create-file throw Value fd-out
                   2523: @end example
                   2524: 
                   2525: The available file modes are r/o for read-only access, r/w for
                   2526: read-write access, and w/o for write-only access. You could open both
                   2527: files with r/w, too, if you like. All file words return error codes; for
                   2528: most applications, it's best to pass there error codes with @code{throw}
                   2529: to the outer error handler.
                   2530: 
                   2531: If you want words for opening and assigning, define them as follows:
                   2532: 
                   2533: @example
                   2534: 0 Value fd-in
                   2535: 0 Value fd-out
                   2536: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
                   2537: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
                   2538: @end example
                   2539: 
                   2540: Usage example:
                   2541: 
                   2542: @example
                   2543: s" foo.in" open-input
                   2544: s" foo.out" open-output
                   2545: @end example
                   2546: 
                   2547: @subsection Scan file for a particular line
                   2548: 
                   2549: @example
                   2550: 256 Constant max-line
                   2551: Create line-buffer  max-line 2 + allot
                   2552: 
                   2553: : scan-file ( addr u -- )
                   2554:   begin
                   2555:       line-buffer max-line fd-in read-line throw
                   2556:   while
                   2557:          >r 2dup line-buffer r> compare 0=
                   2558:      until
                   2559:   else
                   2560:      drop
                   2561:   then
                   2562:   2drop ;
                   2563: @end example
                   2564: 
                   2565: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94      anton    2566: the buffer at addr, and returns the number of bytes read, a flag that is
                   2567: false when the end of file is reached, and an error code.
1.84      pazsan   2568: 
                   2569: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
                   2570: returns zero if both strings are equal. It returns a positive number if
                   2571: the first string is lexically greater, a negative if the second string
                   2572: is lexically greater.
                   2573: 
                   2574: We haven't seen this loop here; it has two exits. Since the @code{while}
                   2575: exits with the number of bytes read on the stack, we have to clean up
                   2576: that separately; that's after the @code{else}.
                   2577: 
                   2578: Usage example:
                   2579: 
                   2580: @example
                   2581: s" The text I search is here" scan-file
                   2582: @end example
                   2583: 
                   2584: @subsection Copy input to output
                   2585: 
                   2586: @example
                   2587: : copy-file ( -- )
                   2588:   begin
                   2589:       line-buffer max-line fd-in read-line throw
                   2590:   while
                   2591:       line-buffer swap fd-out write-file throw
                   2592:   repeat ;
                   2593: @end example
                   2594: 
                   2595: @subsection Close files
                   2596: 
                   2597: @example
                   2598: fd-in close-file throw
                   2599: fd-out close-file throw
                   2600: @end example
                   2601: 
                   2602: Likewise, you can put that into definitions, too:
                   2603: 
                   2604: @example
                   2605: : close-input ( -- )  fd-in close-file throw ;
                   2606: : close-output ( -- )  fd-out close-file throw ;
                   2607: @end example
                   2608: 
1.141     anton    2609: @quotation Assignment
1.84      pazsan   2610: How could you modify @code{copy-file} so that it copies until a second line is
                   2611: matched? Can you write a program that extracts a section of a text file,
                   2612: given the line that starts and the line that terminates that section?
1.141     anton    2613: @end quotation
1.84      pazsan   2614: 
                   2615: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48      anton    2616: @section Interpretation and Compilation Semantics and Immediacy
1.66      anton    2617: @cindex semantics tutorial
                   2618: @cindex interpretation semantics tutorial
                   2619: @cindex compilation semantics tutorial
                   2620: @cindex immediate, tutorial
1.48      anton    2621: 
                   2622: When a word is compiled, it behaves differently from being interpreted.
                   2623: E.g., consider @code{+}:
                   2624: 
                   2625: @example
                   2626: 1 2 + .
                   2627: : foo + ;
                   2628: @end example
                   2629: 
                   2630: These two behaviours are known as compilation and interpretation
                   2631: semantics.  For normal words (e.g., @code{+}), the compilation semantics
                   2632: is to append the interpretation semantics to the currently defined word
                   2633: (@code{foo} in the example above).  I.e., when @code{foo} is executed
                   2634: later, the interpretation semantics of @code{+} (i.e., adding two
                   2635: numbers) will be performed.
                   2636: 
                   2637: However, there are words with non-default compilation semantics, e.g.,
                   2638: the control-flow words like @code{if}.  You can use @code{immediate} to
                   2639: change the compilation semantics of the last defined word to be equal to
                   2640: the interpretation semantics:
                   2641: 
                   2642: @example
                   2643: : [FOO] ( -- )
                   2644:  5 . ; immediate
                   2645: 
                   2646: [FOO]
                   2647: : bar ( -- )
                   2648:   [FOO] ;
                   2649: bar
                   2650: see bar
                   2651: @end example
                   2652: 
                   2653: Two conventions to mark words with non-default compilation semnatics are
                   2654: names with brackets (more frequently used) and to write them all in
                   2655: upper case (less frequently used).
                   2656: 
                   2657: In Gforth (and many other systems) you can also remove the
                   2658: interpretation semantics with @code{compile-only} (the compilation
                   2659: semantics is derived from the original interpretation semantics):
                   2660: 
                   2661: @example
                   2662: : flip ( -- )
                   2663:  6 . ; compile-only \ but not immediate
                   2664: flip
                   2665: 
                   2666: : flop ( -- )
                   2667:  flip ;
                   2668: flop
                   2669: @end example
                   2670: 
                   2671: In this example the interpretation semantics of @code{flop} is equal to
                   2672: the original interpretation semantics of @code{flip}.
                   2673: 
                   2674: The text interpreter has two states: in interpret state, it performs the
                   2675: interpretation semantics of words it encounters; in compile state, it
                   2676: performs the compilation semantics of these words.
                   2677: 
                   2678: Among other things, @code{:} switches into compile state, and @code{;}
                   2679: switches back to interpret state.  They contain the factors @code{]}
                   2680: (switch to compile state) and @code{[} (switch to interpret state), that
                   2681: do nothing but switch the state.
                   2682: 
                   2683: @example
                   2684: : xxx ( -- )
                   2685:   [ 5 . ]
                   2686: ;
                   2687: 
                   2688: xxx
                   2689: see xxx
                   2690: @end example
                   2691: 
                   2692: These brackets are also the source of the naming convention mentioned
                   2693: above.
                   2694: 
1.66      anton    2695: Reference: @ref{Interpretation and Compilation Semantics}.
                   2696: 
1.48      anton    2697: 
                   2698: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
                   2699: @section Execution Tokens
1.66      anton    2700: @cindex execution tokens tutorial
                   2701: @cindex XT tutorial
1.48      anton    2702: 
                   2703: @code{' word} gives you the execution token (XT) of a word.  The XT is a
                   2704: cell representing the interpretation semantics of a word.  You can
                   2705: execute this semantics with @code{execute}:
                   2706: 
                   2707: @example
                   2708: ' + .s
                   2709: 1 2 rot execute .
                   2710: @end example
                   2711: 
                   2712: The XT is similar to a function pointer in C.  However, parameter
                   2713: passing through the stack makes it a little more flexible:
                   2714: 
                   2715: @example
                   2716: : map-array ( ... addr u xt -- ... )
1.50      anton    2717: \ executes xt ( ... x -- ... ) for every element of the array starting
                   2718: \ at addr and containing u elements
1.48      anton    2719:   @{ xt @}
                   2720:   cells over + swap ?do
1.50      anton    2721:     i @@ xt execute
1.48      anton    2722:   1 cells +loop ;
                   2723: 
                   2724: create a 3 , 4 , 2 , -1 , 4 ,
                   2725: a 5 ' . map-array .s
                   2726: 0 a 5 ' + map-array .
                   2727: s" max-n" environment? drop .s
                   2728: a 5 ' min map-array .
                   2729: @end example
                   2730: 
                   2731: You can use map-array with the XTs of words that consume one element
                   2732: more than they produce.  In theory you can also use it with other XTs,
                   2733: but the stack effect then depends on the size of the array, which is
                   2734: hard to understand.
                   2735: 
1.51      pazsan   2736: Since XTs are cell-sized, you can store them in memory and manipulate
                   2737: them on the stack like other cells.  You can also compile the XT into a
1.48      anton    2738: word with @code{compile,}:
                   2739: 
                   2740: @example
                   2741: : foo1 ( n1 n2 -- n )
                   2742:    [ ' + compile, ] ;
                   2743: see foo
                   2744: @end example
                   2745: 
                   2746: This is non-standard, because @code{compile,} has no compilation
                   2747: semantics in the standard, but it works in good Forth systems.  For the
                   2748: broken ones, use
                   2749: 
                   2750: @example
                   2751: : [compile,] compile, ; immediate
                   2752: 
                   2753: : foo1 ( n1 n2 -- n )
                   2754:    [ ' + ] [compile,] ;
                   2755: see foo
                   2756: @end example
                   2757: 
                   2758: @code{'} is a word with default compilation semantics; it parses the
                   2759: next word when its interpretation semantics are executed, not during
                   2760: compilation:
                   2761: 
                   2762: @example
                   2763: : foo ( -- xt )
                   2764:   ' ;
                   2765: see foo
                   2766: : bar ( ... "word" -- ... )
                   2767:   ' execute ;
                   2768: see bar
1.60      anton    2769: 1 2 bar + .
1.48      anton    2770: @end example
                   2771: 
                   2772: You often want to parse a word during compilation and compile its XT so
                   2773: it will be pushed on the stack at run-time.  @code{[']} does this:
                   2774: 
                   2775: @example
                   2776: : xt-+ ( -- xt )
                   2777:   ['] + ;
                   2778: see xt-+
                   2779: 1 2 xt-+ execute .
                   2780: @end example
                   2781: 
                   2782: Many programmers tend to see @code{'} and the word it parses as one
                   2783: unit, and expect it to behave like @code{[']} when compiled, and are
                   2784: confused by the actual behaviour.  If you are, just remember that the
                   2785: Forth system just takes @code{'} as one unit and has no idea that it is
                   2786: a parsing word (attempts to convenience programmers in this issue have
                   2787: usually resulted in even worse pitfalls, see
1.66      anton    2788: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
                   2789: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48      anton    2790: 
                   2791: Note that the state of the interpreter does not come into play when
1.51      pazsan   2792: creating and executing XTs.  I.e., even when you execute @code{'} in
1.48      anton    2793: compile state, it still gives you the interpretation semantics.  And
                   2794: whatever that state is, @code{execute} performs the semantics
1.66      anton    2795: represented by the XT (i.e., for XTs produced with @code{'} the
                   2796: interpretation semantics).
                   2797: 
                   2798: Reference: @ref{Tokens for Words}.
1.48      anton    2799: 
                   2800: 
                   2801: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
                   2802: @section Exceptions
1.66      anton    2803: @cindex exceptions tutorial
1.48      anton    2804: 
                   2805: @code{throw ( n -- )} causes an exception unless n is zero.
                   2806: 
                   2807: @example
                   2808: 100 throw .s
                   2809: 0 throw .s
                   2810: @end example
                   2811: 
                   2812: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
                   2813: it catches exceptions and pushes the number of the exception on the
                   2814: stack (or 0, if the xt executed without exception).  If there was an
                   2815: exception, the stacks have the same depth as when entering @code{catch}:
                   2816: 
                   2817: @example
                   2818: .s
                   2819: 3 0 ' / catch .s
                   2820: 3 2 ' / catch .s
                   2821: @end example
                   2822: 
1.141     anton    2823: @quotation Assignment
1.48      anton    2824: Try the same with @code{execute} instead of @code{catch}.
1.141     anton    2825: @end quotation
1.48      anton    2826: 
                   2827: @code{Throw} always jumps to the dynamically next enclosing
                   2828: @code{catch}, even if it has to leave several call levels to achieve
                   2829: this:
                   2830: 
                   2831: @example
                   2832: : foo 100 throw ;
                   2833: : foo1 foo ." after foo" ;
1.51      pazsan   2834: : bar ['] foo1 catch ;
1.60      anton    2835: bar .
1.48      anton    2836: @end example
                   2837: 
                   2838: It is often important to restore a value upon leaving a definition, even
                   2839: if the definition is left through an exception.  You can ensure this
                   2840: like this:
                   2841: 
                   2842: @example
                   2843: : ...
                   2844:    save-x
1.51      pazsan   2845:    ['] word-changing-x catch ( ... n )
1.48      anton    2846:    restore-x
                   2847:    ( ... n ) throw ;
                   2848: @end example
                   2849: 
1.172     anton    2850: However, this is still not safe against, e.g., the user pressing
                   2851: @kbd{Ctrl-C} when execution is between the @code{catch} and
                   2852: @code{restore-x}.
                   2853: 
                   2854: Gforth provides an alternative exception handling syntax that is safe
                   2855: against such cases: @code{try ... restore ... endtry}.  If the code
                   2856: between @code{try} and @code{endtry} has an exception, the stack
                   2857: depths are restored, the exception number is pushed on the stack, and
                   2858: the execution continues right after @code{restore}.
1.48      anton    2859: 
1.172     anton    2860: The safer equivalent to the restoration code above is
1.48      anton    2861: 
                   2862: @example
                   2863: : ...
                   2864:   save-x
                   2865:   try
1.92      anton    2866:     word-changing-x 0
1.172     anton    2867:   restore
                   2868:     restore-x
                   2869:   endtry
1.48      anton    2870:   throw ;
                   2871: @end example
                   2872: 
1.66      anton    2873: Reference: @ref{Exception Handling}.
                   2874: 
1.48      anton    2875: 
                   2876: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
                   2877: @section Defining Words
1.66      anton    2878: @cindex defining words tutorial
                   2879: @cindex does> tutorial
                   2880: @cindex create...does> tutorial
                   2881: 
                   2882: @c before semantics?
1.48      anton    2883: 
                   2884: @code{:}, @code{create}, and @code{variable} are definition words: They
                   2885: define other words.  @code{Constant} is another definition word:
                   2886: 
                   2887: @example
                   2888: 5 constant foo
                   2889: foo .
                   2890: @end example
                   2891: 
                   2892: You can also use the prefixes @code{2} (double-cell) and @code{f}
                   2893: (floating point) with @code{variable} and @code{constant}.
                   2894: 
                   2895: You can also define your own defining words.  E.g.:
                   2896: 
                   2897: @example
                   2898: : variable ( "name" -- )
                   2899:   create 0 , ;
                   2900: @end example
                   2901: 
                   2902: You can also define defining words that create words that do something
                   2903: other than just producing their address:
                   2904: 
                   2905: @example
                   2906: : constant ( n "name" -- )
                   2907:   create ,
                   2908: does> ( -- n )
1.50      anton    2909:   ( addr ) @@ ;
1.48      anton    2910: 
                   2911: 5 constant foo
                   2912: foo .
                   2913: @end example
                   2914: 
                   2915: The definition of @code{constant} above ends at the @code{does>}; i.e.,
                   2916: @code{does>} replaces @code{;}, but it also does something else: It
                   2917: changes the last defined word such that it pushes the address of the
                   2918: body of the word and then performs the code after the @code{does>}
                   2919: whenever it is called.
                   2920: 
                   2921: In the example above, @code{constant} uses @code{,} to store 5 into the
                   2922: body of @code{foo}.  When @code{foo} executes, it pushes the address of
                   2923: the body onto the stack, then (in the code after the @code{does>})
                   2924: fetches the 5 from there.
                   2925: 
                   2926: The stack comment near the @code{does>} reflects the stack effect of the
                   2927: defined word, not the stack effect of the code after the @code{does>}
                   2928: (the difference is that the code expects the address of the body that
                   2929: the stack comment does not show).
                   2930: 
                   2931: You can use these definition words to do factoring in cases that involve
                   2932: (other) definition words.  E.g., a field offset is always added to an
                   2933: address.  Instead of defining
                   2934: 
                   2935: @example
                   2936: 2 cells constant offset-field1
                   2937: @end example
                   2938: 
                   2939: and using this like
                   2940: 
                   2941: @example
                   2942: ( addr ) offset-field1 +
                   2943: @end example
                   2944: 
                   2945: you can define a definition word
                   2946: 
                   2947: @example
                   2948: : simple-field ( n "name" -- )
                   2949:   create ,
                   2950: does> ( n1 -- n1+n )
1.50      anton    2951:   ( addr ) @@ + ;
1.48      anton    2952: @end example
1.21      crook    2953: 
1.48      anton    2954: Definition and use of field offsets now look like this:
1.21      crook    2955: 
1.48      anton    2956: @example
                   2957: 2 cells simple-field field1
1.60      anton    2958: create mystruct 4 cells allot
                   2959: mystruct .s field1 .s drop
1.48      anton    2960: @end example
1.21      crook    2961: 
1.48      anton    2962: If you want to do something with the word without performing the code
                   2963: after the @code{does>}, you can access the body of a @code{create}d word
                   2964: with @code{>body ( xt -- addr )}:
1.21      crook    2965: 
1.48      anton    2966: @example
                   2967: : value ( n "name" -- )
                   2968:   create ,
                   2969: does> ( -- n1 )
1.50      anton    2970:   @@ ;
1.48      anton    2971: : to ( n "name" -- )
                   2972:   ' >body ! ;
1.21      crook    2973: 
1.48      anton    2974: 5 value foo
                   2975: foo .
                   2976: 7 to foo
                   2977: foo .
                   2978: @end example
1.21      crook    2979: 
1.141     anton    2980: @quotation Assignment
1.48      anton    2981: Define @code{defer ( "name" -- )}, which creates a word that stores an
                   2982: XT (at the start the XT of @code{abort}), and upon execution
                   2983: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
                   2984: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
                   2985: recursion is one application of @code{defer}.
1.141     anton    2986: @end quotation
1.29      crook    2987: 
1.66      anton    2988: Reference: @ref{User-defined Defining Words}.
                   2989: 
                   2990: 
1.48      anton    2991: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
                   2992: @section Arrays and Records
1.66      anton    2993: @cindex arrays tutorial
                   2994: @cindex records tutorial
                   2995: @cindex structs tutorial
1.29      crook    2996: 
1.48      anton    2997: Forth has no standard words for defining data structures such as arrays
                   2998: and records (structs in C terminology), but you can build them yourself
                   2999: based on address arithmetic.  You can also define words for defining
                   3000: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29      crook    3001: 
1.48      anton    3002: One of the first projects a Forth newcomer sets out upon when learning
                   3003: about defining words is an array defining word (possibly for
                   3004: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
                   3005: learn something from it.  However, don't be disappointed when you later
                   3006: learn that you have little use for these words (inappropriate use would
                   3007: be even worse).  I have not yet found a set of useful array words yet;
                   3008: the needs are just too diverse, and named, global arrays (the result of
                   3009: naive use of defining words) are often not flexible enough (e.g.,
1.66      anton    3010: consider how to pass them as parameters).  Another such project is a set
                   3011: of words to help dealing with strings.
1.29      crook    3012: 
1.48      anton    3013: On the other hand, there is a useful set of record words, and it has
                   3014: been defined in @file{compat/struct.fs}; these words are predefined in
                   3015: Gforth.  They are explained in depth elsewhere in this manual (see
                   3016: @pxref{Structures}).  The @code{simple-field} example above is
                   3017: simplified variant of fields in this package.
1.21      crook    3018: 
                   3019: 
1.48      anton    3020: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
                   3021: @section @code{POSTPONE}
1.66      anton    3022: @cindex postpone tutorial
1.21      crook    3023: 
1.48      anton    3024: You can compile the compilation semantics (instead of compiling the
                   3025: interpretation semantics) of a word with @code{POSTPONE}:
1.21      crook    3026: 
1.48      anton    3027: @example
                   3028: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51      pazsan   3029:  POSTPONE + ; immediate
1.48      anton    3030: : foo ( n1 n2 -- n )
                   3031:  MY-+ ;
                   3032: 1 2 foo .
                   3033: see foo
                   3034: @end example
1.21      crook    3035: 
1.48      anton    3036: During the definition of @code{foo} the text interpreter performs the
                   3037: compilation semantics of @code{MY-+}, which performs the compilation
                   3038: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
                   3039: 
                   3040: This example also displays separate stack comments for the compilation
                   3041: semantics and for the stack effect of the compiled code.  For words with
                   3042: default compilation semantics these stack effects are usually not
                   3043: displayed; the stack effect of the compilation semantics is always
                   3044: @code{( -- )} for these words, the stack effect for the compiled code is
                   3045: the stack effect of the interpretation semantics.
                   3046: 
                   3047: Note that the state of the interpreter does not come into play when
                   3048: performing the compilation semantics in this way.  You can also perform
                   3049: it interpretively, e.g.:
                   3050: 
                   3051: @example
                   3052: : foo2 ( n1 n2 -- n )
                   3053:  [ MY-+ ] ;
                   3054: 1 2 foo .
                   3055: see foo
                   3056: @end example
1.21      crook    3057: 
1.48      anton    3058: However, there are some broken Forth systems where this does not always
1.62      crook    3059: work, and therefore this practice was been declared non-standard in
1.48      anton    3060: 1999.
                   3061: @c !! repair.fs
                   3062: 
                   3063: Here is another example for using @code{POSTPONE}:
1.44      crook    3064: 
1.48      anton    3065: @example
                   3066: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
                   3067:  POSTPONE negate POSTPONE + ; immediate compile-only
                   3068: : bar ( n1 n2 -- n )
                   3069:   MY-- ;
                   3070: 2 1 bar .
                   3071: see bar
                   3072: @end example
1.21      crook    3073: 
1.48      anton    3074: You can define @code{ENDIF} in this way:
1.21      crook    3075: 
1.48      anton    3076: @example
                   3077: : ENDIF ( Compilation: orig -- )
                   3078:   POSTPONE then ; immediate
                   3079: @end example
1.21      crook    3080: 
1.141     anton    3081: @quotation Assignment
1.48      anton    3082: Write @code{MY-2DUP} that has compilation semantics equivalent to
                   3083: @code{2dup}, but compiles @code{over over}.
1.141     anton    3084: @end quotation
1.29      crook    3085: 
1.66      anton    3086: @c !! @xref{Macros} for reference
                   3087: 
                   3088: 
1.48      anton    3089: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
                   3090: @section @code{Literal}
1.66      anton    3091: @cindex literal tutorial
1.29      crook    3092: 
1.48      anton    3093: You cannot @code{POSTPONE} numbers:
1.21      crook    3094: 
1.48      anton    3095: @example
                   3096: : [FOO] POSTPONE 500 ; immediate
1.21      crook    3097: @end example
                   3098: 
1.48      anton    3099: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29      crook    3100: 
1.48      anton    3101: @example
                   3102: : [FOO] ( compilation: --; run-time: -- n )
                   3103:   500 POSTPONE literal ; immediate
1.29      crook    3104: 
1.60      anton    3105: : flip [FOO] ;
1.48      anton    3106: flip .
                   3107: see flip
                   3108: @end example
1.29      crook    3109: 
1.48      anton    3110: @code{LITERAL} consumes a number at compile-time (when it's compilation
                   3111: semantics are executed) and pushes it at run-time (when the code it
                   3112: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
                   3113: number computed at compile time into the current word:
1.29      crook    3114: 
1.48      anton    3115: @example
                   3116: : bar ( -- n )
                   3117:   [ 2 2 + ] literal ;
                   3118: see bar
                   3119: @end example
1.29      crook    3120: 
1.141     anton    3121: @quotation Assignment
1.48      anton    3122: Write @code{]L} which allows writing the example above as @code{: bar (
                   3123: -- n ) [ 2 2 + ]L ;}
1.141     anton    3124: @end quotation
1.48      anton    3125: 
1.66      anton    3126: @c !! @xref{Macros} for reference
                   3127: 
1.48      anton    3128: 
                   3129: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
                   3130: @section Advanced macros
1.66      anton    3131: @cindex macros, advanced tutorial
                   3132: @cindex run-time code generation, tutorial
1.48      anton    3133: 
1.66      anton    3134: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
                   3135: Execution Tokens}.  It frequently performs @code{execute}, a relatively
                   3136: expensive operation in some Forth implementations.  You can use
1.48      anton    3137: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
                   3138: and produce a word that contains the word to be performed directly:
                   3139: 
                   3140: @c use ]] ... [[
                   3141: @example
                   3142: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
                   3143: \ at run-time, execute xt ( ... x -- ... ) for each element of the
                   3144: \ array beginning at addr and containing u elements
                   3145:   @{ xt @}
                   3146:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50      anton    3147:     POSTPONE i POSTPONE @@ xt compile,
1.48      anton    3148:   1 cells POSTPONE literal POSTPONE +loop ;
                   3149: 
                   3150: : sum-array ( addr u -- n )
                   3151:  0 rot rot [ ' + compile-map-array ] ;
                   3152: see sum-array
                   3153: a 5 sum-array .
                   3154: @end example
                   3155: 
                   3156: You can use the full power of Forth for generating the code; here's an
                   3157: example where the code is generated in a loop:
                   3158: 
                   3159: @example
                   3160: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
                   3161: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50      anton    3162:   POSTPONE tuck POSTPONE @@
1.48      anton    3163:   POSTPONE literal POSTPONE * POSTPONE +
                   3164:   POSTPONE swap POSTPONE cell+ ;
                   3165: 
                   3166: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51      pazsan   3167: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48      anton    3168:   0 postpone literal postpone swap
                   3169:   [ ' compile-vmul-step compile-map-array ]
                   3170:   postpone drop ;
                   3171: see compile-vmul
                   3172: 
                   3173: : a-vmul ( addr -- n )
1.51      pazsan   3174: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48      anton    3175:  [ a 5 compile-vmul ] ;
                   3176: see a-vmul
                   3177: a a-vmul .
                   3178: @end example
                   3179: 
                   3180: This example uses @code{compile-map-array} to show off, but you could
1.66      anton    3181: also use @code{map-array} instead (try it now!).
1.48      anton    3182: 
                   3183: You can use this technique for efficient multiplication of large
                   3184: matrices.  In matrix multiplication, you multiply every line of one
                   3185: matrix with every column of the other matrix.  You can generate the code
                   3186: for one line once, and use it for every column.  The only downside of
                   3187: this technique is that it is cumbersome to recover the memory consumed
                   3188: by the generated code when you are done (and in more complicated cases
                   3189: it is not possible portably).
                   3190: 
1.66      anton    3191: @c !! @xref{Macros} for reference
                   3192: 
                   3193: 
1.48      anton    3194: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
                   3195: @section Compilation Tokens
1.66      anton    3196: @cindex compilation tokens, tutorial
                   3197: @cindex CT, tutorial
1.48      anton    3198: 
                   3199: This section is Gforth-specific.  You can skip it.
                   3200: 
                   3201: @code{' word compile,} compiles the interpretation semantics.  For words
                   3202: with default compilation semantics this is the same as performing the
                   3203: compilation semantics.  To represent the compilation semantics of other
                   3204: words (e.g., words like @code{if} that have no interpretation
                   3205: semantics), Gforth has the concept of a compilation token (CT,
                   3206: consisting of two cells), and words @code{comp'} and @code{[comp']}.
                   3207: You can perform the compilation semantics represented by a CT with
                   3208: @code{execute}:
1.29      crook    3209: 
1.48      anton    3210: @example
                   3211: : foo2 ( n1 n2 -- n )
                   3212:    [ comp' + execute ] ;
                   3213: see foo
                   3214: @end example
1.29      crook    3215: 
1.48      anton    3216: You can compile the compilation semantics represented by a CT with
                   3217: @code{postpone,}:
1.30      anton    3218: 
1.48      anton    3219: @example
                   3220: : foo3 ( -- )
                   3221:   [ comp' + postpone, ] ;
                   3222: see foo3
                   3223: @end example
1.30      anton    3224: 
1.51      pazsan   3225: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48      anton    3226: @code{comp'} is particularly useful for words that have no
                   3227: interpretation semantics:
1.29      crook    3228: 
1.30      anton    3229: @example
1.48      anton    3230: ' if
1.60      anton    3231: comp' if .s 2drop
1.30      anton    3232: @end example
                   3233: 
1.66      anton    3234: Reference: @ref{Tokens for Words}.
                   3235: 
1.29      crook    3236: 
1.48      anton    3237: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
                   3238: @section Wordlists and Search Order
1.66      anton    3239: @cindex wordlists tutorial
                   3240: @cindex search order, tutorial
1.48      anton    3241: 
                   3242: The dictionary is not just a memory area that allows you to allocate
                   3243: memory with @code{allot}, it also contains the Forth words, arranged in
                   3244: several wordlists.  When searching for a word in a wordlist,
                   3245: conceptually you start searching at the youngest and proceed towards
                   3246: older words (in reality most systems nowadays use hash-tables); i.e., if
                   3247: you define a word with the same name as an older word, the new word
                   3248: shadows the older word.
                   3249: 
                   3250: Which wordlists are searched in which order is determined by the search
                   3251: order.  You can display the search order with @code{order}.  It displays
                   3252: first the search order, starting with the wordlist searched first, then
                   3253: it displays the wordlist that will contain newly defined words.
1.21      crook    3254: 
1.48      anton    3255: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21      crook    3256: 
1.48      anton    3257: @example
                   3258: wordlist constant mywords
                   3259: @end example
1.21      crook    3260: 
1.48      anton    3261: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
                   3262: defined words (the @emph{current} wordlist):
1.21      crook    3263: 
1.48      anton    3264: @example
                   3265: mywords set-current
                   3266: order
                   3267: @end example
1.26      crook    3268: 
1.48      anton    3269: Gforth does not display a name for the wordlist in @code{mywords}
                   3270: because this wordlist was created anonymously with @code{wordlist}.
1.21      crook    3271: 
1.48      anton    3272: You can get the current wordlist with @code{get-current ( -- wid)}.  If
                   3273: you want to put something into a specific wordlist without overall
                   3274: effect on the current wordlist, this typically looks like this:
1.21      crook    3275: 
1.48      anton    3276: @example
                   3277: get-current mywords set-current ( wid )
                   3278: create someword
                   3279: ( wid ) set-current
                   3280: @end example
1.21      crook    3281: 
1.48      anton    3282: You can write the search order with @code{set-order ( wid1 .. widn n --
                   3283: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
                   3284: searched wordlist is topmost.
1.21      crook    3285: 
1.48      anton    3286: @example
                   3287: get-order mywords swap 1+ set-order
                   3288: order
                   3289: @end example
1.21      crook    3290: 
1.48      anton    3291: Yes, the order of wordlists in the output of @code{order} is reversed
                   3292: from stack comments and the output of @code{.s} and thus unintuitive.
1.21      crook    3293: 
1.141     anton    3294: @quotation Assignment
1.48      anton    3295: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
                   3296: wordlist to the search order.  Define @code{previous ( -- )}, which
                   3297: removes the first searched wordlist from the search order.  Experiment
                   3298: with boundary conditions (you will see some crashes or situations that
                   3299: are hard or impossible to leave).
1.141     anton    3300: @end quotation
1.21      crook    3301: 
1.48      anton    3302: The search order is a powerful foundation for providing features similar
                   3303: to Modula-2 modules and C++ namespaces.  However, trying to modularize
                   3304: programs in this way has disadvantages for debugging and reuse/factoring
                   3305: that overcome the advantages in my experience (I don't do huge projects,
1.55      anton    3306: though).  These disadvantages are not so clear in other
1.82      anton    3307: languages/programming environments, because these languages are not so
1.48      anton    3308: strong in debugging and reuse.
1.21      crook    3309: 
1.66      anton    3310: @c !! example
                   3311: 
                   3312: Reference: @ref{Word Lists}.
1.21      crook    3313: 
1.29      crook    3314: @c ******************************************************************
1.48      anton    3315: @node Introduction, Words, Tutorial, Top
1.29      crook    3316: @comment node-name,     next,           previous, up
                   3317: @chapter An Introduction to ANS Forth
                   3318: @cindex Forth - an introduction
1.21      crook    3319: 
1.83      anton    3320: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
                   3321: that it is slower-paced in its examples, but uses them to dive deep into
                   3322: explaining Forth internals (not covered by the Tutorial).  Apart from
                   3323: that, this chapter covers far less material.  It is suitable for reading
                   3324: without using a computer.
                   3325: 
1.29      crook    3326: The primary purpose of this manual is to document Gforth. However, since
                   3327: Forth is not a widely-known language and there is a lack of up-to-date
                   3328: teaching material, it seems worthwhile to provide some introductory
1.49      anton    3329: material.  For other sources of Forth-related
                   3330: information, see @ref{Forth-related information}.
1.21      crook    3331: 
1.29      crook    3332: The examples in this section should work on any ANS Forth; the
                   3333: output shown was produced using Gforth. Each example attempts to
                   3334: reproduce the exact output that Gforth produces. If you try out the
                   3335: examples (and you should), what you should type is shown @kbd{like this}
                   3336: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    3337: that, where the example shows @key{RET} it means that you should
1.29      crook    3338: press the ``carriage return'' key. Unfortunately, some output formats for
                   3339: this manual cannot show the difference between @kbd{this} and
                   3340: @code{this} which will make trying out the examples harder (but not
                   3341: impossible).
1.21      crook    3342: 
1.29      crook    3343: Forth is an unusual language. It provides an interactive development
                   3344: environment which includes both an interpreter and compiler. Forth
                   3345: programming style encourages you to break a problem down into many
                   3346: @cindex factoring
                   3347: small fragments (@dfn{factoring}), and then to develop and test each
                   3348: fragment interactively. Forth advocates assert that breaking the
                   3349: edit-compile-test cycle used by conventional programming languages can
                   3350: lead to great productivity improvements.
1.21      crook    3351: 
1.29      crook    3352: @menu
1.67      anton    3353: * Introducing the Text Interpreter::  
                   3354: * Stacks and Postfix notation::  
                   3355: * Your first definition::       
                   3356: * How does that work?::         
                   3357: * Forth is written in Forth::   
                   3358: * Review - elements of a Forth system::  
                   3359: * Where to go next::            
                   3360: * Exercises::                   
1.29      crook    3361: @end menu
1.21      crook    3362: 
1.29      crook    3363: @comment ----------------------------------------------
                   3364: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   3365: @section Introducing the Text Interpreter
                   3366: @cindex text interpreter
                   3367: @cindex outer interpreter
1.21      crook    3368: 
1.30      anton    3369: @c IMO this is too detailed and the pace is too slow for
                   3370: @c an introduction.  If you know German, take a look at
                   3371: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   3372: @c to see how I do it - anton 
                   3373: 
1.44      crook    3374: @c nac-> Where I have accepted your comments 100% and modified the text
                   3375: @c accordingly, I have deleted your comments. Elsewhere I have added a
                   3376: @c response like this to attempt to rationalise what I have done. Of
                   3377: @c course, this is a very clumsy mechanism for something that would be
                   3378: @c done far more efficiently over a beer. Please delete any dialogue
                   3379: @c you consider closed.
                   3380: 
1.29      crook    3381: When you invoke the Forth image, you will see a startup banner printed
                   3382: and nothing else (if you have Gforth installed on your system, try
1.30      anton    3383: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    3384: its command line interpreter, which is called the @dfn{Text Interpreter}
                   3385: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.49      anton    3386: about the text interpreter as you read through this chapter, for more
                   3387: detail @pxref{The Text Interpreter}).
1.21      crook    3388: 
1.29      crook    3389: Although it's not obvious, Forth is actually waiting for your
1.30      anton    3390: input. Type a number and press the @key{RET} key:
1.21      crook    3391: 
1.26      crook    3392: @example
1.30      anton    3393: @kbd{45@key{RET}}  ok
1.26      crook    3394: @end example
1.21      crook    3395: 
1.29      crook    3396: Rather than give you a prompt to invite you to input something, the text
                   3397: interpreter prints a status message @i{after} it has processed a line
                   3398: of input. The status message in this case (``@code{ ok}'' followed by
                   3399: carriage-return) indicates that the text interpreter was able to process
                   3400: all of your input successfully. Now type something illegal:
                   3401: 
                   3402: @example
1.30      anton    3403: @kbd{qwer341@key{RET}}
1.134     anton    3404: *the terminal*:2: Undefined word
                   3405: >>>qwer341<<<
                   3406: Backtrace:
                   3407: $2A95B42A20 throw 
                   3408: $2A95B57FB8 no.extensions 
1.29      crook    3409: @end example
1.23      crook    3410: 
1.134     anton    3411: The exact text, other than the ``Undefined word'' may differ slightly
                   3412: on your system, but the effect is the same; when the text interpreter
1.29      crook    3413: detects an error, it discards any remaining text on a line, resets
1.134     anton    3414: certain internal state and prints an error message. For a detailed
                   3415: description of error messages see @ref{Error messages}.
1.23      crook    3416: 
1.29      crook    3417: The text interpreter waits for you to press carriage-return, and then
                   3418: processes your input line. Starting at the beginning of the line, it
                   3419: breaks the line into groups of characters separated by spaces. For each
                   3420: group of characters in turn, it makes two attempts to do something:
1.23      crook    3421: 
1.29      crook    3422: @itemize @bullet
                   3423: @item
1.44      crook    3424: @cindex name dictionary
1.29      crook    3425: It tries to treat it as a command. It does this by searching a @dfn{name
                   3426: dictionary}. If the group of characters matches an entry in the name
                   3427: dictionary, the name dictionary provides the text interpreter with
                   3428: information that allows the text interpreter perform some actions. In
                   3429: Forth jargon, we say that the group
                   3430: @cindex word
                   3431: @cindex definition
                   3432: @cindex execution token
                   3433: @cindex xt
                   3434: of characters names a @dfn{word}, that the dictionary search returns an
                   3435: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   3436: word, and that the text interpreter executes the xt. Often, the terms
                   3437: @dfn{word} and @dfn{definition} are used interchangeably.
                   3438: @item
                   3439: If the text interpreter fails to find a match in the name dictionary, it
                   3440: tries to treat the group of characters as a number in the current number
                   3441: base (when you start up Forth, the current number base is base 10). If
                   3442: the group of characters legitimately represents a number, the text
                   3443: interpreter pushes the number onto a stack (we'll learn more about that
                   3444: in the next section).
                   3445: @end itemize
1.23      crook    3446: 
1.29      crook    3447: If the text interpreter is unable to do either of these things with any
                   3448: group of characters, it discards the group of characters and the rest of
                   3449: the line, then prints an error message. If the text interpreter reaches
                   3450: the end of the line without error, it prints the status message ``@code{ ok}''
                   3451: followed by carriage-return.
1.21      crook    3452: 
1.29      crook    3453: This is the simplest command we can give to the text interpreter:
1.23      crook    3454: 
                   3455: @example
1.30      anton    3456: @key{RET}  ok
1.23      crook    3457: @end example
1.21      crook    3458: 
1.29      crook    3459: The text interpreter did everything we asked it to do (nothing) without
                   3460: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   3461: command:
1.21      crook    3462: 
1.23      crook    3463: @example
1.30      anton    3464: @kbd{12 dup fred dup@key{RET}}
1.134     anton    3465: *the terminal*:3: Undefined word
                   3466: 12 dup >>>fred<<< dup
                   3467: Backtrace:
                   3468: $2A95B42A20 throw 
                   3469: $2A95B57FB8 no.extensions 
1.23      crook    3470: @end example
1.21      crook    3471: 
1.29      crook    3472: When you press the carriage-return key, the text interpreter starts to
                   3473: work its way along the line:
1.21      crook    3474: 
1.29      crook    3475: @itemize @bullet
                   3476: @item
                   3477: When it gets to the space after the @code{2}, it takes the group of
                   3478: characters @code{12} and looks them up in the name
                   3479: dictionary@footnote{We can't tell if it found them or not, but assume
                   3480: for now that it did not}. There is no match for this group of characters
                   3481: in the name dictionary, so it tries to treat them as a number. It is
                   3482: able to do this successfully, so it puts the number, 12, ``on the stack''
                   3483: (whatever that means).
                   3484: @item
                   3485: The text interpreter resumes scanning the line and gets the next group
                   3486: of characters, @code{dup}. It looks it up in the name dictionary and
                   3487: (you'll have to take my word for this) finds it, and executes the word
                   3488: @code{dup} (whatever that means).
                   3489: @item
                   3490: Once again, the text interpreter resumes scanning the line and gets the
                   3491: group of characters @code{fred}. It looks them up in the name
                   3492: dictionary, but can't find them. It tries to treat them as a number, but
                   3493: they don't represent any legal number.
                   3494: @end itemize
1.21      crook    3495: 
1.29      crook    3496: At this point, the text interpreter gives up and prints an error
                   3497: message. The error message shows exactly how far the text interpreter
                   3498: got in processing the line. In particular, it shows that the text
                   3499: interpreter made no attempt to do anything with the final character
                   3500: group, @code{dup}, even though we have good reason to believe that the
                   3501: text interpreter would have no problem looking that word up and
                   3502: executing it a second time.
1.21      crook    3503: 
                   3504: 
1.29      crook    3505: @comment ----------------------------------------------
                   3506: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   3507: @section Stacks, postfix notation and parameter passing
                   3508: @cindex text interpreter
                   3509: @cindex outer interpreter
1.21      crook    3510: 
1.29      crook    3511: In procedural programming languages (like C and Pascal), the
                   3512: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   3513: functions or procedures are called with @dfn{explicit parameters}. For
                   3514: example, in C we might write:
1.21      crook    3515: 
1.23      crook    3516: @example
1.29      crook    3517: total = total + new_volume(length,height,depth);
1.23      crook    3518: @end example
1.21      crook    3519: 
1.23      crook    3520: @noindent
1.29      crook    3521: where new_volume is a function-call to another piece of code, and total,
                   3522: length, height and depth are all variables. length, height and depth are
                   3523: parameters to the function-call.
1.21      crook    3524: 
1.29      crook    3525: In Forth, the equivalent of the function or procedure is the
                   3526: @dfn{definition} and parameters are implicitly passed between
                   3527: definitions using a shared stack that is visible to the
                   3528: programmer. Although Forth does support variables, the existence of the
                   3529: stack means that they are used far less often than in most other
                   3530: programming languages. When the text interpreter encounters a number, it
                   3531: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    3532: actual number is implementation-dependent ...) and the particular stack
1.29      crook    3533: used for any operation is implied unambiguously by the operation being
                   3534: performed. The stack used for all integer operations is called the @dfn{data
                   3535: stack} and, since this is the stack used most commonly, references to
                   3536: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    3537: 
1.29      crook    3538: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    3539: 
1.23      crook    3540: @example
1.30      anton    3541: @kbd{1 2 3@key{RET}}  ok
1.23      crook    3542: @end example
1.21      crook    3543: 
1.29      crook    3544: Then this instructs the text interpreter to placed three numbers on the
                   3545: (data) stack. An analogy for the behaviour of the stack is to take a
                   3546: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   3547: the table. The 3 was the last card onto the pile (``last-in'') and if
                   3548: you take a card off the pile then, unless you're prepared to fiddle a
                   3549: bit, the card that you take off will be the 3 (``first-out''). The
                   3550: number that will be first-out of the stack is called the @dfn{top of
                   3551: stack}, which
                   3552: @cindex TOS definition
                   3553: is often abbreviated to @dfn{TOS}.
1.21      crook    3554: 
1.29      crook    3555: To understand how parameters are passed in Forth, consider the
                   3556: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   3557: be surprised to learn that this definition performs addition. More
                   3558: precisely, it adds two number together and produces a result. Where does
                   3559: it get the two numbers from? It takes the top two numbers off the
                   3560: stack. Where does it place the result? On the stack. You can act-out the
                   3561: behaviour of @code{+} with your playing cards like this:
1.21      crook    3562: 
                   3563: @itemize @bullet
                   3564: @item
1.29      crook    3565: Pick up two cards from the stack on the table
1.21      crook    3566: @item
1.29      crook    3567: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   3568: numbers''
1.21      crook    3569: @item
1.29      crook    3570: Decide that the answer is 5
1.21      crook    3571: @item
1.29      crook    3572: Shuffle the two cards back into the pack and find a 5
1.21      crook    3573: @item
1.29      crook    3574: Put a 5 on the remaining ace that's on the table.
1.21      crook    3575: @end itemize
                   3576: 
1.29      crook    3577: If you don't have a pack of cards handy but you do have Forth running,
                   3578: you can use the definition @code{.s} to show the current state of the stack,
                   3579: without affecting the stack. Type:
1.21      crook    3580: 
                   3581: @example
1.124     anton    3582: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30      anton    3583: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    3584: @end example
                   3585: 
1.124     anton    3586: The text interpreter looks up the word @code{clearstacks} and executes
                   3587: it; it tidies up the stacks and removes any entries that may have been
1.29      crook    3588: left on it by earlier examples. The text interpreter pushes each of the
                   3589: three numbers in turn onto the stack. Finally, the text interpreter
                   3590: looks up the word @code{.s} and executes it. The effect of executing
                   3591: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   3592: followed by a list of all the items on the stack; the item on the far
                   3593: right-hand side is the TOS.
1.21      crook    3594: 
1.29      crook    3595: You can now type:
1.21      crook    3596: 
1.29      crook    3597: @example
1.30      anton    3598: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    3599: @end example
1.21      crook    3600: 
1.29      crook    3601: @noindent
                   3602: which is correct; there are now 2 items on the stack and the result of
                   3603: the addition is 5.
1.23      crook    3604: 
1.29      crook    3605: If you're playing with cards, try doing a second addition: pick up the
                   3606: two cards, work out that their sum is 6, shuffle them into the pack,
                   3607: look for a 6 and place that on the table. You now have just one item on
                   3608: the stack. What happens if you try to do a third addition? Pick up the
                   3609: first card, pick up the second card -- ah! There is no second card. This
                   3610: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95      anton    3611: do the same thing with Forth it often reports an error (probably a Stack
1.29      crook    3612: Underflow or an Invalid Memory Address error).
1.23      crook    3613: 
1.29      crook    3614: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   3615: which simply accepts that there is a finite amount of storage space
                   3616: reserved for the stack. To stretch the playing card analogy, if you had
                   3617: enough packs of cards and you piled the cards up on the table, you would
                   3618: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   3619: allows you to set the maximum size of the stacks. In general, the only
                   3620: time that you will get a stack overflow is because a definition has a
                   3621: bug in it and is generating data on the stack uncontrollably.
1.23      crook    3622: 
1.29      crook    3623: There's one final use for the playing card analogy. If you model your
                   3624: stack using a pack of playing cards, the maximum number of items on
                   3625: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   3626: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   3627: possible numbers are positive integer numbers 1 through 13; you can't
                   3628: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   3629: think about some of the cards, you can accommodate different
                   3630: numbers. For example, you could think of the Jack as representing 0,
                   3631: the Queen as representing -1 and the King as representing -2. Your
1.45      crook    3632: @i{range} remains unchanged (you can still only represent a total of 13
1.29      crook    3633: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    3634: 
1.29      crook    3635: In that analogy, the limit was the amount of information that a single
                   3636: stack entry could hold, and Forth has a similar limit. In Forth, the
                   3637: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   3638: implementation dependent and affects the maximum value that a stack
                   3639: entry can hold. A Standard Forth provides a cell size of at least
                   3640: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    3641: 
1.29      crook    3642: Forth does not do any type checking for you, so you are free to
                   3643: manipulate and combine stack items in any way you wish. A convenient way
                   3644: of treating stack items is as 2's complement signed integers, and that
                   3645: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    3646: 
1.29      crook    3647: @example
1.30      anton    3648: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    3649: @end example
1.21      crook    3650: 
1.29      crook    3651: If you use numbers and definitions like @code{+} in order to turn Forth
                   3652: into a great big pocket calculator, you will realise that it's rather
                   3653: different from a normal calculator. Rather than typing 2 + 3 = you had
                   3654: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   3655: result). The terminology used to describe this difference is to say that
                   3656: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   3657: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   3658: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    3659: 
1.29      crook    3660: Whilst postfix notation might look confusing to begin with, it has
                   3661: several important advantages:
1.21      crook    3662: 
1.23      crook    3663: @itemize @bullet
                   3664: @item
1.29      crook    3665: it is unambiguous
1.23      crook    3666: @item
1.29      crook    3667: it is more concise
1.23      crook    3668: @item
1.29      crook    3669: it fits naturally with a stack-based system
1.23      crook    3670: @end itemize
1.21      crook    3671: 
1.29      crook    3672: To examine these claims in more detail, consider these sums:
1.21      crook    3673: 
1.29      crook    3674: @example
                   3675: 6 + 5 * 4 =
                   3676: 4 * 5 + 6 =
                   3677: @end example
1.21      crook    3678: 
1.29      crook    3679: If you're just learning maths or your maths is very rusty, you will
                   3680: probably come up with the answer 44 for the first and 26 for the
                   3681: second. If you are a bit of a whizz at maths you will remember the
                   3682: @i{convention} that multiplication takes precendence over addition, and
                   3683: you'd come up with the answer 26 both times. To explain the answer 26
                   3684: to someone who got the answer 44, you'd probably rewrite the first sum
                   3685: like this:
1.21      crook    3686: 
1.29      crook    3687: @example
                   3688: 6 + (5 * 4) =
                   3689: @end example
1.21      crook    3690: 
1.29      crook    3691: If what you really wanted was to perform the addition before the
                   3692: multiplication, you would have to use parentheses to force it.
1.21      crook    3693: 
1.29      crook    3694: If you did the first two sums on a pocket calculator you would probably
                   3695: get the right answers, unless you were very cautious and entered them using
                   3696: these keystroke sequences:
1.21      crook    3697: 
1.29      crook    3698: 6 + 5 = * 4 =
                   3699: 4 * 5 = + 6 =
1.21      crook    3700: 
1.29      crook    3701: Postfix notation is unambiguous because the order that the operators
                   3702: are applied is always explicit; that also means that parentheses are
                   3703: never required. The operators are @i{active} (the act of quoting the
                   3704: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    3705: 
1.29      crook    3706: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   3707: equivalent ways:
1.26      crook    3708: 
                   3709: @example
1.29      crook    3710: 6 5 4 * +      or:
                   3711: 5 4 * 6 +
1.26      crook    3712: @end example
1.23      crook    3713: 
1.29      crook    3714: An important thing that you should notice about this notation is that
                   3715: the @i{order} of the numbers does not change; if you want to subtract
                   3716: 2 from 10 you type @code{10 2 -}.
1.1       anton    3717: 
1.29      crook    3718: The reason that Forth uses postfix notation is very simple to explain: it
                   3719: makes the implementation extremely simple, and it follows naturally from
                   3720: using the stack as a mechanism for passing parameters. Another way of
                   3721: thinking about this is to realise that all Forth definitions are
                   3722: @i{active}; they execute as they are encountered by the text
                   3723: interpreter. The result of this is that the syntax of Forth is trivially
                   3724: simple.
1.1       anton    3725: 
                   3726: 
                   3727: 
1.29      crook    3728: @comment ----------------------------------------------
                   3729: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   3730: @section Your first Forth definition
                   3731: @cindex first definition
1.1       anton    3732: 
1.29      crook    3733: Until now, the examples we've seen have been trivial; we've just been
                   3734: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   3735: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   3736: again@footnote{That's not quite true. If you press the up-arrow key on
                   3737: your keyboard you should be able to scroll back to any earlier command,
                   3738: edit it and re-enter it.} In this section we'll see how to add new
                   3739: words to Forth's vocabulary.
1.1       anton    3740: 
1.29      crook    3741: The easiest way to create a new word is to use a @dfn{colon
                   3742: definition}. We'll define a few and try them out before worrying too
                   3743: much about how they work. Try typing in these examples; be careful to
                   3744: copy the spaces accurately:
1.1       anton    3745: 
1.29      crook    3746: @example
                   3747: : add-two 2 + . ;
                   3748: : greet ." Hello and welcome" ;
                   3749: : demo 5 add-two ;
                   3750: @end example
1.1       anton    3751: 
1.29      crook    3752: @noindent
                   3753: Now try them out:
1.1       anton    3754: 
1.29      crook    3755: @example
1.30      anton    3756: @kbd{greet@key{RET}} Hello and welcome  ok
                   3757: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   3758: @kbd{4 add-two@key{RET}} 6  ok
                   3759: @kbd{demo@key{RET}} 7  ok
                   3760: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    3761: @end example
1.1       anton    3762: 
1.29      crook    3763: The first new thing that we've introduced here is the pair of words
                   3764: @code{:} and @code{;}. These are used to start and terminate a new
                   3765: definition, respectively. The first word after the @code{:} is the name
                   3766: for the new definition.
1.1       anton    3767: 
1.29      crook    3768: As you can see from the examples, a definition is built up of words that
                   3769: have already been defined; Forth makes no distinction between
                   3770: definitions that existed when you started the system up, and those that
                   3771: you define yourself.
1.1       anton    3772: 
1.29      crook    3773: The examples also introduce the words @code{.} (dot), @code{."}
                   3774: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   3775: the stack and displays it. It's like @code{.s} except that it only
                   3776: displays the top item of the stack and it is destructive; after it has
                   3777: executed, the number is no longer on the stack. There is always one
                   3778: space printed after the number, and no spaces before it. Dot-quote
                   3779: defines a string (a sequence of characters) that will be printed when
                   3780: the word is executed. The string can contain any printable characters
                   3781: except @code{"}. A @code{"} has a special function; it is not a Forth
                   3782: word but it acts as a delimiter (the way that delimiters work is
                   3783: described in the next section). Finally, @code{dup} duplicates the value
                   3784: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    3785: 
1.29      crook    3786: We already know that the text interpreter searches through the
                   3787: dictionary to locate names. If you've followed the examples earlier, you
                   3788: will already have a definition called @code{add-two}. Lets try modifying
                   3789: it by typing in a new definition:
1.1       anton    3790: 
1.29      crook    3791: @example
1.30      anton    3792: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    3793: @end example
1.5       anton    3794: 
1.29      crook    3795: Forth recognised that we were defining a word that already exists, and
                   3796: printed a message to warn us of that fact. Let's try out the new
                   3797: definition:
1.5       anton    3798: 
1.29      crook    3799: @example
1.30      anton    3800: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    3801: @end example
1.1       anton    3802: 
1.29      crook    3803: @noindent
                   3804: All that we've actually done here, though, is to create a new
                   3805: definition, with a particular name. The fact that there was already a
                   3806: definition with the same name did not make any difference to the way
                   3807: that the new definition was created (except that Forth printed a warning
                   3808: message). The old definition of add-two still exists (try @code{demo}
                   3809: again to see that this is true). Any new definition will use the new
                   3810: definition of @code{add-two}, but old definitions continue to use the
                   3811: version that already existed at the time that they were @code{compiled}.
1.1       anton    3812: 
1.29      crook    3813: Before you go on to the next section, try defining and redefining some
                   3814: words of your own.
1.1       anton    3815: 
1.29      crook    3816: @comment ----------------------------------------------
                   3817: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   3818: @section How does that work?
                   3819: @cindex parsing words
1.1       anton    3820: 
1.30      anton    3821: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   3822: 
                   3823: @c Is it a good idea to talk about the interpretation semantics of a
                   3824: @c number? We don't have an xt to go along with it. - anton
                   3825: 
                   3826: @c Now that I have eliminated execution semantics, I wonder if it would not
                   3827: @c be better to keep them (or add run-time semantics), to make it easier to
                   3828: @c explain what compilation semantics usually does. - anton
                   3829: 
1.44      crook    3830: @c nac-> I removed the term ``default compilation sematics'' from the
                   3831: @c introductory chapter. Removing ``execution semantics'' was making
                   3832: @c everything simpler to explain, then I think the use of this term made
                   3833: @c everything more complex again. I replaced it with ``default
                   3834: @c semantics'' (which is used elsewhere in the manual) by which I mean
                   3835: @c ``a definition that has neither the immediate nor the compile-only
1.83      anton    3836: @c flag set''.
                   3837: 
                   3838: @c anton: I have eliminated default semantics (except in one place where it
                   3839: @c means "default interpretation and compilation semantics"), because it
                   3840: @c makes no sense in the presence of combined words.  I reverted to
                   3841: @c "execution semantics" where necessary.
                   3842: 
                   3843: @c nac-> I reworded big chunks of the ``how does that work''
1.44      crook    3844: @c section (and, unusually for me, I think I even made it shorter!).  See
                   3845: @c what you think -- I know I have not addressed your primary concern
                   3846: @c that it is too heavy-going for an introduction. From what I understood
                   3847: @c of your course notes it looks as though they might be a good framework. 
                   3848: @c Things that I've tried to capture here are some things that came as a
                   3849: @c great revelation here when I first understood them. Also, I like the
                   3850: @c fact that a very simple code example shows up almost all of the issues
                   3851: @c that you need to understand to see how Forth works. That's unique and
                   3852: @c worthwhile to emphasise.
                   3853: 
1.83      anton    3854: @c anton: I think it's a good idea to present the details, especially those
                   3855: @c that you found to be a revelation, and probably the tutorial tries to be
                   3856: @c too superficial and does not get some of the things across that make
                   3857: @c Forth special.  I do believe that most of the time these things should
                   3858: @c be discussed at the end of a section or in separate sections instead of
                   3859: @c in the middle of a section (e.g., the stuff you added in "User-defined
                   3860: @c defining words" leads in a completely different direction from the rest
                   3861: @c of the section).
                   3862: 
1.29      crook    3863: Now we're going to take another look at the definition of @code{add-two}
                   3864: from the previous section. From our knowledge of the way that the text
                   3865: interpreter works, we would have expected this result when we tried to
                   3866: define @code{add-two}:
1.21      crook    3867: 
1.29      crook    3868: @example
1.44      crook    3869: @kbd{: add-two 2 + . ;@key{RET}}
1.134     anton    3870: *the terminal*:4: Undefined word
                   3871: : >>>add-two<<< 2 + . ;
1.29      crook    3872: @end example
1.28      crook    3873: 
1.29      crook    3874: The reason that this didn't happen is bound up in the way that @code{:}
                   3875: works. The word @code{:} does two special things. The first special
                   3876: thing that it does prevents the text interpreter from ever seeing the
                   3877: characters @code{add-two}. The text interpreter uses a variable called
                   3878: @cindex modifying >IN
1.44      crook    3879: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29      crook    3880: input line. When it encounters the word @code{:} it behaves in exactly
                   3881: the same way as it does for any other word; it looks it up in the name
                   3882: dictionary, finds its xt and executes it. When @code{:} executes, it
                   3883: looks at the input buffer, finds the word @code{add-two} and advances the
                   3884: value of @code{>IN} to point past it. It then does some other stuff
                   3885: associated with creating the new definition (including creating an entry
                   3886: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   3887: completes, control returns to the text interpreter, which is oblivious
                   3888: to the fact that it has been tricked into ignoring part of the input
                   3889: line.
1.21      crook    3890: 
1.29      crook    3891: @cindex parsing words
                   3892: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   3893: prevent the text interpreter from acting on the whole of the input line
                   3894: -- are called @dfn{parsing words}.
1.21      crook    3895: 
1.29      crook    3896: @cindex @code{state} - effect on the text interpreter
                   3897: @cindex text interpreter - effect of state
                   3898: The second special thing that @code{:} does is change the value of a
                   3899: variable called @code{state}, which affects the way that the text
                   3900: interpreter behaves. When Gforth starts up, @code{state} has the value
                   3901: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   3902: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44      crook    3903: the text interpreter is said to be @dfn{compiling}.
                   3904: 
                   3905: In this example, the text interpreter is compiling when it processes the
                   3906: string ``@code{2 + . ;}''. It still breaks the string down into
                   3907: character sequences in the same way. However, instead of pushing the
                   3908: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
                   3909: into the definition of @code{add-two} that will make the number @code{2} get
                   3910: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
                   3911: the behaviours of @code{+} and @code{.} are also compiled into the
                   3912: definition.
                   3913: 
                   3914: One category of words don't get compiled. These so-called @dfn{immediate
                   3915: words} get executed (performed @i{now}) regardless of whether the text
                   3916: interpreter is interpreting or compiling. The word @code{;} is an
                   3917: immediate word. Rather than being compiled into the definition, it
                   3918: executes. Its effect is to terminate the current definition, which
                   3919: includes changing the value of @code{state} back to 0.
                   3920: 
                   3921: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
                   3922: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
                   3923: definition.
1.28      crook    3924: 
1.30      anton    3925: In Forth, every word or number can be described in terms of two
1.29      crook    3926: properties:
1.28      crook    3927: 
                   3928: @itemize @bullet
                   3929: @item
1.29      crook    3930: @cindex interpretation semantics
1.44      crook    3931: Its @dfn{interpretation semantics} describe how it will behave when the
                   3932: text interpreter encounters it in @dfn{interpret} state. The
                   3933: interpretation semantics of a word are represented by an @dfn{execution
                   3934: token}.
1.28      crook    3935: @item
1.29      crook    3936: @cindex compilation semantics
1.44      crook    3937: Its @dfn{compilation semantics} describe how it will behave when the
                   3938: text interpreter encounters it in @dfn{compile} state. The compilation
                   3939: semantics of a word are represented in an implementation-dependent way;
                   3940: Gforth uses a @dfn{compilation token}.
1.29      crook    3941: @end itemize
                   3942: 
                   3943: @noindent
                   3944: Numbers are always treated in a fixed way:
                   3945: 
                   3946: @itemize @bullet
1.28      crook    3947: @item
1.44      crook    3948: When the number is @dfn{interpreted}, its behaviour is to push the
                   3949: number onto the stack.
1.28      crook    3950: @item
1.30      anton    3951: When the number is @dfn{compiled}, a piece of code is appended to the
                   3952: current definition that pushes the number when it runs. (In other words,
                   3953: the compilation semantics of a number are to postpone its interpretation
                   3954: semantics until the run-time of the definition that it is being compiled
                   3955: into.)
1.29      crook    3956: @end itemize
                   3957: 
1.44      crook    3958: Words don't behave in such a regular way, but most have @i{default
                   3959: semantics} which means that they behave like this:
1.29      crook    3960: 
                   3961: @itemize @bullet
1.28      crook    3962: @item
1.30      anton    3963: The @dfn{interpretation semantics} of the word are to do something useful.
                   3964: @item
1.29      crook    3965: The @dfn{compilation semantics} of the word are to append its
1.30      anton    3966: @dfn{interpretation semantics} to the current definition (so that its
                   3967: run-time behaviour is to do something useful).
1.28      crook    3968: @end itemize
                   3969: 
1.30      anton    3970: @cindex immediate words
1.44      crook    3971: The actual behaviour of any particular word can be controlled by using
                   3972: the words @code{immediate} and @code{compile-only} when the word is
                   3973: defined. These words set flags in the name dictionary entry of the most
                   3974: recently defined word, and these flags are retrieved by the text
                   3975: interpreter when it finds the word in the name dictionary.
                   3976: 
                   3977: A word that is marked as @dfn{immediate} has compilation semantics that
                   3978: are identical to its interpretation semantics. In other words, it
                   3979: behaves like this:
1.29      crook    3980: 
                   3981: @itemize @bullet
                   3982: @item
1.30      anton    3983: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    3984: @item
1.30      anton    3985: The @dfn{compilation semantics} of the word are to do something useful
                   3986: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    3987: @end itemize
1.28      crook    3988: 
1.44      crook    3989: Marking a word as @dfn{compile-only} prohibits the text interpreter from
                   3990: performing the interpretation semantics of the word directly; an attempt
                   3991: to do so will generate an error. It is never necessary to use
                   3992: @code{compile-only} (and it is not even part of ANS Forth, though it is
                   3993: provided by many implementations) but it is good etiquette to apply it
                   3994: to a word that will not behave correctly (and might have unexpected
                   3995: side-effects) in interpret state. For example, it is only legal to use
                   3996: the conditional word @code{IF} within a definition. If you forget this
                   3997: and try to use it elsewhere, the fact that (in Gforth) it is marked as
                   3998: @code{compile-only} allows the text interpreter to generate a helpful
                   3999: error message rather than subjecting you to the consequences of your
                   4000: folly.
                   4001: 
1.29      crook    4002: This example shows the difference between an immediate and a
                   4003: non-immediate word:
1.28      crook    4004: 
1.29      crook    4005: @example
                   4006: : show-state state @@ . ;
                   4007: : show-state-now show-state ; immediate
                   4008: : word1 show-state ;
                   4009: : word2 show-state-now ;
1.28      crook    4010: @end example
1.23      crook    4011: 
1.29      crook    4012: The word @code{immediate} after the definition of @code{show-state-now}
                   4013: makes that word an immediate word. These definitions introduce a new
                   4014: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   4015: variable, and leaves it on the stack. Therefore, the behaviour of
                   4016: @code{show-state} is to print a number that represents the current value
                   4017: of @code{state}.
1.28      crook    4018: 
1.29      crook    4019: When you execute @code{word1}, it prints the number 0, indicating that
                   4020: the system is interpreting. When the text interpreter compiled the
                   4021: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    4022: compilation semantics are to append its interpretation semantics to the
1.29      crook    4023: current definition. When you execute @code{word1}, it performs the
1.30      anton    4024: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    4025: (and therefore @code{show-state}) are executed, the system is
                   4026: interpreting.
1.28      crook    4027: 
1.30      anton    4028: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    4029: you should have seen the number -1 printed, followed by ``@code{
                   4030: ok}''. When the text interpreter compiled the definition of
                   4031: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    4032: whose compilation semantics are therefore to perform its interpretation
1.29      crook    4033: semantics. It is executed straight away (even before the text
                   4034: interpreter has moved on to process another group of characters; the
                   4035: @code{;} in this example). The effect of executing it are to display the
                   4036: value of @code{state} @i{at the time that the definition of}
                   4037: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   4038: system is compiling at this time. If you execute @code{word2} it does
                   4039: nothing at all.
1.28      crook    4040: 
1.29      crook    4041: @cindex @code{."}, how it works
                   4042: Before leaving the subject of immediate words, consider the behaviour of
                   4043: @code{."} in the definition of @code{greet}, in the previous
                   4044: section. This word is both a parsing word and an immediate word. Notice
                   4045: that there is a space between @code{."} and the start of the text
                   4046: @code{Hello and welcome}, but that there is no space between the last
                   4047: letter of @code{welcome} and the @code{"} character. The reason for this
                   4048: is that @code{."} is a Forth word; it must have a space after it so that
                   4049: the text interpreter can identify it. The @code{"} is not a Forth word;
                   4050: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   4051: is displayed, there is neither a space before the @code{H} nor after the
                   4052: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   4053: that @code{greet} is defined. When it executes, its behaviour is to
                   4054: search forward in the input line looking for the delimiter. When it
                   4055: finds the delimiter, it updates @code{>IN} to point past the
                   4056: delimiter. It also compiles some magic code into the definition of
                   4057: @code{greet}; the xt of a run-time routine that prints a text string. It
                   4058: compiles the string @code{Hello and welcome} into memory so that it is
                   4059: available to be printed later. When the text interpreter gains control,
                   4060: the next word it finds in the input stream is @code{;} and so it
                   4061: terminates the definition of @code{greet}.
1.28      crook    4062: 
                   4063: 
                   4064: @comment ----------------------------------------------
1.29      crook    4065: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   4066: @section Forth is written in Forth
                   4067: @cindex structure of Forth programs
                   4068: 
                   4069: When you start up a Forth compiler, a large number of definitions
                   4070: already exist. In Forth, you develop a new application using bottom-up
                   4071: programming techniques to create new definitions that are defined in
                   4072: terms of existing definitions. As you create each definition you can
                   4073: test and debug it interactively.
                   4074: 
                   4075: If you have tried out the examples in this section, you will probably
                   4076: have typed them in by hand; when you leave Gforth, your definitions will
                   4077: be lost. You can avoid this by using a text editor to enter Forth source
                   4078: code into a file, and then loading code from the file using
1.49      anton    4079: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29      crook    4080: processed by the text interpreter, just as though you had typed it in by
                   4081: hand@footnote{Actually, there are some subtle differences -- see
                   4082: @ref{The Text Interpreter}.}.
                   4083: 
                   4084: Gforth also supports the traditional Forth alternative to using text
1.49      anton    4085: files for program entry (@pxref{Blocks}).
1.28      crook    4086: 
1.29      crook    4087: In common with many, if not most, Forth compilers, most of Gforth is
                   4088: actually written in Forth. All of the @file{.fs} files in the
                   4089: installation directory@footnote{For example,
1.30      anton    4090: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    4091: study to see examples of Forth programming.
1.28      crook    4092: 
1.29      crook    4093: Gforth maintains a history file that records every line that you type to
                   4094: the text interpreter. This file is preserved between sessions, and is
                   4095: used to provide a command-line recall facility. If you enter long
                   4096: definitions by hand, you can use a text editor to paste them out of the
                   4097: history file into a Forth source file for reuse at a later time
1.49      anton    4098: (for more information @pxref{Command-line editing}).
1.28      crook    4099: 
                   4100: 
                   4101: @comment ----------------------------------------------
1.29      crook    4102: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   4103: @section Review - elements of a Forth system
                   4104: @cindex elements of a Forth system
1.28      crook    4105: 
1.29      crook    4106: To summarise this chapter:
1.28      crook    4107: 
                   4108: @itemize @bullet
                   4109: @item
1.29      crook    4110: Forth programs use @dfn{factoring} to break a problem down into small
                   4111: fragments called @dfn{words} or @dfn{definitions}.
                   4112: @item
                   4113: Forth program development is an interactive process.
                   4114: @item
                   4115: The main command loop that accepts input, and controls both
                   4116: interpretation and compilation, is called the @dfn{text interpreter}
                   4117: (also known as the @dfn{outer interpreter}).
                   4118: @item
                   4119: Forth has a very simple syntax, consisting of words and numbers
                   4120: separated by spaces or carriage-return characters. Any additional syntax
                   4121: is imposed by @dfn{parsing words}.
                   4122: @item
                   4123: Forth uses a stack to pass parameters between words. As a result, it
                   4124: uses postfix notation.
                   4125: @item
                   4126: To use a word that has previously been defined, the text interpreter
                   4127: searches for the word in the @dfn{name dictionary}.
                   4128: @item
1.30      anton    4129: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    4130: @item
1.29      crook    4131: The text interpreter uses the value of @code{state} to select between
                   4132: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   4133: semantics} of a word that it encounters.
1.28      crook    4134: @item
1.30      anton    4135: The relationship between the @dfn{interpretation semantics} and
                   4136: @dfn{compilation semantics} for a word
1.29      crook    4137: depend upon the way in which the word was defined (for example, whether
                   4138: it is an @dfn{immediate} word).
1.28      crook    4139: @item
1.29      crook    4140: Forth definitions can be implemented in Forth (called @dfn{high-level
                   4141: definitions}) or in some other way (usually a lower-level language and
                   4142: as a result often called @dfn{low-level definitions}, @dfn{code
                   4143: definitions} or @dfn{primitives}).
1.28      crook    4144: @item
1.29      crook    4145: Many Forth systems are implemented mainly in Forth.
1.28      crook    4146: @end itemize
                   4147: 
                   4148: 
1.29      crook    4149: @comment ----------------------------------------------
1.48      anton    4150: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29      crook    4151: @section Where To Go Next
                   4152: @cindex where to go next
1.28      crook    4153: 
1.29      crook    4154: Amazing as it may seem, if you have read (and understood) this far, you
                   4155: know almost all the fundamentals about the inner workings of a Forth
                   4156: system. You certainly know enough to be able to read and understand the
                   4157: rest of this manual and the ANS Forth document, to learn more about the
                   4158: facilities that Forth in general and Gforth in particular provide. Even
                   4159: scarier, you know almost enough to implement your own Forth system.
1.30      anton    4160: However, that's not a good idea just yet... better to try writing some
1.29      crook    4161: programs in Gforth.
1.28      crook    4162: 
1.29      crook    4163: Forth has such a rich vocabulary that it can be hard to know where to
                   4164: start in learning it. This section suggests a few sets of words that are
                   4165: enough to write small but useful programs. Use the word index in this
                   4166: document to learn more about each word, then try it out and try to write
                   4167: small definitions using it. Start by experimenting with these words:
1.28      crook    4168: 
                   4169: @itemize @bullet
                   4170: @item
1.29      crook    4171: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   4172: @item
                   4173: Comparison: @code{MIN MAX =}
                   4174: @item
                   4175: Logic: @code{AND OR XOR NOT}
                   4176: @item
                   4177: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    4178: @item
1.29      crook    4179: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    4180: @item
1.29      crook    4181: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    4182: @item
1.29      crook    4183: Defining words: @code{: ; CREATE}
1.28      crook    4184: @item
1.29      crook    4185: Memory allocation words: @code{ALLOT ,}
1.28      crook    4186: @item
1.29      crook    4187: Tools: @code{SEE WORDS .S MARKER}
                   4188: @end itemize
                   4189: 
                   4190: When you have mastered those, go on to:
                   4191: 
                   4192: @itemize @bullet
1.28      crook    4193: @item
1.29      crook    4194: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    4195: @item
1.29      crook    4196: Memory access: @code{@@ !}
1.28      crook    4197: @end itemize
1.23      crook    4198: 
1.29      crook    4199: When you have mastered these, there's nothing for it but to read through
                   4200: the whole of this manual and find out what you've missed.
                   4201: 
                   4202: @comment ----------------------------------------------
1.48      anton    4203: @node Exercises,  , Where to go next, Introduction
1.29      crook    4204: @section Exercises
                   4205: @cindex exercises
                   4206: 
                   4207: TODO: provide a set of programming excercises linked into the stuff done
                   4208: already and into other sections of the manual. Provide solutions to all
                   4209: the exercises in a .fs file in the distribution.
                   4210: 
                   4211: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   4212: 
                   4213: @c excercises:
                   4214: @c 1. take inches and convert to feet and inches.
                   4215: @c 2. take temperature and convert from fahrenheight to celcius;
                   4216: @c    may need to care about symmetric vs floored??
                   4217: @c 3. take input line and do character substitution
                   4218: @c    to encipher or decipher
                   4219: @c 4. as above but work on a file for in and out
                   4220: @c 5. take input line and convert to pig-latin 
                   4221: @c
                   4222: @c thing of sets of things to exercise then come up with
                   4223: @c problems that need those things.
                   4224: 
                   4225: 
1.26      crook    4226: @c ******************************************************************
1.29      crook    4227: @node Words, Error messages, Introduction, Top
1.1       anton    4228: @chapter Forth Words
1.26      crook    4229: @cindex words
1.1       anton    4230: 
                   4231: @menu
                   4232: * Notation::                    
1.65      anton    4233: * Case insensitivity::          
                   4234: * Comments::                    
                   4235: * Boolean Flags::               
1.1       anton    4236: * Arithmetic::                  
                   4237: * Stack Manipulation::          
1.5       anton    4238: * Memory::                      
1.1       anton    4239: * Control Structures::          
                   4240: * Defining Words::              
1.65      anton    4241: * Interpretation and Compilation Semantics::  
1.47      crook    4242: * Tokens for Words::            
1.81      anton    4243: * Compiling words::             
1.65      anton    4244: * The Text Interpreter::        
1.111     anton    4245: * The Input Stream::            
1.65      anton    4246: * Word Lists::                  
                   4247: * Environmental Queries::       
1.12      anton    4248: * Files::                       
                   4249: * Blocks::                      
                   4250: * Other I/O::                   
1.121     anton    4251: * OS command line arguments::   
1.78      anton    4252: * Locals::                      
                   4253: * Structures::                  
                   4254: * Object-oriented Forth::       
1.12      anton    4255: * Programming Tools::           
1.150     anton    4256: * C Interface::                 
1.12      anton    4257: * Assembler and Code Words::    
                   4258: * Threading Words::             
1.65      anton    4259: * Passing Commands to the OS::  
                   4260: * Keeping track of Time::       
                   4261: * Miscellaneous Words::         
1.1       anton    4262: @end menu
                   4263: 
1.65      anton    4264: @node Notation, Case insensitivity, Words, Words
1.1       anton    4265: @section Notation
                   4266: @cindex notation of glossary entries
                   4267: @cindex format of glossary entries
                   4268: @cindex glossary notation format
                   4269: @cindex word glossary entry format
                   4270: 
                   4271: The Forth words are described in this section in the glossary notation
1.67      anton    4272: that has become a de-facto standard for Forth texts:
1.1       anton    4273: 
                   4274: @format
1.29      crook    4275: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    4276: @end format
1.29      crook    4277: @i{Description}
1.1       anton    4278: 
                   4279: @table @var
                   4280: @item word
1.28      crook    4281: The name of the word.
1.1       anton    4282: 
                   4283: @item Stack effect
                   4284: @cindex stack effect
1.29      crook    4285: The stack effect is written in the notation @code{@i{before} --
                   4286: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    4287: stack entries before and after the execution of the word. The rest of
                   4288: the stack is not touched by the word. The top of stack is rightmost,
                   4289: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   4290: uses a separate floating point stack, but a unified stack
1.29      crook    4291: notation. Also, return stack effects are not shown in @i{stack
                   4292: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    4293: the type and/or the function of the item. See below for a discussion of
                   4294: the types.
                   4295: 
                   4296: All words have two stack effects: A compile-time stack effect and a
                   4297: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    4298: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    4299: this standard behaviour, or the word does other unusual things at
                   4300: compile time, both stack effects are shown; otherwise only the run-time
                   4301: stack effect is shown.
                   4302: 
                   4303: @cindex pronounciation of words
                   4304: @item pronunciation
                   4305: How the word is pronounced.
                   4306: 
                   4307: @cindex wordset
1.67      anton    4308: @cindex environment wordset
1.1       anton    4309: @item wordset
1.21      crook    4310: The ANS Forth standard is divided into several word sets. A standard
                   4311: system need not support all of them. Therefore, in theory, the fewer
                   4312: word sets your program uses the more portable it will be. However, we
                   4313: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    4314: all word sets. Words that are not defined in ANS Forth have
1.21      crook    4315: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    4316: describes words that will work in future releases of Gforth;
                   4317: @code{gforth-internal} words are more volatile. Environmental query
                   4318: strings are also displayed like words; you can recognize them by the
1.21      crook    4319: @code{environment} in the word set field.
1.1       anton    4320: 
                   4321: @item Description
                   4322: A description of the behaviour of the word.
                   4323: @end table
                   4324: 
                   4325: @cindex types of stack items
                   4326: @cindex stack item types
                   4327: The type of a stack item is specified by the character(s) the name
                   4328: starts with:
                   4329: 
                   4330: @table @code
                   4331: @item f
                   4332: @cindex @code{f}, stack item type
                   4333: Boolean flags, i.e. @code{false} or @code{true}.
                   4334: @item c
                   4335: @cindex @code{c}, stack item type
                   4336: Char
                   4337: @item w
                   4338: @cindex @code{w}, stack item type
                   4339: Cell, can contain an integer or an address
                   4340: @item n
                   4341: @cindex @code{n}, stack item type
                   4342: signed integer
                   4343: @item u
                   4344: @cindex @code{u}, stack item type
                   4345: unsigned integer
                   4346: @item d
                   4347: @cindex @code{d}, stack item type
                   4348: double sized signed integer
                   4349: @item ud
                   4350: @cindex @code{ud}, stack item type
                   4351: double sized unsigned integer
                   4352: @item r
                   4353: @cindex @code{r}, stack item type
                   4354: Float (on the FP stack)
1.21      crook    4355: @item a-
1.1       anton    4356: @cindex @code{a_}, stack item type
                   4357: Cell-aligned address
1.21      crook    4358: @item c-
1.1       anton    4359: @cindex @code{c_}, stack item type
                   4360: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    4361: @item f-
1.1       anton    4362: @cindex @code{f_}, stack item type
                   4363: Float-aligned address
1.21      crook    4364: @item df-
1.1       anton    4365: @cindex @code{df_}, stack item type
                   4366: Address aligned for IEEE double precision float
1.21      crook    4367: @item sf-
1.1       anton    4368: @cindex @code{sf_}, stack item type
                   4369: Address aligned for IEEE single precision float
                   4370: @item xt
                   4371: @cindex @code{xt}, stack item type
                   4372: Execution token, same size as Cell
                   4373: @item wid
                   4374: @cindex @code{wid}, stack item type
1.21      crook    4375: Word list ID, same size as Cell
1.68      anton    4376: @item ior, wior
                   4377: @cindex ior type description
                   4378: @cindex wior type description
                   4379: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
1.1       anton    4380: @item f83name
                   4381: @cindex @code{f83name}, stack item type
                   4382: Pointer to a name structure
                   4383: @item "
                   4384: @cindex @code{"}, stack item type
1.12      anton    4385: string in the input stream (not on the stack). The terminating character
                   4386: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    4387: quotes.
                   4388: @end table
                   4389: 
1.65      anton    4390: @comment ----------------------------------------------
                   4391: @node Case insensitivity, Comments, Notation, Words
                   4392: @section Case insensitivity
                   4393: @cindex case sensitivity
                   4394: @cindex upper and lower case
                   4395: 
                   4396: Gforth is case-insensitive; you can enter definitions and invoke
                   4397: Standard words using upper, lower or mixed case (however,
                   4398: @pxref{core-idef, Implementation-defined options, Implementation-defined
                   4399: options}).
                   4400: 
                   4401: ANS Forth only @i{requires} implementations to recognise Standard words
                   4402: when they are typed entirely in upper case. Therefore, a Standard
                   4403: program must use upper case for all Standard words. You can use whatever
                   4404: case you like for words that you define, but in a Standard program you
                   4405: have to use the words in the same case that you defined them.
                   4406: 
                   4407: Gforth supports case sensitivity through @code{table}s (case-sensitive
                   4408: wordlists, @pxref{Word Lists}).
                   4409: 
                   4410: Two people have asked how to convert Gforth to be case-sensitive; while
                   4411: we think this is a bad idea, you can change all wordlists into tables
                   4412: like this:
                   4413: 
                   4414: @example
                   4415: ' table-find forth-wordlist wordlist-map @ !
                   4416: @end example
                   4417: 
                   4418: Note that you now have to type the predefined words in the same case
                   4419: that we defined them, which are varying.  You may want to convert them
                   4420: to your favourite case before doing this operation (I won't explain how,
                   4421: because if you are even contemplating doing this, you'd better have
                   4422: enough knowledge of Forth systems to know this already).
                   4423: 
                   4424: @node Comments, Boolean Flags, Case insensitivity, Words
1.21      crook    4425: @section Comments
1.26      crook    4426: @cindex comments
1.21      crook    4427: 
1.29      crook    4428: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   4429: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    4430: 
1.44      crook    4431: 
1.23      crook    4432: doc-(
1.21      crook    4433: doc-\
1.23      crook    4434: doc-\G
1.21      crook    4435: 
1.44      crook    4436: 
1.21      crook    4437: @node Boolean Flags, Arithmetic, Comments, Words
                   4438: @section Boolean Flags
1.26      crook    4439: @cindex Boolean flags
1.21      crook    4440: 
                   4441: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   4442: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    4443: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    4444: a cell that has @i{any} bit set as @code{true}.
1.67      anton    4445: @c on and off to Memory? 
                   4446: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44      crook    4447: 
1.21      crook    4448: doc-true
                   4449: doc-false
1.29      crook    4450: doc-on
                   4451: doc-off
1.21      crook    4452: 
1.44      crook    4453: 
1.21      crook    4454: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    4455: @section Arithmetic
                   4456: @cindex arithmetic words
                   4457: 
                   4458: @cindex division with potentially negative operands
                   4459: Forth arithmetic is not checked, i.e., you will not hear about integer
                   4460: overflow on addition or multiplication, you may hear about division by
                   4461: zero if you are lucky. The operator is written after the operands, but
                   4462: the operands are still in the original order. I.e., the infix @code{2-1}
                   4463: corresponds to @code{2 1 -}. Forth offers a variety of division
                   4464: operators. If you perform division with potentially negative operands,
                   4465: you do not want to use @code{/} or @code{/mod} with its undefined
                   4466: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   4467: former, @pxref{Mixed precision}).
1.26      crook    4468: @comment TODO discuss the different division forms and the std approach
1.1       anton    4469: 
                   4470: @menu
                   4471: * Single precision::            
1.67      anton    4472: * Double precision::            Double-cell integer arithmetic
1.1       anton    4473: * Bitwise operations::          
1.67      anton    4474: * Numeric comparison::          
1.29      crook    4475: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    4476: * Floating Point::              
                   4477: @end menu
                   4478: 
1.67      anton    4479: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1       anton    4480: @subsection Single precision
                   4481: @cindex single precision arithmetic words
                   4482: 
1.67      anton    4483: @c !! cell undefined
                   4484: 
                   4485: By default, numbers in Forth are single-precision integers that are one
1.26      crook    4486: cell in size. They can be signed or unsigned, depending upon how you
1.49      anton    4487: treat them. For the rules used by the text interpreter for recognising
                   4488: single-precision integers see @ref{Number Conversion}.
1.21      crook    4489: 
1.67      anton    4490: These words are all defined for signed operands, but some of them also
                   4491: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
                   4492: @code{*}.
1.44      crook    4493: 
1.1       anton    4494: doc-+
1.21      crook    4495: doc-1+
1.128     anton    4496: doc-under+
1.1       anton    4497: doc--
1.21      crook    4498: doc-1-
1.1       anton    4499: doc-*
                   4500: doc-/
                   4501: doc-mod
                   4502: doc-/mod
                   4503: doc-negate
                   4504: doc-abs
                   4505: doc-min
                   4506: doc-max
1.27      crook    4507: doc-floored
1.1       anton    4508: 
1.44      crook    4509: 
1.67      anton    4510: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21      crook    4511: @subsection Double precision
                   4512: @cindex double precision arithmetic words
                   4513: 
1.49      anton    4514: For the rules used by the text interpreter for
                   4515: recognising double-precision integers, see @ref{Number Conversion}.
1.21      crook    4516: 
                   4517: A double precision number is represented by a cell pair, with the most
1.67      anton    4518: significant cell at the TOS. It is trivial to convert an unsigned single
                   4519: to a double: simply push a @code{0} onto the TOS. Since numbers are
                   4520: represented by Gforth using 2's complement arithmetic, converting a
                   4521: signed single to a (signed) double requires sign-extension across the
                   4522: most significant cell. This can be achieved using @code{s>d}. The moral
                   4523: of the story is that you cannot convert a number without knowing whether
                   4524: it represents an unsigned or a signed number.
1.21      crook    4525: 
1.67      anton    4526: These words are all defined for signed operands, but some of them also
                   4527: work for unsigned numbers: @code{d+}, @code{d-}.
1.44      crook    4528: 
1.21      crook    4529: doc-s>d
1.67      anton    4530: doc-d>s
1.21      crook    4531: doc-d+
                   4532: doc-d-
                   4533: doc-dnegate
                   4534: doc-dabs
                   4535: doc-dmin
                   4536: doc-dmax
                   4537: 
1.44      crook    4538: 
1.67      anton    4539: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
                   4540: @subsection Bitwise operations
                   4541: @cindex bitwise operation words
                   4542: 
                   4543: 
                   4544: doc-and
                   4545: doc-or
                   4546: doc-xor
                   4547: doc-invert
                   4548: doc-lshift
                   4549: doc-rshift
                   4550: doc-2*
                   4551: doc-d2*
                   4552: doc-2/
                   4553: doc-d2/
                   4554: 
                   4555: 
                   4556: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21      crook    4557: @subsection Numeric comparison
                   4558: @cindex numeric comparison words
                   4559: 
1.67      anton    4560: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
                   4561: d0= d0<>}) work for for both signed and unsigned numbers.
1.44      crook    4562: 
1.28      crook    4563: doc-<
                   4564: doc-<=
                   4565: doc-<>
                   4566: doc-=
                   4567: doc->
                   4568: doc->=
                   4569: 
1.21      crook    4570: doc-0<
1.23      crook    4571: doc-0<=
1.21      crook    4572: doc-0<>
                   4573: doc-0=
1.23      crook    4574: doc-0>
                   4575: doc-0>=
1.28      crook    4576: 
                   4577: doc-u<
                   4578: doc-u<=
1.44      crook    4579: @c u<> and u= exist but are the same as <> and =
1.31      anton    4580: @c doc-u<>
                   4581: @c doc-u=
1.28      crook    4582: doc-u>
                   4583: doc-u>=
                   4584: 
                   4585: doc-within
                   4586: 
                   4587: doc-d<
                   4588: doc-d<=
                   4589: doc-d<>
                   4590: doc-d=
                   4591: doc-d>
                   4592: doc-d>=
1.23      crook    4593: 
1.21      crook    4594: doc-d0<
1.23      crook    4595: doc-d0<=
                   4596: doc-d0<>
1.21      crook    4597: doc-d0=
1.23      crook    4598: doc-d0>
                   4599: doc-d0>=
                   4600: 
1.21      crook    4601: doc-du<
1.28      crook    4602: doc-du<=
1.44      crook    4603: @c du<> and du= exist but are the same as d<> and d=
1.31      anton    4604: @c doc-du<>
                   4605: @c doc-du=
1.28      crook    4606: doc-du>
                   4607: doc-du>=
1.1       anton    4608: 
1.44      crook    4609: 
1.21      crook    4610: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    4611: @subsection Mixed precision
                   4612: @cindex mixed precision arithmetic words
                   4613: 
1.44      crook    4614: 
1.1       anton    4615: doc-m+
                   4616: doc-*/
                   4617: doc-*/mod
                   4618: doc-m*
                   4619: doc-um*
                   4620: doc-m*/
                   4621: doc-um/mod
                   4622: doc-fm/mod
                   4623: doc-sm/rem
                   4624: 
1.44      crook    4625: 
1.21      crook    4626: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    4627: @subsection Floating Point
                   4628: @cindex floating point arithmetic words
                   4629: 
1.49      anton    4630: For the rules used by the text interpreter for
                   4631: recognising floating-point numbers see @ref{Number Conversion}.
1.1       anton    4632: 
1.67      anton    4633: Gforth has a separate floating point stack, but the documentation uses
                   4634: the unified notation.@footnote{It's easy to generate the separate
                   4635: notation from that by just separating the floating-point numbers out:
                   4636: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
                   4637: r3 )}.}
1.1       anton    4638: 
                   4639: @cindex floating-point arithmetic, pitfalls
                   4640: Floating point numbers have a number of unpleasant surprises for the
                   4641: unwary (e.g., floating point addition is not associative) and even a few
                   4642: for the wary. You should not use them unless you know what you are doing
                   4643: or you don't care that the results you get are totally bogus. If you
                   4644: want to learn about the problems of floating point numbers (and how to
1.66      anton    4645: avoid them), you might start with @cite{David Goldberg,
                   4646: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
                   4647: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
                   4648: Surveys 23(1):5@minus{}48, March 1991}.
1.1       anton    4649: 
1.44      crook    4650: 
1.21      crook    4651: doc-d>f
                   4652: doc-f>d
1.1       anton    4653: doc-f+
                   4654: doc-f-
                   4655: doc-f*
                   4656: doc-f/
                   4657: doc-fnegate
                   4658: doc-fabs
                   4659: doc-fmax
                   4660: doc-fmin
                   4661: doc-floor
                   4662: doc-fround
                   4663: doc-f**
                   4664: doc-fsqrt
                   4665: doc-fexp
                   4666: doc-fexpm1
                   4667: doc-fln
                   4668: doc-flnp1
                   4669: doc-flog
                   4670: doc-falog
1.32      anton    4671: doc-f2*
                   4672: doc-f2/
                   4673: doc-1/f
                   4674: doc-precision
                   4675: doc-set-precision
                   4676: 
                   4677: @cindex angles in trigonometric operations
                   4678: @cindex trigonometric operations
                   4679: Angles in floating point operations are given in radians (a full circle
                   4680: has 2 pi radians).
                   4681: 
1.1       anton    4682: doc-fsin
                   4683: doc-fcos
                   4684: doc-fsincos
                   4685: doc-ftan
                   4686: doc-fasin
                   4687: doc-facos
                   4688: doc-fatan
                   4689: doc-fatan2
                   4690: doc-fsinh
                   4691: doc-fcosh
                   4692: doc-ftanh
                   4693: doc-fasinh
                   4694: doc-facosh
                   4695: doc-fatanh
1.21      crook    4696: doc-pi
1.28      crook    4697: 
1.32      anton    4698: @cindex equality of floats
                   4699: @cindex floating-point comparisons
1.31      anton    4700: One particular problem with floating-point arithmetic is that comparison
                   4701: for equality often fails when you would expect it to succeed.  For this
                   4702: reason approximate equality is often preferred (but you still have to
1.67      anton    4703: know what you are doing).  Also note that IEEE NaNs may compare
1.68      anton    4704: differently from what you might expect.  The comparison words are:
1.31      anton    4705: 
                   4706: doc-f~rel
                   4707: doc-f~abs
1.68      anton    4708: doc-f~
1.31      anton    4709: doc-f=
                   4710: doc-f<>
                   4711: 
                   4712: doc-f<
                   4713: doc-f<=
                   4714: doc-f>
                   4715: doc-f>=
                   4716: 
1.21      crook    4717: doc-f0<
1.28      crook    4718: doc-f0<=
                   4719: doc-f0<>
1.21      crook    4720: doc-f0=
1.28      crook    4721: doc-f0>
                   4722: doc-f0>=
                   4723: 
1.1       anton    4724: 
                   4725: @node Stack Manipulation, Memory, Arithmetic, Words
                   4726: @section Stack Manipulation
                   4727: @cindex stack manipulation words
                   4728: 
                   4729: @cindex floating-point stack in the standard
1.21      crook    4730: Gforth maintains a number of separate stacks:
                   4731: 
1.29      crook    4732: @cindex data stack
                   4733: @cindex parameter stack
1.21      crook    4734: @itemize @bullet
                   4735: @item
1.29      crook    4736: A data stack (also known as the @dfn{parameter stack}) -- for
                   4737: characters, cells, addresses, and double cells.
1.21      crook    4738: 
1.29      crook    4739: @cindex floating-point stack
1.21      crook    4740: @item
1.44      crook    4741: A floating point stack -- for holding floating point (FP) numbers.
1.21      crook    4742: 
1.29      crook    4743: @cindex return stack
1.21      crook    4744: @item
1.44      crook    4745: A return stack -- for holding the return addresses of colon
1.32      anton    4746: definitions and other (non-FP) data.
1.21      crook    4747: 
1.29      crook    4748: @cindex locals stack
1.21      crook    4749: @item
1.44      crook    4750: A locals stack -- for holding local variables.
1.21      crook    4751: @end itemize
                   4752: 
1.1       anton    4753: @menu
                   4754: * Data stack::                  
                   4755: * Floating point stack::        
                   4756: * Return stack::                
                   4757: * Locals stack::                
                   4758: * Stack pointer manipulation::  
                   4759: @end menu
                   4760: 
                   4761: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   4762: @subsection Data stack
                   4763: @cindex data stack manipulation words
                   4764: @cindex stack manipulations words, data stack
                   4765: 
1.44      crook    4766: 
1.1       anton    4767: doc-drop
                   4768: doc-nip
                   4769: doc-dup
                   4770: doc-over
                   4771: doc-tuck
                   4772: doc-swap
1.21      crook    4773: doc-pick
1.1       anton    4774: doc-rot
                   4775: doc--rot
                   4776: doc-?dup
                   4777: doc-roll
                   4778: doc-2drop
                   4779: doc-2nip
                   4780: doc-2dup
                   4781: doc-2over
                   4782: doc-2tuck
                   4783: doc-2swap
                   4784: doc-2rot
                   4785: 
1.44      crook    4786: 
1.1       anton    4787: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   4788: @subsection Floating point stack
                   4789: @cindex floating-point stack manipulation words
                   4790: @cindex stack manipulation words, floating-point stack
                   4791: 
1.32      anton    4792: Whilst every sane Forth has a separate floating-point stack, it is not
                   4793: strictly required; an ANS Forth system could theoretically keep
                   4794: floating-point numbers on the data stack. As an additional difficulty,
                   4795: you don't know how many cells a floating-point number takes. It is
                   4796: reportedly possible to write words in a way that they work also for a
                   4797: unified stack model, but we do not recommend trying it. Instead, just
                   4798: say that your program has an environmental dependency on a separate
                   4799: floating-point stack.
                   4800: 
                   4801: doc-floating-stack
                   4802: 
1.1       anton    4803: doc-fdrop
                   4804: doc-fnip
                   4805: doc-fdup
                   4806: doc-fover
                   4807: doc-ftuck
                   4808: doc-fswap
1.21      crook    4809: doc-fpick
1.1       anton    4810: doc-frot
                   4811: 
1.44      crook    4812: 
1.1       anton    4813: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   4814: @subsection Return stack
                   4815: @cindex return stack manipulation words
                   4816: @cindex stack manipulation words, return stack
                   4817: 
1.32      anton    4818: @cindex return stack and locals
                   4819: @cindex locals and return stack
                   4820: A Forth system is allowed to keep local variables on the
                   4821: return stack. This is reasonable, as local variables usually eliminate
                   4822: the need to use the return stack explicitly. So, if you want to produce
                   4823: a standard compliant program and you are using local variables in a
                   4824: word, forget about return stack manipulations in that word (refer to the
                   4825: standard document for the exact rules).
                   4826: 
1.1       anton    4827: doc->r
                   4828: doc-r>
                   4829: doc-r@
                   4830: doc-rdrop
                   4831: doc-2>r
                   4832: doc-2r>
                   4833: doc-2r@
                   4834: doc-2rdrop
                   4835: 
1.44      crook    4836: 
1.1       anton    4837: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   4838: @subsection Locals stack
                   4839: 
1.78      anton    4840: Gforth uses an extra locals stack.  It is described, along with the
                   4841: reasons for its existence, in @ref{Locals implementation}.
1.21      crook    4842: 
1.1       anton    4843: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   4844: @subsection Stack pointer manipulation
                   4845: @cindex stack pointer manipulation words
                   4846: 
1.44      crook    4847: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21      crook    4848: doc-sp0
1.1       anton    4849: doc-sp@
                   4850: doc-sp!
1.21      crook    4851: doc-fp0
1.1       anton    4852: doc-fp@
                   4853: doc-fp!
1.21      crook    4854: doc-rp0
1.1       anton    4855: doc-rp@
                   4856: doc-rp!
1.21      crook    4857: doc-lp0
1.1       anton    4858: doc-lp@
                   4859: doc-lp!
                   4860: 
1.44      crook    4861: 
1.1       anton    4862: @node Memory, Control Structures, Stack Manipulation, Words
                   4863: @section Memory
1.26      crook    4864: @cindex memory words
1.1       anton    4865: 
1.32      anton    4866: @menu
                   4867: * Memory model::                
                   4868: * Dictionary allocation::       
                   4869: * Heap Allocation::             
                   4870: * Memory Access::               
                   4871: * Address arithmetic::          
                   4872: * Memory Blocks::               
                   4873: @end menu
                   4874: 
1.67      anton    4875: In addition to the standard Forth memory allocation words, there is also
                   4876: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   4877: garbage collector}.
                   4878: 
1.32      anton    4879: @node Memory model, Dictionary allocation, Memory, Memory
                   4880: @subsection ANS Forth and Gforth memory models
                   4881: 
                   4882: @c The ANS Forth description is a mess (e.g., is the heap part of
                   4883: @c the dictionary?), so let's not stick to closely with it.
                   4884: 
1.67      anton    4885: ANS Forth considers a Forth system as consisting of several address
                   4886: spaces, of which only @dfn{data space} is managed and accessible with
                   4887: the memory words.  Memory not necessarily in data space includes the
                   4888: stacks, the code (called code space) and the headers (called name
                   4889: space). In Gforth everything is in data space, but the code for the
                   4890: primitives is usually read-only.
1.32      anton    4891: 
                   4892: Data space is divided into a number of areas: The (data space portion of
                   4893: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
                   4894: refer to the search data structure embodied in word lists and headers,
                   4895: because it is used for looking up names, just as you would in a
                   4896: conventional dictionary.}, the heap, and a number of system-allocated
                   4897: buffers.
                   4898: 
1.68      anton    4899: @cindex address arithmetic restrictions, ANS vs. Gforth
                   4900: @cindex contiguous regions, ANS vs. Gforth
1.32      anton    4901: In ANS Forth data space is also divided into contiguous regions.  You
                   4902: can only use address arithmetic within a contiguous region, not between
                   4903: them.  Usually each allocation gives you one contiguous region, but the
1.33      anton    4904: dictionary allocation words have additional rules (@pxref{Dictionary
1.32      anton    4905: allocation}).
                   4906: 
                   4907: Gforth provides one big address space, and address arithmetic can be
                   4908: performed between any addresses. However, in the dictionary headers or
                   4909: code are interleaved with data, so almost the only contiguous data space
                   4910: regions there are those described by ANS Forth as contiguous; but you
                   4911: can be sure that the dictionary is allocated towards increasing
                   4912: addresses even between contiguous regions.  The memory order of
                   4913: allocations in the heap is platform-dependent (and possibly different
                   4914: from one run to the next).
                   4915: 
1.27      crook    4916: 
1.32      anton    4917: @node Dictionary allocation, Heap Allocation, Memory model, Memory
                   4918: @subsection Dictionary allocation
1.27      crook    4919: @cindex reserving data space
                   4920: @cindex data space - reserving some
                   4921: 
1.32      anton    4922: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
                   4923: you want to deallocate X, you also deallocate everything
                   4924: allocated after X.
                   4925: 
1.68      anton    4926: @cindex contiguous regions in dictionary allocation
1.32      anton    4927: The allocations using the words below are contiguous and grow the region
                   4928: towards increasing addresses.  Other words that allocate dictionary
                   4929: memory of any kind (i.e., defining words including @code{:noname}) end
                   4930: the contiguous region and start a new one.
                   4931: 
                   4932: In ANS Forth only @code{create}d words are guaranteed to produce an
                   4933: address that is the start of the following contiguous region.  In
                   4934: particular, the cell allocated by @code{variable} is not guaranteed to
                   4935: be contiguous with following @code{allot}ed memory.
                   4936: 
                   4937: You can deallocate memory by using @code{allot} with a negative argument
                   4938: (with some restrictions, see @code{allot}). For larger deallocations use
                   4939: @code{marker}.
1.27      crook    4940: 
1.29      crook    4941: 
1.27      crook    4942: doc-here
                   4943: doc-unused
                   4944: doc-allot
                   4945: doc-c,
1.29      crook    4946: doc-f,
1.27      crook    4947: doc-,
                   4948: doc-2,
                   4949: 
1.32      anton    4950: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
                   4951: course you should allocate memory in an aligned way, too. I.e., before
                   4952: allocating allocating a cell, @code{here} must be cell-aligned, etc.
                   4953: The words below align @code{here} if it is not already.  Basically it is
                   4954: only already aligned for a type, if the last allocation was a multiple
                   4955: of the size of this type and if @code{here} was aligned for this type
                   4956: before.
                   4957: 
                   4958: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
                   4959: ANS Forth (@code{maxalign}ed in Gforth).
                   4960: 
                   4961: doc-align
                   4962: doc-falign
                   4963: doc-sfalign
                   4964: doc-dfalign
                   4965: doc-maxalign
                   4966: doc-cfalign
                   4967: 
                   4968: 
                   4969: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
                   4970: @subsection Heap allocation
                   4971: @cindex heap allocation
                   4972: @cindex dynamic allocation of memory
                   4973: @cindex memory-allocation word set
                   4974: 
1.68      anton    4975: @cindex contiguous regions and heap allocation
1.32      anton    4976: Heap allocation supports deallocation of allocated memory in any
                   4977: order. Dictionary allocation is not affected by it (i.e., it does not
                   4978: end a contiguous region). In Gforth, these words are implemented using
                   4979: the standard C library calls malloc(), free() and resize().
                   4980: 
1.68      anton    4981: The memory region produced by one invocation of @code{allocate} or
                   4982: @code{resize} is internally contiguous.  There is no contiguity between
                   4983: such a region and any other region (including others allocated from the
                   4984: heap).
                   4985: 
1.32      anton    4986: doc-allocate
                   4987: doc-free
                   4988: doc-resize
                   4989: 
1.27      crook    4990: 
1.32      anton    4991: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1       anton    4992: @subsection Memory Access
                   4993: @cindex memory access words
                   4994: 
                   4995: doc-@
                   4996: doc-!
                   4997: doc-+!
                   4998: doc-c@
                   4999: doc-c!
                   5000: doc-2@
                   5001: doc-2!
                   5002: doc-f@
                   5003: doc-f!
                   5004: doc-sf@
                   5005: doc-sf!
                   5006: doc-df@
                   5007: doc-df!
1.144     anton    5008: doc-sw@
                   5009: doc-uw@
                   5010: doc-w!
                   5011: doc-sl@
                   5012: doc-ul@
                   5013: doc-l!
1.68      anton    5014: 
1.32      anton    5015: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   5016: @subsection Address arithmetic
1.1       anton    5017: @cindex address arithmetic words
                   5018: 
1.67      anton    5019: Address arithmetic is the foundation on which you can build data
                   5020: structures like arrays, records (@pxref{Structures}) and objects
                   5021: (@pxref{Object-oriented Forth}).
1.32      anton    5022: 
1.68      anton    5023: @cindex address unit
                   5024: @cindex au (address unit)
1.1       anton    5025: ANS Forth does not specify the sizes of the data types. Instead, it
                   5026: offers a number of words for computing sizes and doing address
1.29      crook    5027: arithmetic. Address arithmetic is performed in terms of address units
                   5028: (aus); on most systems the address unit is one byte. Note that a
                   5029: character may have more than one au, so @code{chars} is no noop (on
1.68      anton    5030: platforms where it is a noop, it compiles to nothing).
1.1       anton    5031: 
1.67      anton    5032: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
                   5033: you have the address of a cell, perform @code{1 cells +}, and you will
                   5034: have the address of the next cell.
                   5035: 
1.68      anton    5036: @cindex contiguous regions and address arithmetic
1.67      anton    5037: In ANS Forth you can perform address arithmetic only within a contiguous
                   5038: region, i.e., if you have an address into one region, you can only add
                   5039: and subtract such that the result is still within the region; you can
                   5040: only subtract or compare addresses from within the same contiguous
                   5041: region.  Reasons: several contiguous regions can be arranged in memory
                   5042: in any way; on segmented systems addresses may have unusual
                   5043: representations, such that address arithmetic only works within a
                   5044: region.  Gforth provides a few more guarantees (linear address space,
                   5045: dictionary grows upwards), but in general I have found it easy to stay
                   5046: within contiguous regions (exception: computing and comparing to the
                   5047: address just beyond the end of an array).
                   5048: 
1.1       anton    5049: @cindex alignment of addresses for types
                   5050: ANS Forth also defines words for aligning addresses for specific
                   5051: types. Many computers require that accesses to specific data types
                   5052: must only occur at specific addresses; e.g., that cells may only be
                   5053: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   5054: accesses, it can usually perform aligned accesses faster. 
                   5055: 
                   5056: For the performance-conscious: alignment operations are usually only
                   5057: necessary during the definition of a data structure, not during the
                   5058: (more frequent) accesses to it.
                   5059: 
                   5060: ANS Forth defines no words for character-aligning addresses. This is not
                   5061: an oversight, but reflects the fact that addresses that are not
                   5062: char-aligned have no use in the standard and therefore will not be
                   5063: created.
                   5064: 
                   5065: @cindex @code{CREATE} and alignment
1.29      crook    5066: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    5067: are cell-aligned; in addition, Gforth guarantees that these addresses
                   5068: are aligned for all purposes.
                   5069: 
1.26      crook    5070: Note that the ANS Forth word @code{char} has nothing to do with address
                   5071: arithmetic.
1.1       anton    5072: 
1.44      crook    5073: 
1.1       anton    5074: doc-chars
                   5075: doc-char+
                   5076: doc-cells
                   5077: doc-cell+
                   5078: doc-cell
                   5079: doc-aligned
                   5080: doc-floats
                   5081: doc-float+
                   5082: doc-float
                   5083: doc-faligned
                   5084: doc-sfloats
                   5085: doc-sfloat+
                   5086: doc-sfaligned
                   5087: doc-dfloats
                   5088: doc-dfloat+
                   5089: doc-dfaligned
                   5090: doc-maxaligned
                   5091: doc-cfaligned
                   5092: doc-address-unit-bits
1.145     anton    5093: doc-/w
                   5094: doc-/l
1.44      crook    5095: 
1.32      anton    5096: @node Memory Blocks,  , Address arithmetic, Memory
1.1       anton    5097: @subsection Memory Blocks
                   5098: @cindex memory block words
1.27      crook    5099: @cindex character strings - moving and copying
                   5100: 
1.49      anton    5101: Memory blocks often represent character strings; For ways of storing
                   5102: character strings in memory see @ref{String Formats}.  For other
                   5103: string-processing words see @ref{Displaying characters and strings}.
1.1       anton    5104: 
1.67      anton    5105: A few of these words work on address unit blocks.  In that case, you
                   5106: usually have to insert @code{CHARS} before the word when working on
                   5107: character strings.  Most words work on character blocks, and expect a
                   5108: char-aligned address.
                   5109: 
                   5110: When copying characters between overlapping memory regions, use
                   5111: @code{chars move} or choose carefully between @code{cmove} and
                   5112: @code{cmove>}.
1.44      crook    5113: 
1.1       anton    5114: doc-move
                   5115: doc-erase
                   5116: doc-cmove
                   5117: doc-cmove>
                   5118: doc-fill
                   5119: doc-blank
1.21      crook    5120: doc-compare
1.111     anton    5121: doc-str=
                   5122: doc-str<
                   5123: doc-string-prefix?
1.21      crook    5124: doc-search
1.27      crook    5125: doc--trailing
                   5126: doc-/string
1.82      anton    5127: doc-bounds
1.141     anton    5128: doc-pad
1.111     anton    5129: 
1.27      crook    5130: @comment TODO examples
                   5131: 
1.1       anton    5132: 
1.26      crook    5133: @node Control Structures, Defining Words, Memory, Words
1.1       anton    5134: @section Control Structures
                   5135: @cindex control structures
                   5136: 
1.33      anton    5137: Control structures in Forth cannot be used interpretively, only in a
                   5138: colon definition@footnote{To be precise, they have no interpretation
                   5139: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
                   5140: not like this limitation, but have not seen a satisfying way around it
                   5141: yet, although many schemes have been proposed.
1.1       anton    5142: 
                   5143: @menu
1.33      anton    5144: * Selection::                   IF ... ELSE ... ENDIF
                   5145: * Simple Loops::                BEGIN ...
1.29      crook    5146: * Counted Loops::               DO
1.67      anton    5147: * Arbitrary control structures::  
                   5148: * Calls and returns::           
1.1       anton    5149: * Exception Handling::          
                   5150: @end menu
                   5151: 
                   5152: @node Selection, Simple Loops, Control Structures, Control Structures
                   5153: @subsection Selection
                   5154: @cindex selection control structures
                   5155: @cindex control structures for selection
                   5156: 
                   5157: @cindex @code{IF} control structure
                   5158: @example
1.29      crook    5159: @i{flag}
1.1       anton    5160: IF
1.29      crook    5161:   @i{code}
1.1       anton    5162: ENDIF
                   5163: @end example
1.21      crook    5164: @noindent
1.33      anton    5165: 
1.44      crook    5166: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
                   5167: with any bit set represents truth) @i{code} is executed.
1.33      anton    5168: 
1.1       anton    5169: @example
1.29      crook    5170: @i{flag}
1.1       anton    5171: IF
1.29      crook    5172:   @i{code1}
1.1       anton    5173: ELSE
1.29      crook    5174:   @i{code2}
1.1       anton    5175: ENDIF
                   5176: @end example
                   5177: 
1.44      crook    5178: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
                   5179: executed.
1.33      anton    5180: 
1.1       anton    5181: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   5182: standard, and @code{ENDIF} is not, although it is quite popular. We
                   5183: recommend using @code{ENDIF}, because it is less confusing for people
                   5184: who also know other languages (and is not prone to reinforcing negative
                   5185: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   5186: system that only supplies @code{THEN} is simple:
                   5187: @example
1.82      anton    5188: : ENDIF   POSTPONE then ; immediate
1.1       anton    5189: @end example
                   5190: 
                   5191: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   5192: (adv.)}  has the following meanings:
                   5193: @quotation
                   5194: ... 2b: following next after in order ... 3d: as a necessary consequence
                   5195: (if you were there, then you saw them).
                   5196: @end quotation
                   5197: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   5198: and many other programming languages has the meaning 3d.]
                   5199: 
1.21      crook    5200: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    5201: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    5202: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    5203: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   5204: @file{compat/control.fs}.
                   5205: 
                   5206: @cindex @code{CASE} control structure
                   5207: @example
1.29      crook    5208: @i{n}
1.1       anton    5209: CASE
1.29      crook    5210:   @i{n1} OF @i{code1} ENDOF
                   5211:   @i{n2} OF @i{code2} ENDOF
1.1       anton    5212:   @dots{}
1.68      anton    5213:   ( n ) @i{default-code} ( n )
1.131     anton    5214: ENDCASE ( )
1.1       anton    5215: @end example
                   5216: 
1.131     anton    5217: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If
                   5218: no @i{ni} matches, the optional @i{default-code} is executed. The
                   5219: optional default case can be added by simply writing the code after
                   5220: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
                   5221: but must not consume it.  The value @i{n} is consumed by this
                   5222: construction (either by a OF that matches, or by the ENDCASE, if no OF
                   5223: matches).
1.1       anton    5224: 
1.69      anton    5225: @progstyle
1.131     anton    5226: To keep the code understandable, you should ensure that you change the
                   5227: stack in the same way (wrt. number and types of stack items consumed
                   5228: and pushed) on all paths through a selection construct.
1.69      anton    5229: 
1.1       anton    5230: @node Simple Loops, Counted Loops, Selection, Control Structures
                   5231: @subsection Simple Loops
                   5232: @cindex simple loops
                   5233: @cindex loops without count 
                   5234: 
                   5235: @cindex @code{WHILE} loop
                   5236: @example
                   5237: BEGIN
1.29      crook    5238:   @i{code1}
                   5239:   @i{flag}
1.1       anton    5240: WHILE
1.29      crook    5241:   @i{code2}
1.1       anton    5242: REPEAT
                   5243: @end example
                   5244: 
1.29      crook    5245: @i{code1} is executed and @i{flag} is computed. If it is true,
                   5246: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    5247: false, execution continues after the @code{REPEAT}.
                   5248: 
                   5249: @cindex @code{UNTIL} loop
                   5250: @example
                   5251: BEGIN
1.29      crook    5252:   @i{code}
                   5253:   @i{flag}
1.1       anton    5254: UNTIL
                   5255: @end example
                   5256: 
1.29      crook    5257: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    5258: 
1.69      anton    5259: @progstyle
                   5260: To keep the code understandable, a complete iteration of the loop should
                   5261: not change the number and types of the items on the stacks.
                   5262: 
1.1       anton    5263: @cindex endless loop
                   5264: @cindex loops, endless
                   5265: @example
                   5266: BEGIN
1.29      crook    5267:   @i{code}
1.1       anton    5268: AGAIN
                   5269: @end example
                   5270: 
                   5271: This is an endless loop.
                   5272: 
                   5273: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   5274: @subsection Counted Loops
                   5275: @cindex counted loops
                   5276: @cindex loops, counted
                   5277: @cindex @code{DO} loops
                   5278: 
                   5279: The basic counted loop is:
                   5280: @example
1.29      crook    5281: @i{limit} @i{start}
1.1       anton    5282: ?DO
1.29      crook    5283:   @i{body}
1.1       anton    5284: LOOP
                   5285: @end example
                   5286: 
1.29      crook    5287: This performs one iteration for every integer, starting from @i{start}
                   5288: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    5289: accessed with @code{i}. For example, the loop:
1.1       anton    5290: @example
                   5291: 10 0 ?DO
                   5292:   i .
                   5293: LOOP
                   5294: @end example
1.21      crook    5295: @noindent
                   5296: prints @code{0 1 2 3 4 5 6 7 8 9}
                   5297: 
1.1       anton    5298: The index of the innermost loop can be accessed with @code{i}, the index
                   5299: of the next loop with @code{j}, and the index of the third loop with
                   5300: @code{k}.
                   5301: 
1.44      crook    5302: 
1.1       anton    5303: doc-i
                   5304: doc-j
                   5305: doc-k
                   5306: 
1.44      crook    5307: 
1.1       anton    5308: The loop control data are kept on the return stack, so there are some
1.21      crook    5309: restrictions on mixing return stack accesses and counted loop words. In
                   5310: particuler, if you put values on the return stack outside the loop, you
                   5311: cannot read them inside the loop@footnote{well, not in a way that is
                   5312: portable.}. If you put values on the return stack within a loop, you
                   5313: have to remove them before the end of the loop and before accessing the
                   5314: index of the loop.
1.1       anton    5315: 
                   5316: There are several variations on the counted loop:
                   5317: 
1.21      crook    5318: @itemize @bullet
                   5319: @item
                   5320: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   5321: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   5322: 
                   5323: @example
                   5324: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   5325: @end example
                   5326: prints @code{0 1 2 3}
                   5327: 
1.1       anton    5328: 
1.21      crook    5329: @item
                   5330: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   5331: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   5332: return stack so @code{EXIT} can get to its return address. For example:
                   5333: 
                   5334: @example
                   5335: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   5336: @end example
                   5337: prints @code{0 1 2 3}
                   5338: 
                   5339: 
                   5340: @item
1.29      crook    5341: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    5342: (and @code{LOOP} iterates until they become equal by wrap-around
                   5343: arithmetic). This behaviour is usually not what you want. Therefore,
                   5344: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    5345: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   5346: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    5347: unsigned loop parameters.
                   5348: 
1.21      crook    5349: @item
                   5350: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   5351: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   5352: if you know that the loop is entered in any case. Such knowledge tends
                   5353: to become invalid during maintenance of a program, and then the
                   5354: @code{DO} will make trouble.
                   5355: 
                   5356: @item
1.29      crook    5357: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   5358: index by @i{n} instead of by 1. The loop is terminated when the border
                   5359: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    5360: 
1.21      crook    5361: @example
                   5362: 4 0 +DO  i .  2 +LOOP
                   5363: @end example
                   5364: @noindent
                   5365: prints @code{0 2}
                   5366: 
                   5367: @example
                   5368: 4 1 +DO  i .  2 +LOOP
                   5369: @end example
                   5370: @noindent
                   5371: prints @code{1 3}
1.1       anton    5372: 
1.68      anton    5373: @item
1.1       anton    5374: @cindex negative increment for counted loops
                   5375: @cindex counted loops with negative increment
1.29      crook    5376: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    5377: 
1.21      crook    5378: @example
                   5379: -1 0 ?DO  i .  -1 +LOOP
                   5380: @end example
                   5381: @noindent
                   5382: prints @code{0 -1}
1.1       anton    5383: 
1.21      crook    5384: @example
                   5385: 0 0 ?DO  i .  -1 +LOOP
                   5386: @end example
                   5387: prints nothing.
1.1       anton    5388: 
1.29      crook    5389: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   5390: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   5391: index by @i{u} each iteration. The loop is terminated when the border
                   5392: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    5393: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   5394: 
1.21      crook    5395: @example
                   5396: -2 0 -DO  i .  1 -LOOP
                   5397: @end example
                   5398: @noindent
                   5399: prints @code{0 -1}
1.1       anton    5400: 
1.21      crook    5401: @example
                   5402: -1 0 -DO  i .  1 -LOOP
                   5403: @end example
                   5404: @noindent
                   5405: prints @code{0}
                   5406: 
                   5407: @example
                   5408: 0 0 -DO  i .  1 -LOOP
                   5409: @end example
                   5410: @noindent
                   5411: prints nothing.
1.1       anton    5412: 
1.21      crook    5413: @end itemize
1.1       anton    5414: 
                   5415: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    5416: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   5417: for these words that uses only standard words is provided in
                   5418: @file{compat/loops.fs}.
1.1       anton    5419: 
                   5420: 
                   5421: @cindex @code{FOR} loops
1.26      crook    5422: Another counted loop is:
1.1       anton    5423: @example
1.29      crook    5424: @i{n}
1.1       anton    5425: FOR
1.29      crook    5426:   @i{body}
1.1       anton    5427: NEXT
                   5428: @end example
                   5429: This is the preferred loop of native code compiler writers who are too
1.26      crook    5430: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    5431: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   5432: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    5433: Forth systems may behave differently, even if they support @code{FOR}
                   5434: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    5435: 
                   5436: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   5437: @subsection Arbitrary control structures
                   5438: @cindex control structures, user-defined
                   5439: 
                   5440: @cindex control-flow stack
                   5441: ANS Forth permits and supports using control structures in a non-nested
                   5442: way. Information about incomplete control structures is stored on the
                   5443: control-flow stack. This stack may be implemented on the Forth data
                   5444: stack, and this is what we have done in Gforth.
                   5445: 
                   5446: @cindex @code{orig}, control-flow stack item
                   5447: @cindex @code{dest}, control-flow stack item
                   5448: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   5449: entry represents a backward branch target. A few words are the basis for
                   5450: building any control structure possible (except control structures that
                   5451: need storage, like calls, coroutines, and backtracking).
                   5452: 
1.44      crook    5453: 
1.1       anton    5454: doc-if
                   5455: doc-ahead
                   5456: doc-then
                   5457: doc-begin
                   5458: doc-until
                   5459: doc-again
                   5460: doc-cs-pick
                   5461: doc-cs-roll
                   5462: 
1.44      crook    5463: 
1.21      crook    5464: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   5465: manipulate the control-flow stack in a portable way. Without them, you
                   5466: would need to know how many stack items are occupied by a control-flow
                   5467: entry (many systems use one cell. In Gforth they currently take three,
                   5468: but this may change in the future).
                   5469: 
1.1       anton    5470: Some standard control structure words are built from these words:
                   5471: 
1.44      crook    5472: 
1.1       anton    5473: doc-else
                   5474: doc-while
                   5475: doc-repeat
                   5476: 
1.44      crook    5477: 
                   5478: @noindent
1.1       anton    5479: Gforth adds some more control-structure words:
                   5480: 
1.44      crook    5481: 
1.1       anton    5482: doc-endif
                   5483: doc-?dup-if
                   5484: doc-?dup-0=-if
                   5485: 
1.44      crook    5486: 
                   5487: @noindent
1.1       anton    5488: Counted loop words constitute a separate group of words:
                   5489: 
1.44      crook    5490: 
1.1       anton    5491: doc-?do
                   5492: doc-+do
                   5493: doc-u+do
                   5494: doc--do
                   5495: doc-u-do
                   5496: doc-do
                   5497: doc-for
                   5498: doc-loop
                   5499: doc-+loop
                   5500: doc--loop
                   5501: doc-next
                   5502: doc-leave
                   5503: doc-?leave
                   5504: doc-unloop
                   5505: doc-done
                   5506: 
1.44      crook    5507: 
1.21      crook    5508: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   5509: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    5510: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   5511: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   5512: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   5513: resolved (by using one of the loop-ending words or @code{DONE}).
                   5514: 
1.44      crook    5515: @noindent
1.26      crook    5516: Another group of control structure words are:
1.1       anton    5517: 
1.44      crook    5518: 
1.1       anton    5519: doc-case
                   5520: doc-endcase
                   5521: doc-of
                   5522: doc-endof
                   5523: 
1.44      crook    5524: 
1.21      crook    5525: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   5526: @code{CS-ROLL}.
1.1       anton    5527: 
                   5528: @subsubsection Programming Style
1.47      crook    5529: @cindex control structures programming style
                   5530: @cindex programming style, arbitrary control structures
1.1       anton    5531: 
                   5532: In order to ensure readability we recommend that you do not create
                   5533: arbitrary control structures directly, but define new control structure
                   5534: words for the control structure you want and use these words in your
1.26      crook    5535: program. For example, instead of writing:
1.1       anton    5536: 
                   5537: @example
1.26      crook    5538: BEGIN
1.1       anton    5539:   ...
1.26      crook    5540: IF [ 1 CS-ROLL ]
1.1       anton    5541:   ...
1.26      crook    5542: AGAIN THEN
1.1       anton    5543: @end example
                   5544: 
1.21      crook    5545: @noindent
1.1       anton    5546: we recommend defining control structure words, e.g.,
                   5547: 
                   5548: @example
1.26      crook    5549: : WHILE ( DEST -- ORIG DEST )
                   5550:  POSTPONE IF
                   5551:  1 CS-ROLL ; immediate
                   5552: 
                   5553: : REPEAT ( orig dest -- )
                   5554:  POSTPONE AGAIN
                   5555:  POSTPONE THEN ; immediate
1.1       anton    5556: @end example
                   5557: 
1.21      crook    5558: @noindent
1.1       anton    5559: and then using these to create the control structure:
                   5560: 
                   5561: @example
1.26      crook    5562: BEGIN
1.1       anton    5563:   ...
1.26      crook    5564: WHILE
1.1       anton    5565:   ...
1.26      crook    5566: REPEAT
1.1       anton    5567: @end example
                   5568: 
                   5569: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   5570: @code{WHILE} are predefined, so in this example it would not be
                   5571: necessary to define them.
                   5572: 
                   5573: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   5574: @subsection Calls and returns
                   5575: @cindex calling a definition
                   5576: @cindex returning from a definition
                   5577: 
1.3       anton    5578: @cindex recursive definitions
                   5579: A definition can be called simply be writing the name of the definition
1.26      crook    5580: to be called. Normally a definition is invisible during its own
1.3       anton    5581: definition. If you want to write a directly recursive definition, you
1.26      crook    5582: can use @code{recursive} to make the current definition visible, or
                   5583: @code{recurse} to call the current definition directly.
1.3       anton    5584: 
1.44      crook    5585: 
1.3       anton    5586: doc-recursive
                   5587: doc-recurse
                   5588: 
1.44      crook    5589: 
1.21      crook    5590: @comment TODO add example of the two recursion methods
1.12      anton    5591: @quotation
                   5592: @progstyle
                   5593: I prefer using @code{recursive} to @code{recurse}, because calling the
                   5594: definition by name is more descriptive (if the name is well-chosen) than
                   5595: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   5596: implementation, it is much better to read (and think) ``now sort the
                   5597: partitions'' than to read ``now do a recursive call''.
                   5598: @end quotation
1.3       anton    5599: 
1.29      crook    5600: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    5601: 
                   5602: @example
1.28      crook    5603: Defer foo
1.3       anton    5604: 
                   5605: : bar ( ... -- ... )
                   5606:  ... foo ... ;
                   5607: 
                   5608: :noname ( ... -- ... )
                   5609:  ... bar ... ;
                   5610: IS foo
                   5611: @end example
                   5612: 
1.170     pazsan   5613: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33      anton    5614: 
1.26      crook    5615: The current definition returns control to the calling definition when
1.33      anton    5616: the end of the definition is reached or @code{EXIT} is encountered.
1.1       anton    5617: 
                   5618: doc-exit
                   5619: doc-;s
                   5620: 
1.44      crook    5621: 
1.1       anton    5622: @node Exception Handling,  , Calls and returns, Control Structures
                   5623: @subsection Exception Handling
1.26      crook    5624: @cindex exceptions
1.1       anton    5625: 
1.68      anton    5626: @c quit is a very bad idea for error handling, 
                   5627: @c because it does not translate into a THROW
                   5628: @c it also does not belong into this chapter
                   5629: 
                   5630: If a word detects an error condition that it cannot handle, it can
                   5631: @code{throw} an exception.  In the simplest case, this will terminate
                   5632: your program, and report an appropriate error.
1.21      crook    5633: 
1.68      anton    5634: doc-throw
1.1       anton    5635: 
1.69      anton    5636: @code{Throw} consumes a cell-sized error number on the stack. There are
                   5637: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
                   5638: Gforth (and most other systems) you can use the iors produced by various
                   5639: words as error numbers (e.g., a typical use of @code{allocate} is
                   5640: @code{allocate throw}).  Gforth also provides the word @code{exception}
                   5641: to define your own error numbers (with decent error reporting); an ANS
                   5642: Forth version of this word (but without the error messages) is available
                   5643: in @code{compat/except.fs}.  And finally, you can use your own error
1.68      anton    5644: numbers (anything outside the range -4095..0), but won't get nice error
                   5645: messages, only numbers.  For example, try:
                   5646: 
                   5647: @example
1.69      anton    5648: -10 throw                    \ ANS defined
                   5649: -267 throw                   \ system defined
                   5650: s" my error" exception throw \ user defined
                   5651: 7 throw                      \ arbitrary number
1.68      anton    5652: @end example
                   5653: 
                   5654: doc---exception-exception
1.1       anton    5655: 
1.69      anton    5656: A common idiom to @code{THROW} a specific error if a flag is true is
                   5657: this:
                   5658: 
                   5659: @example
                   5660: @code{( flag ) 0<> @i{errno} and throw}
                   5661: @end example
                   5662: 
                   5663: Your program can provide exception handlers to catch exceptions.  An
                   5664: exception handler can be used to correct the problem, or to clean up
                   5665: some data structures and just throw the exception to the next exception
                   5666: handler.  Note that @code{throw} jumps to the dynamically innermost
                   5667: exception handler.  The system's exception handler is outermost, and just
                   5668: prints an error and restarts command-line interpretation (or, in batch
                   5669: mode (i.e., while processing the shell command line), leaves Gforth).
1.1       anton    5670: 
1.68      anton    5671: The ANS Forth way to catch exceptions is @code{catch}:
1.1       anton    5672: 
1.68      anton    5673: doc-catch
1.160     anton    5674: doc-nothrow
1.68      anton    5675: 
                   5676: The most common use of exception handlers is to clean up the state when
                   5677: an error happens.  E.g.,
1.1       anton    5678: 
1.26      crook    5679: @example
1.68      anton    5680: base @ >r hex \ actually the hex should be inside foo, or we h
                   5681: ['] foo catch ( nerror|0 )
                   5682: r> base !
1.69      anton    5683: ( nerror|0 ) throw \ pass it on
1.26      crook    5684: @end example
1.1       anton    5685: 
1.69      anton    5686: A use of @code{catch} for handling the error @code{myerror} might look
                   5687: like this:
1.44      crook    5688: 
1.68      anton    5689: @example
1.69      anton    5690: ['] foo catch
                   5691: CASE
1.160     anton    5692:   myerror OF ... ( do something about it ) nothrow ENDOF
1.69      anton    5693:   dup throw \ default: pass other errors on, do nothing on non-errors
                   5694: ENDCASE
1.68      anton    5695: @end example
1.44      crook    5696: 
1.68      anton    5697: Having to wrap the code into a separate word is often cumbersome,
                   5698: therefore Gforth provides an alternative syntax:
1.1       anton    5699: 
                   5700: @example
1.69      anton    5701: TRY
1.68      anton    5702:   @i{code1}
1.172     anton    5703:   IFERROR
                   5704:     @i{code2}
                   5705:   THEN
                   5706:   @i{code3}
1.69      anton    5707: ENDTRY
1.1       anton    5708: @end example
                   5709: 
1.172     anton    5710: This performs @i{code1}.  If @i{code1} completes normally, execution
                   5711: continues with @i{code3}.  If @i{code1} or there is an exception
                   5712: before @code{endtry}, the stacks are reset to the state during
                   5713: @code{try}, the throw value is pushed on the data stack, and execution
                   5714: constinues at @i{code2}, and finally falls through the @i{code3}.
1.26      crook    5715: 
1.68      anton    5716: doc-try
                   5717: doc-endtry
1.172     anton    5718: doc-iferror
                   5719: 
                   5720: If you don't need @i{code2}, you can write @code{restore} instead of
                   5721: @code{iferror then}:
                   5722: 
                   5723: @example
                   5724: TRY
                   5725:   @i{code1}
                   5726: RESTORE
                   5727:   @i{code3}
                   5728: ENDTRY
                   5729: @end example
1.26      crook    5730: 
1.172     anton    5731: @cindex unwind-protect
1.69      anton    5732: The cleanup example from above in this syntax:
1.26      crook    5733: 
1.68      anton    5734: @example
1.172     anton    5735: base @ @{ oldbase @}
                   5736: TRY
1.68      anton    5737:   hex foo \ now the hex is placed correctly
1.69      anton    5738:   0       \ value for throw
1.172     anton    5739: RESTORE
                   5740:   oldbase base !
                   5741: ENDTRY
                   5742: throw
1.1       anton    5743: @end example
                   5744: 
1.172     anton    5745: An additional advantage of this variant is that an exception between
                   5746: @code{restore} and @code{endtry} (e.g., from the user pressing
                   5747: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
                   5748: so the base will be restored under all circumstances.
                   5749: 
                   5750: However, you have to ensure that this code does not cause an exception
                   5751: itself, otherwise the @code{iferror}/@code{restore} code will loop.
                   5752: Moreover, you should also make sure that the stack contents needed by
                   5753: the @code{iferror}/@code{restore} code exist everywhere between
                   5754: @code{try} and @code{endtry}; in our example this is achived by
                   5755: putting the data in a local before the @code{try} (you cannot use the
                   5756: return stack because the exception frame (@i{sys1}) is in the way
                   5757: there).
                   5758: 
                   5759: This kind of usage corresponds to Lisp's @code{unwind-protect}.
                   5760: 
                   5761: @cindex @code{recover} (old Gforth versions)
                   5762: If you do not want this exception-restarting behaviour, you achieve
                   5763: this as follows:
                   5764: 
                   5765: @example
                   5766: TRY
                   5767:   @i{code1}
                   5768: ENDTRY-IFERROR
                   5769:   @i{code2}
                   5770: THEN
                   5771: @end example
                   5772: 
                   5773: If there is an exception in @i{code1}, then @i{code2} is executed,
                   5774: otherwise execution continues behind the @code{then} (or in a possible
                   5775: @code{else} branch).  This corresponds to the construct
                   5776: 
                   5777: @example
                   5778: TRY
                   5779:   @i{code1}
                   5780: RECOVER
                   5781:   @i{code2}
                   5782: ENDTRY
                   5783: @end example
                   5784: 
                   5785: in Gforth before version 0.7.  So you can directly replace
                   5786: @code{recover}-using code; however, we recommend that you check if it
                   5787: would not be better to use one of the other @code{try} variants while
                   5788: you are at it.
                   5789: 
1.173   ! anton    5790: To ease the transition, Gforth provides two compatibility files:
        !          5791: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
        !          5792: ... then} syntax (but not @code{iferror} or @code{restore}) for old
        !          5793: systems; @file{recover-endtry.fs} provides the @code{try ... recover
        !          5794: ... endtry} syntax on new systems, so you can use that file as a
        !          5795: stopgap to run old programs.  Both files work on any system (they just
        !          5796: do nothing if the system already has the syntax it implements), so you
        !          5797: can unconditionally @code{require} one of these files, even if you use
        !          5798: a mix old and new systems.
        !          5799: 
1.172     anton    5800: doc-restore
                   5801: doc-endtry-iferror
                   5802: 
                   5803: Here's the error handling example:
1.1       anton    5804: 
1.68      anton    5805: @example
1.69      anton    5806: TRY
1.68      anton    5807:   foo
1.172     anton    5808: ENDTRY-IFERROR
1.69      anton    5809:   CASE
1.160     anton    5810:     myerror OF ... ( do something about it ) nothrow ENDOF
1.69      anton    5811:     throw \ pass other errors on
                   5812:   ENDCASE
1.172     anton    5813: THEN
1.68      anton    5814: @end example
1.1       anton    5815: 
1.69      anton    5816: @progstyle
                   5817: As usual, you should ensure that the stack depth is statically known at
                   5818: the end: either after the @code{throw} for passing on errors, or after
                   5819: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
                   5820: selection construct for handling the error).
                   5821: 
1.68      anton    5822: There are two alternatives to @code{throw}: @code{Abort"} is conditional
                   5823: and you can provide an error message.  @code{Abort} just produces an
                   5824: ``Aborted'' error.
1.1       anton    5825: 
1.68      anton    5826: The problem with these words is that exception handlers cannot
                   5827: differentiate between different @code{abort"}s; they just look like
                   5828: @code{-2 throw} to them (the error message cannot be accessed by
                   5829: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
                   5830: exception handlers.
1.44      crook    5831: 
1.68      anton    5832: doc-abort"
1.26      crook    5833: doc-abort
1.29      crook    5834: 
                   5835: 
1.44      crook    5836: 
1.29      crook    5837: @c -------------------------------------------------------------
1.47      crook    5838: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29      crook    5839: @section Defining Words
                   5840: @cindex defining words
                   5841: 
1.47      crook    5842: Defining words are used to extend Forth by creating new entries in the dictionary.
                   5843: 
1.29      crook    5844: @menu
1.67      anton    5845: * CREATE::                      
1.44      crook    5846: * Variables::                   Variables and user variables
1.67      anton    5847: * Constants::                   
1.44      crook    5848: * Values::                      Initialised variables
1.67      anton    5849: * Colon Definitions::           
1.44      crook    5850: * Anonymous Definitions::       Definitions without names
1.69      anton    5851: * Supplying names::             Passing definition names as strings
1.67      anton    5852: * User-defined Defining Words::  
1.170     pazsan   5853: * Deferred Words::              Allow forward references
1.67      anton    5854: * Aliases::                     
1.29      crook    5855: @end menu
                   5856: 
1.44      crook    5857: @node CREATE, Variables, Defining Words, Defining Words
                   5858: @subsection @code{CREATE}
1.29      crook    5859: @cindex simple defining words
                   5860: @cindex defining words, simple
                   5861: 
                   5862: Defining words are used to create new entries in the dictionary. The
                   5863: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   5864: this:
                   5865: 
                   5866: @example
                   5867: CREATE new-word1
                   5868: @end example
                   5869: 
1.69      anton    5870: @code{CREATE} is a parsing word, i.e., it takes an argument from the
                   5871: input stream (@code{new-word1} in our example).  It generates a
                   5872: dictionary entry for @code{new-word1}. When @code{new-word1} is
                   5873: executed, all that it does is leave an address on the stack. The address
                   5874: represents the value of the data space pointer (@code{HERE}) at the time
                   5875: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
                   5876: associating a name with the address of a region of memory.
1.29      crook    5877: 
1.34      anton    5878: doc-create
                   5879: 
1.69      anton    5880: Note that in ANS Forth guarantees only for @code{create} that its body
                   5881: is in dictionary data space (i.e., where @code{here}, @code{allot}
                   5882: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
                   5883: @code{create}d words can be modified with @code{does>}
                   5884: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
                   5885: can only be applied to @code{create}d words.
                   5886: 
1.29      crook    5887: By extending this example to reserve some memory in data space, we end
1.69      anton    5888: up with something like a @i{variable}. Here are two different ways to do
                   5889: it:
1.29      crook    5890: 
                   5891: @example
                   5892: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   5893: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   5894: @end example
                   5895: 
                   5896: The variable can be examined and modified using @code{@@} (``fetch'') and
                   5897: @code{!} (``store'') like this:
                   5898: 
                   5899: @example
                   5900: new-word2 @@ .      \ get address, fetch from it and display
                   5901: 1234 new-word2 !   \ new value, get address, store to it
                   5902: @end example
                   5903: 
1.44      crook    5904: @cindex arrays
                   5905: A similar mechanism can be used to create arrays. For example, an
                   5906: 80-character text input buffer:
1.29      crook    5907: 
                   5908: @example
1.44      crook    5909: CREATE text-buf 80 chars allot
                   5910: 
1.168     anton    5911: text-buf 0 chars + c@@ \ the 1st character (offset 0)
                   5912: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44      crook    5913: @end example
1.29      crook    5914: 
1.44      crook    5915: You can build arbitrarily complex data structures by allocating
1.49      anton    5916: appropriate areas of memory. For further discussions of this, and to
1.66      anton    5917: learn about some Gforth tools that make it easier,
1.49      anton    5918: @xref{Structures}.
1.44      crook    5919: 
                   5920: 
                   5921: @node Variables, Constants, CREATE, Defining Words
                   5922: @subsection Variables
                   5923: @cindex variables
                   5924: 
                   5925: The previous section showed how a sequence of commands could be used to
                   5926: generate a variable.  As a final refinement, the whole code sequence can
                   5927: be wrapped up in a defining word (pre-empting the subject of the next
                   5928: section), making it easier to create new variables:
                   5929: 
                   5930: @example
                   5931: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
                   5932: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
                   5933: 
                   5934: myvariableX foo \ variable foo starts off with an unknown value
                   5935: myvariable0 joe \ whilst joe is initialised to 0
1.29      crook    5936: 
                   5937: 45 3 * foo !   \ set foo to 135
                   5938: 1234 joe !     \ set joe to 1234
                   5939: 3 joe +!       \ increment joe by 3.. to 1237
                   5940: @end example
                   5941: 
                   5942: Not surprisingly, there is no need to define @code{myvariable}, since
1.44      crook    5943: Forth already has a definition @code{Variable}. ANS Forth does not
1.69      anton    5944: guarantee that a @code{Variable} is initialised when it is created
                   5945: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
                   5946: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
                   5947: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47      crook    5948: @code{fvariable} for double and floating-point variables, respectively
1.69      anton    5949: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47      crook    5950: store a boolean, you can use @code{on} and @code{off} to toggle its
                   5951: state.
1.29      crook    5952: 
1.34      anton    5953: doc-variable
                   5954: doc-2variable
                   5955: doc-fvariable
                   5956: 
1.29      crook    5957: @cindex user variables
                   5958: @cindex user space
                   5959: The defining word @code{User} behaves in the same way as @code{Variable}.
                   5960: The difference is that it reserves space in @i{user (data) space} rather
                   5961: than normal data space. In a Forth system that has a multi-tasker, each
                   5962: task has its own set of user variables.
                   5963: 
1.34      anton    5964: doc-user
1.67      anton    5965: @c doc-udp
                   5966: @c doc-uallot
1.34      anton    5967: 
1.29      crook    5968: @comment TODO is that stuff about user variables strictly correct? Is it
                   5969: @comment just terminal tasks that have user variables?
                   5970: @comment should document tasker.fs (with some examples) elsewhere
                   5971: @comment in this manual, then expand on user space and user variables.
                   5972: 
1.44      crook    5973: @node Constants, Values, Variables, Defining Words
                   5974: @subsection Constants
                   5975: @cindex constants
                   5976: 
                   5977: @code{Constant} allows you to declare a fixed value and refer to it by
                   5978: name. For example:
1.29      crook    5979: 
                   5980: @example
                   5981: 12 Constant INCHES-PER-FOOT
                   5982: 3E+08 fconstant SPEED-O-LIGHT
                   5983: @end example
                   5984: 
                   5985: A @code{Variable} can be both read and written, so its run-time
                   5986: behaviour is to supply an address through which its current value can be
                   5987: manipulated. In contrast, the value of a @code{Constant} cannot be
                   5988: changed once it has been declared@footnote{Well, often it can be -- but
                   5989: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   5990: on).} so it's not necessary to supply the address -- it is more
                   5991: efficient to return the value of the constant directly. That's exactly
                   5992: what happens; the run-time effect of a constant is to put its value on
1.49      anton    5993: the top of the stack (You can find one
                   5994: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29      crook    5995: 
1.69      anton    5996: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29      crook    5997: double and floating-point constants, respectively.
                   5998: 
1.34      anton    5999: doc-constant
                   6000: doc-2constant
                   6001: doc-fconstant
                   6002: 
                   6003: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44      crook    6004: @c nac-> How could that not be true in an ANS Forth? You can't define a
                   6005: @c constant, use it and then delete the definition of the constant..
1.69      anton    6006: 
                   6007: @c anton->An ANS Forth system can compile a constant to a literal; On
                   6008: @c decompilation you would see only the number, just as if it had been used
                   6009: @c in the first place.  The word will stay, of course, but it will only be
                   6010: @c used by the text interpreter (no run-time duties, except when it is 
                   6011: @c POSTPONEd or somesuch).
                   6012: 
                   6013: @c nac:
1.44      crook    6014: @c I agree that it's rather deep, but IMO it is an important difference
                   6015: @c relative to other programming languages.. often it's annoying: it
                   6016: @c certainly changes my programming style relative to C.
                   6017: 
1.69      anton    6018: @c anton: In what way?
                   6019: 
1.29      crook    6020: Constants in Forth behave differently from their equivalents in other
                   6021: programming languages. In other languages, a constant (such as an EQU in
                   6022: assembler or a #define in C) only exists at compile-time; in the
                   6023: executable program the constant has been translated into an absolute
                   6024: number and, unless you are using a symbolic debugger, it's impossible to
                   6025: know what abstract thing that number represents. In Forth a constant has
1.44      crook    6026: an entry in the header space and remains there after the code that uses
                   6027: it has been defined. In fact, it must remain in the dictionary since it
                   6028: has run-time duties to perform. For example:
1.29      crook    6029: 
                   6030: @example
                   6031: 12 Constant INCHES-PER-FOOT
                   6032: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   6033: @end example
                   6034: 
                   6035: @cindex in-lining of constants
                   6036: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   6037: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   6038: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   6039: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   6040: attempt to optimise constants by in-lining them where they are used. You
                   6041: can force Gforth to in-line a constant like this:
                   6042: 
                   6043: @example
                   6044: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   6045: @end example
                   6046: 
                   6047: If you use @code{see} to decompile @i{this} version of
                   6048: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49      anton    6049: longer present. To understand how this works, read
                   6050: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29      crook    6051: 
                   6052: In-lining constants in this way might improve execution time
                   6053: fractionally, and can ensure that a constant is now only referenced at
                   6054: compile-time. However, the definition of the constant still remains in
                   6055: the dictionary. Some Forth compilers provide a mechanism for controlling
                   6056: a second dictionary for holding transient words such that this second
                   6057: dictionary can be deleted later in order to recover memory
                   6058: space. However, there is no standard way of doing this.
                   6059: 
                   6060: 
1.44      crook    6061: @node Values, Colon Definitions, Constants, Defining Words
                   6062: @subsection Values
                   6063: @cindex values
1.34      anton    6064: 
1.69      anton    6065: A @code{Value} behaves like a @code{Constant}, but it can be changed.
                   6066: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
                   6067: (not in ANS Forth) you can access (and change) a @code{value} also with
                   6068: @code{>body}.
                   6069: 
                   6070: Here are some
                   6071: examples:
1.29      crook    6072: 
                   6073: @example
1.69      anton    6074: 12 Value APPLES     \ Define APPLES with an initial value of 12
                   6075: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
                   6076: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
                   6077: APPLES              \ puts 35 on the top of the stack.
1.29      crook    6078: @end example
                   6079: 
1.44      crook    6080: doc-value
                   6081: doc-to
1.29      crook    6082: 
1.35      anton    6083: 
1.69      anton    6084: 
1.44      crook    6085: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
                   6086: @subsection Colon Definitions
                   6087: @cindex colon definitions
1.35      anton    6088: 
                   6089: @example
1.44      crook    6090: : name ( ... -- ... )
                   6091:     word1 word2 word3 ;
1.29      crook    6092: @end example
                   6093: 
1.44      crook    6094: @noindent
                   6095: Creates a word called @code{name} that, upon execution, executes
                   6096: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29      crook    6097: 
1.49      anton    6098: The explanation above is somewhat superficial. For simple examples of
                   6099: colon definitions see @ref{Your first definition}.  For an in-depth
1.66      anton    6100: discussion of some of the issues involved, @xref{Interpretation and
1.49      anton    6101: Compilation Semantics}.
1.29      crook    6102: 
1.44      crook    6103: doc-:
                   6104: doc-;
1.1       anton    6105: 
1.34      anton    6106: 
1.69      anton    6107: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44      crook    6108: @subsection Anonymous Definitions
                   6109: @cindex colon definitions
                   6110: @cindex defining words without name
1.34      anton    6111: 
1.44      crook    6112: Sometimes you want to define an @dfn{anonymous word}; a word without a
                   6113: name. You can do this with:
1.1       anton    6114: 
1.44      crook    6115: doc-:noname
1.1       anton    6116: 
1.44      crook    6117: This leaves the execution token for the word on the stack after the
                   6118: closing @code{;}. Here's an example in which a deferred word is
                   6119: initialised with an @code{xt} from an anonymous colon definition:
1.1       anton    6120: 
1.29      crook    6121: @example
1.44      crook    6122: Defer deferred
                   6123: :noname ( ... -- ... )
                   6124:   ... ;
                   6125: IS deferred
1.29      crook    6126: @end example
1.26      crook    6127: 
1.44      crook    6128: @noindent
                   6129: Gforth provides an alternative way of doing this, using two separate
                   6130: words:
1.27      crook    6131: 
1.44      crook    6132: doc-noname
                   6133: @cindex execution token of last defined word
1.116     anton    6134: doc-latestxt
1.1       anton    6135: 
1.44      crook    6136: @noindent
                   6137: The previous example can be rewritten using @code{noname} and
1.116     anton    6138: @code{latestxt}:
1.1       anton    6139: 
1.26      crook    6140: @example
1.44      crook    6141: Defer deferred
                   6142: noname : ( ... -- ... )
                   6143:   ... ;
1.116     anton    6144: latestxt IS deferred
1.26      crook    6145: @end example
1.1       anton    6146: 
1.29      crook    6147: @noindent
1.44      crook    6148: @code{noname} works with any defining word, not just @code{:}.
                   6149: 
1.116     anton    6150: @code{latestxt} also works when the last word was not defined as
1.71      anton    6151: @code{noname}.  It does not work for combined words, though.  It also has
                   6152: the useful property that is is valid as soon as the header for a
                   6153: definition has been built. Thus:
1.44      crook    6154: 
                   6155: @example
1.116     anton    6156: latestxt . : foo [ latestxt . ] ; ' foo .
1.44      crook    6157: @end example
1.1       anton    6158: 
1.44      crook    6159: @noindent
                   6160: prints 3 numbers; the last two are the same.
1.26      crook    6161: 
1.69      anton    6162: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
                   6163: @subsection Supplying the name of a defined word
                   6164: @cindex names for defined words
                   6165: @cindex defining words, name given in a string
                   6166: 
                   6167: By default, a defining word takes the name for the defined word from the
                   6168: input stream. Sometimes you want to supply the name from a string. You
                   6169: can do this with:
                   6170: 
                   6171: doc-nextname
                   6172: 
                   6173: For example:
                   6174: 
                   6175: @example
                   6176: s" foo" nextname create
                   6177: @end example
                   6178: 
                   6179: @noindent
                   6180: is equivalent to:
                   6181: 
                   6182: @example
                   6183: create foo
                   6184: @end example
                   6185: 
                   6186: @noindent
                   6187: @code{nextname} works with any defining word.
                   6188: 
1.1       anton    6189: 
1.170     pazsan   6190: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26      crook    6191: @subsection User-defined Defining Words
                   6192: @cindex user-defined defining words
                   6193: @cindex defining words, user-defined
1.1       anton    6194: 
1.29      crook    6195: You can create a new defining word by wrapping defining-time code around
                   6196: an existing defining word and putting the sequence in a colon
1.69      anton    6197: definition. 
                   6198: 
                   6199: @c anton: This example is very complex and leads in a quite different
                   6200: @c direction from the CREATE-DOES> stuff that follows.  It should probably
                   6201: @c be done elsewhere, or as a subsubsection of this subsection (or as a
                   6202: @c subsection of Defining Words)
                   6203: 
                   6204: For example, suppose that you have a word @code{stats} that
1.29      crook    6205: gathers statistics about colon definitions given the @i{xt} of the
                   6206: definition, and you want every colon definition in your application to
                   6207: make a call to @code{stats}. You can define and use a new version of
                   6208: @code{:} like this:
                   6209: 
                   6210: @example
                   6211: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   6212:   ... ;  \ other code
                   6213: 
1.116     anton    6214: : my: : latestxt postpone literal ['] stats compile, ;
1.29      crook    6215: 
                   6216: my: foo + - ;
                   6217: @end example
                   6218: 
                   6219: When @code{foo} is defined using @code{my:} these steps occur:
                   6220: 
                   6221: @itemize @bullet
                   6222: @item
                   6223: @code{my:} is executed.
                   6224: @item
                   6225: The @code{:} within the definition (the one between @code{my:} and
1.116     anton    6226: @code{latestxt}) is executed, and does just what it always does; it parses
1.29      crook    6227: the input stream for a name, builds a dictionary header for the name
                   6228: @code{foo} and switches @code{state} from interpret to compile.
                   6229: @item
1.116     anton    6230: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29      crook    6231: being defined -- @code{foo} -- onto the stack.
                   6232: @item
                   6233: The code that was produced by @code{postpone literal} is executed; this
                   6234: causes the value on the stack to be compiled as a literal in the code
                   6235: area of @code{foo}.
                   6236: @item
                   6237: The code @code{['] stats} compiles a literal into the definition of
                   6238: @code{my:}. When @code{compile,} is executed, that literal -- the
                   6239: execution token for @code{stats} -- is layed down in the code area of
                   6240: @code{foo} , following the literal@footnote{Strictly speaking, the
                   6241: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   6242: in the code area is implementation-dependent. A threaded implementation
                   6243: might spit out the execution token directly whilst another
                   6244: implementation might spit out a native code sequence.}.
                   6245: @item
                   6246: At this point, the execution of @code{my:} is complete, and control
                   6247: returns to the text interpreter. The text interpreter is in compile
                   6248: state, so subsequent text @code{+ -} is compiled into the definition of
                   6249: @code{foo} and the @code{;} terminates the definition as always.
                   6250: @end itemize
                   6251: 
                   6252: You can use @code{see} to decompile a word that was defined using
                   6253: @code{my:} and see how it is different from a normal @code{:}
                   6254: definition. For example:
                   6255: 
                   6256: @example
                   6257: : bar + - ;  \ like foo but using : rather than my:
                   6258: see bar
                   6259: : bar
                   6260:   + - ;
                   6261: see foo
                   6262: : foo
                   6263:   107645672 stats + - ;
                   6264: 
1.140     anton    6265: \ use ' foo . to show that 107645672 is the xt for foo
1.29      crook    6266: @end example
                   6267: 
                   6268: You can use techniques like this to make new defining words in terms of
                   6269: @i{any} existing defining word.
1.1       anton    6270: 
                   6271: 
1.29      crook    6272: @cindex defining defining words
1.26      crook    6273: @cindex @code{CREATE} ... @code{DOES>}
                   6274: If you want the words defined with your defining words to behave
                   6275: differently from words defined with standard defining words, you can
                   6276: write your defining word like this:
1.1       anton    6277: 
                   6278: @example
1.26      crook    6279: : def-word ( "name" -- )
1.29      crook    6280:     CREATE @i{code1}
1.26      crook    6281: DOES> ( ... -- ... )
1.29      crook    6282:     @i{code2} ;
1.26      crook    6283: 
                   6284: def-word name
1.1       anton    6285: @end example
                   6286: 
1.29      crook    6287: @cindex child words
                   6288: This fragment defines a @dfn{defining word} @code{def-word} and then
                   6289: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   6290: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   6291: is not executed at this time. The word @code{name} is sometimes called a
                   6292: @dfn{child} of @code{def-word}.
                   6293: 
                   6294: When you execute @code{name}, the address of the body of @code{name} is
                   6295: put on the data stack and @i{code2} is executed (the address of the body
                   6296: of @code{name} is the address @code{HERE} returns immediately after the
1.69      anton    6297: @code{CREATE}, i.e., the address a @code{create}d word returns by
                   6298: default).
                   6299: 
                   6300: @c anton:
                   6301: @c www.dictionary.com says:
                   6302: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
                   6303: @c several generations of absence, usually caused by the chance
                   6304: @c recombination of genes.  2.An individual or a part that exhibits
                   6305: @c atavism. Also called throwback.  3.The return of a trait or recurrence
                   6306: @c of previous behavior after a period of absence.
                   6307: @c
                   6308: @c Doesn't seem to fit.
1.29      crook    6309: 
1.69      anton    6310: @c @cindex atavism in child words
1.33      anton    6311: You can use @code{def-word} to define a set of child words that behave
1.69      anton    6312: similarly; they all have a common run-time behaviour determined by
                   6313: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
                   6314: body of the child word. The structure of the data is common to all
                   6315: children of @code{def-word}, but the data values are specific -- and
                   6316: private -- to each child word. When a child word is executed, the
                   6317: address of its private data area is passed as a parameter on TOS to be
                   6318: used and manipulated@footnote{It is legitimate both to read and write to
                   6319: this data area.} by @i{code2}.
1.29      crook    6320: 
                   6321: The two fragments of code that make up the defining words act (are
                   6322: executed) at two completely separate times:
1.1       anton    6323: 
1.29      crook    6324: @itemize @bullet
                   6325: @item
                   6326: At @i{define time}, the defining word executes @i{code1} to generate a
                   6327: child word
                   6328: @item
                   6329: At @i{child execution time}, when a child word is invoked, @i{code2}
                   6330: is executed, using parameters (data) that are private and specific to
                   6331: the child word.
                   6332: @end itemize
                   6333: 
1.44      crook    6334: Another way of understanding the behaviour of @code{def-word} and
                   6335: @code{name} is to say that, if you make the following definitions:
1.33      anton    6336: @example
                   6337: : def-word1 ( "name" -- )
                   6338:     CREATE @i{code1} ;
                   6339: 
                   6340: : action1 ( ... -- ... )
                   6341:     @i{code2} ;
                   6342: 
                   6343: def-word1 name1
                   6344: @end example
                   6345: 
1.44      crook    6346: @noindent
                   6347: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    6348: 
1.29      crook    6349: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    6350: 
1.1       anton    6351: @example
1.29      crook    6352: : CONSTANT ( w "name" -- )
                   6353:     CREATE ,
1.26      crook    6354: DOES> ( -- w )
                   6355:     @@ ;
1.1       anton    6356: @end example
                   6357: 
1.29      crook    6358: @comment There is a beautiful description of how this works and what
                   6359: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   6360: @comment commentary on the Counting Fruits problem.
                   6361: 
                   6362: When you create a constant with @code{5 CONSTANT five}, a set of
                   6363: define-time actions take place; first a new word @code{five} is created,
                   6364: then the value 5 is laid down in the body of @code{five} with
1.44      crook    6365: @code{,}. When @code{five} is executed, the address of the body is put on
1.29      crook    6366: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   6367: no code of its own; it simply contains a data field and a pointer to the
                   6368: code that follows @code{DOES>} in its defining word. That makes words
                   6369: created in this way very compact.
                   6370: 
                   6371: The final example in this section is intended to remind you that space
                   6372: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   6373: both read and written by a Standard program@footnote{Exercise: use this
                   6374: example as a starting point for your own implementation of @code{Value}
                   6375: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   6376: @code{[']}.}:
                   6377: 
                   6378: @example
                   6379: : foo ( "name" -- )
                   6380:     CREATE -1 ,
                   6381: DOES> ( -- )
1.33      anton    6382:     @@ . ;
1.29      crook    6383: 
                   6384: foo first-word
                   6385: foo second-word
                   6386: 
                   6387: 123 ' first-word >BODY !
                   6388: @end example
                   6389: 
                   6390: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   6391: have executed it to get the address of its data field. However, since it
                   6392: was defined to have @code{DOES>} actions, its execution semantics are to
                   6393: perform those @code{DOES>} actions. To get the address of its data field
                   6394: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   6395: translate the xt into the address of the data field.  When you execute
                   6396: @code{first-word}, it will display @code{123}. When you execute
                   6397: @code{second-word} it will display @code{-1}.
1.26      crook    6398: 
                   6399: @cindex stack effect of @code{DOES>}-parts
                   6400: @cindex @code{DOES>}-parts, stack effect
1.29      crook    6401: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    6402: the stack effect of the defined words, not the stack effect of the
                   6403: following code (the following code expects the address of the body on
                   6404: the top of stack, which is not reflected in the stack comment). This is
                   6405: the convention that I use and recommend (it clashes a bit with using
                   6406: locals declarations for stack effect specification, though).
1.1       anton    6407: 
1.53      anton    6408: @menu
                   6409: * CREATE..DOES> applications::  
                   6410: * CREATE..DOES> details::       
1.63      anton    6411: * Advanced does> usage example::  
1.155     anton    6412: * Const-does>::                 
1.53      anton    6413: @end menu
                   6414: 
                   6415: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26      crook    6416: @subsubsection Applications of @code{CREATE..DOES>}
                   6417: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    6418: 
1.26      crook    6419: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    6420: 
1.26      crook    6421: @cindex factoring similar colon definitions
                   6422: When you see a sequence of code occurring several times, and you can
                   6423: identify a meaning, you will factor it out as a colon definition. When
                   6424: you see similar colon definitions, you can factor them using
                   6425: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   6426: that look very similar:
1.1       anton    6427: @example
1.26      crook    6428: : ori, ( reg-target reg-source n -- )
                   6429:     0 asm-reg-reg-imm ;
                   6430: : andi, ( reg-target reg-source n -- )
                   6431:     1 asm-reg-reg-imm ;
1.1       anton    6432: @end example
                   6433: 
1.26      crook    6434: @noindent
                   6435: This could be factored with:
                   6436: @example
                   6437: : reg-reg-imm ( op-code -- )
                   6438:     CREATE ,
                   6439: DOES> ( reg-target reg-source n -- )
                   6440:     @@ asm-reg-reg-imm ;
                   6441: 
                   6442: 0 reg-reg-imm ori,
                   6443: 1 reg-reg-imm andi,
                   6444: @end example
1.1       anton    6445: 
1.26      crook    6446: @cindex currying
                   6447: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   6448: supply a part of the parameters for a word (known as @dfn{currying} in
                   6449: the functional language community). E.g., @code{+} needs two
                   6450: parameters. Creating versions of @code{+} with one parameter fixed can
                   6451: be done like this:
1.82      anton    6452: 
1.1       anton    6453: @example
1.82      anton    6454: : curry+ ( n1 "name" -- )
1.26      crook    6455:     CREATE ,
                   6456: DOES> ( n2 -- n1+n2 )
                   6457:     @@ + ;
                   6458: 
                   6459:  3 curry+ 3+
                   6460: -2 curry+ 2-
1.1       anton    6461: @end example
                   6462: 
1.91      anton    6463: 
1.63      anton    6464: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26      crook    6465: @subsubsection The gory details of @code{CREATE..DOES>}
                   6466: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    6467: 
1.26      crook    6468: doc-does>
1.1       anton    6469: 
1.26      crook    6470: @cindex @code{DOES>} in a separate definition
                   6471: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   6472: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    6473: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    6474: @example
                   6475: : does1 
                   6476: DOES> ( ... -- ... )
1.44      crook    6477:     ... ;
                   6478: 
                   6479: : does2
                   6480: DOES> ( ... -- ... )
                   6481:     ... ;
                   6482: 
                   6483: : def-word ( ... -- ... )
                   6484:     create ...
                   6485:     IF
                   6486:        does1
                   6487:     ELSE
                   6488:        does2
                   6489:     ENDIF ;
                   6490: @end example
                   6491: 
                   6492: In this example, the selection of whether to use @code{does1} or
1.69      anton    6493: @code{does2} is made at definition-time; at the time that the child word is
1.44      crook    6494: @code{CREATE}d.
                   6495: 
                   6496: @cindex @code{DOES>} in interpretation state
                   6497: In a standard program you can apply a @code{DOES>}-part only if the last
                   6498: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   6499: will override the behaviour of the last word defined in any case. In a
                   6500: standard program, you can use @code{DOES>} only in a colon
                   6501: definition. In Gforth, you can also use it in interpretation state, in a
                   6502: kind of one-shot mode; for example:
                   6503: @example
                   6504: CREATE name ( ... -- ... )
                   6505:   @i{initialization}
                   6506: DOES>
                   6507:   @i{code} ;
                   6508: @end example
                   6509: 
                   6510: @noindent
                   6511: is equivalent to the standard:
                   6512: @example
                   6513: :noname
                   6514: DOES>
                   6515:     @i{code} ;
                   6516: CREATE name EXECUTE ( ... -- ... )
                   6517:     @i{initialization}
                   6518: @end example
                   6519: 
1.53      anton    6520: doc->body
                   6521: 
1.152     pazsan   6522: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63      anton    6523: @subsubsection Advanced does> usage example
                   6524: 
                   6525: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
                   6526: for disassembling instructions, that follow a very repetetive scheme:
                   6527: 
                   6528: @example
                   6529: :noname @var{disasm-operands} s" @var{inst-name}" type ;
                   6530: @var{entry-num} cells @var{table} + !
                   6531: @end example
                   6532: 
                   6533: Of course, this inspires the idea to factor out the commonalities to
                   6534: allow a definition like
                   6535: 
                   6536: @example
                   6537: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
                   6538: @end example
                   6539: 
                   6540: The parameters @var{disasm-operands} and @var{table} are usually
1.69      anton    6541: correlated.  Moreover, before I wrote the disassembler, there already
                   6542: existed code that defines instructions like this:
1.63      anton    6543: 
                   6544: @example
                   6545: @var{entry-num} @var{inst-format} @var{inst-name}
                   6546: @end example
                   6547: 
                   6548: This code comes from the assembler and resides in
                   6549: @file{arch/mips/insts.fs}.
                   6550: 
                   6551: So I had to define the @var{inst-format} words that performed the scheme
                   6552: above when executed.  At first I chose to use run-time code-generation:
                   6553: 
                   6554: @example
                   6555: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
                   6556:   :noname Postpone @var{disasm-operands}
                   6557:   name Postpone sliteral Postpone type Postpone ;
                   6558:   swap cells @var{table} + ! ;
                   6559: @end example
                   6560: 
                   6561: Note that this supplies the other two parameters of the scheme above.
1.44      crook    6562: 
1.63      anton    6563: An alternative would have been to write this using
                   6564: @code{create}/@code{does>}:
                   6565: 
                   6566: @example
                   6567: : @var{inst-format} ( entry-num "name" -- )
                   6568:   here name string, ( entry-num c-addr ) \ parse and save "name"
                   6569:   noname create , ( entry-num )
1.116     anton    6570:   latestxt swap cells @var{table} + !
1.63      anton    6571: does> ( addr w -- )
                   6572:   \ disassemble instruction w at addr
                   6573:   @@ >r 
                   6574:   @var{disasm-operands}
                   6575:   r> count type ;
                   6576: @end example
                   6577: 
                   6578: Somehow the first solution is simpler, mainly because it's simpler to
                   6579: shift a string from definition-time to use-time with @code{sliteral}
                   6580: than with @code{string,} and friends.
                   6581: 
                   6582: I wrote a lot of words following this scheme and soon thought about
                   6583: factoring out the commonalities among them.  Note that this uses a
                   6584: two-level defining word, i.e., a word that defines ordinary defining
                   6585: words.
                   6586: 
                   6587: This time a solution involving @code{postpone} and friends seemed more
                   6588: difficult (try it as an exercise), so I decided to use a
                   6589: @code{create}/@code{does>} word; since I was already at it, I also used
                   6590: @code{create}/@code{does>} for the lower level (try using
                   6591: @code{postpone} etc. as an exercise), resulting in the following
                   6592: definition:
                   6593: 
                   6594: @example
                   6595: : define-format ( disasm-xt table-xt -- )
                   6596:     \ define an instruction format that uses disasm-xt for
                   6597:     \ disassembling and enters the defined instructions into table
                   6598:     \ table-xt
                   6599:     create 2,
                   6600: does> ( u "inst" -- )
                   6601:     \ defines an anonymous word for disassembling instruction inst,
                   6602:     \ and enters it as u-th entry into table-xt
                   6603:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
                   6604:     noname create 2,      \ define anonymous word
1.116     anton    6605:     execute latestxt swap ! \ enter xt of defined word into table-xt
1.63      anton    6606: does> ( addr w -- )
                   6607:     \ disassemble instruction w at addr
                   6608:     2@@ >r ( addr w disasm-xt R: c-addr )
                   6609:     execute ( R: c-addr ) \ disassemble operands
                   6610:     r> count type ; \ print name 
                   6611: @end example
                   6612: 
                   6613: Note that the tables here (in contrast to above) do the @code{cells +}
                   6614: by themselves (that's why you have to pass an xt).  This word is used in
                   6615: the following way:
                   6616: 
                   6617: @example
                   6618: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
                   6619: @end example
                   6620: 
1.71      anton    6621: As shown above, the defined instruction format is then used like this:
                   6622: 
                   6623: @example
                   6624: @var{entry-num} @var{inst-format} @var{inst-name}
                   6625: @end example
                   6626: 
1.63      anton    6627: In terms of currying, this kind of two-level defining word provides the
                   6628: parameters in three stages: first @var{disasm-operands} and @var{table},
                   6629: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
                   6630: the instruction to be disassembled.  
                   6631: 
                   6632: Of course this did not quite fit all the instruction format names used
                   6633: in @file{insts.fs}, so I had to define a few wrappers that conditioned
                   6634: the parameters into the right form.
                   6635: 
                   6636: If you have trouble following this section, don't worry.  First, this is
                   6637: involved and takes time (and probably some playing around) to
                   6638: understand; second, this is the first two-level
                   6639: @code{create}/@code{does>} word I have written in seventeen years of
                   6640: Forth; and if I did not have @file{insts.fs} to start with, I may well
                   6641: have elected to use just a one-level defining word (with some repeating
                   6642: of parameters when using the defining word). So it is not necessary to
                   6643: understand this, but it may improve your understanding of Forth.
1.44      crook    6644: 
                   6645: 
1.152     pazsan   6646: @node Const-does>,  , Advanced does> usage example, User-defined Defining Words
1.91      anton    6647: @subsubsection @code{Const-does>}
                   6648: 
                   6649: A frequent use of @code{create}...@code{does>} is for transferring some
                   6650: values from definition-time to run-time.  Gforth supports this use with
                   6651: 
                   6652: doc-const-does>
                   6653: 
                   6654: A typical use of this word is:
                   6655: 
                   6656: @example
                   6657: : curry+ ( n1 "name" -- )
                   6658: 1 0 CONST-DOES> ( n2 -- n1+n2 )
                   6659:     + ;
                   6660: 
                   6661: 3 curry+ 3+
                   6662: @end example
                   6663: 
                   6664: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
                   6665: definition to run-time.
                   6666: 
                   6667: The advantages of using @code{const-does>} are:
                   6668: 
                   6669: @itemize
                   6670: 
                   6671: @item
                   6672: You don't have to deal with storing and retrieving the values, i.e.,
                   6673: your program becomes more writable and readable.
                   6674: 
                   6675: @item
                   6676: When using @code{does>}, you have to introduce a @code{@@} that cannot
                   6677: be optimized away (because you could change the data using
                   6678: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
                   6679: 
                   6680: @end itemize
                   6681: 
                   6682: An ANS Forth implementation of @code{const-does>} is available in
                   6683: @file{compat/const-does.fs}.
                   6684: 
                   6685: 
1.170     pazsan   6686: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
                   6687: @subsection Deferred Words
1.44      crook    6688: @cindex deferred words
                   6689: 
                   6690: The defining word @code{Defer} allows you to define a word by name
                   6691: without defining its behaviour; the definition of its behaviour is
                   6692: deferred. Here are two situation where this can be useful:
                   6693: 
                   6694: @itemize @bullet
                   6695: @item
                   6696: Where you want to allow the behaviour of a word to be altered later, and
                   6697: for all precompiled references to the word to change when its behaviour
                   6698: is changed.
                   6699: @item
                   6700: For mutual recursion; @xref{Calls and returns}.
                   6701: @end itemize
                   6702: 
                   6703: In the following example, @code{foo} always invokes the version of
                   6704: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
                   6705: always invokes the version that prints ``@code{Hello}''. There is no way
                   6706: of getting @code{foo} to use the later version without re-ordering the
                   6707: source code and recompiling it.
                   6708: 
                   6709: @example
                   6710: : greet ." Good morning" ;
                   6711: : foo ... greet ... ;
                   6712: : greet ." Hello" ;
                   6713: : bar ... greet ... ;
                   6714: @end example
                   6715: 
                   6716: This problem can be solved by defining @code{greet} as a @code{Defer}red
                   6717: word. The behaviour of a @code{Defer}red word can be defined and
                   6718: redefined at any time by using @code{IS} to associate the xt of a
                   6719: previously-defined word with it. The previous example becomes:
                   6720: 
                   6721: @example
1.69      anton    6722: Defer greet ( -- )
1.44      crook    6723: : foo ... greet ... ;
                   6724: : bar ... greet ... ;
1.69      anton    6725: : greet1 ( -- ) ." Good morning" ;
                   6726: : greet2 ( -- ) ." Hello" ;
1.132     anton    6727: ' greet2 IS greet  \ make greet behave like greet2
1.44      crook    6728: @end example
                   6729: 
1.69      anton    6730: @progstyle
                   6731: You should write a stack comment for every deferred word, and put only
                   6732: XTs into deferred words that conform to this stack effect.  Otherwise
                   6733: it's too difficult to use the deferred word.
                   6734: 
1.44      crook    6735: A deferred word can be used to improve the statistics-gathering example
                   6736: from @ref{User-defined Defining Words}; rather than edit the
                   6737: application's source code to change every @code{:} to a @code{my:}, do
                   6738: this:
                   6739: 
                   6740: @example
                   6741: : real: : ;     \ retain access to the original
                   6742: defer :         \ redefine as a deferred word
1.132     anton    6743: ' my: IS :      \ use special version of :
1.44      crook    6744: \
                   6745: \ load application here
                   6746: \
1.132     anton    6747: ' real: IS :    \ go back to the original
1.44      crook    6748: @end example
                   6749: 
                   6750: 
1.132     anton    6751: One thing to note is that @code{IS} has special compilation semantics,
                   6752: such that it parses the name at compile time (like @code{TO}):
1.44      crook    6753: 
                   6754: @example
                   6755: : set-greet ( xt -- )
1.132     anton    6756:   IS greet ;
1.44      crook    6757: 
                   6758: ' greet1 set-greet
                   6759: @end example
                   6760: 
1.132     anton    6761: In situations where @code{IS} does not fit, use @code{defer!} instead.
                   6762: 
1.69      anton    6763: A deferred word can only inherit execution semantics from the xt
                   6764: (because that is all that an xt can represent -- for more discussion of
                   6765: this @pxref{Tokens for Words}); by default it will have default
                   6766: interpretation and compilation semantics deriving from this execution
                   6767: semantics.  However, you can change the interpretation and compilation
                   6768: semantics of the deferred word in the usual ways:
1.44      crook    6769: 
                   6770: @example
1.132     anton    6771: : bar .... ; immediate
1.44      crook    6772: Defer fred immediate
                   6773: Defer jim
                   6774: 
1.132     anton    6775: ' bar IS jim  \ jim has default semantics
                   6776: ' bar IS fred \ fred is immediate
1.44      crook    6777: @end example
                   6778: 
                   6779: doc-defer
1.132     anton    6780: doc-defer!
1.44      crook    6781: doc-is
1.132     anton    6782: doc-defer@
                   6783: doc-action-of
1.44      crook    6784: @comment TODO document these: what's defers [is]
                   6785: doc-defers
                   6786: 
                   6787: @c Use @code{words-deferred} to see a list of deferred words.
                   6788: 
1.132     anton    6789: Definitions of these words (except @code{defers}) in ANS Forth are
                   6790: provided in @file{compat/defer.fs}.
1.44      crook    6791: 
                   6792: 
1.170     pazsan   6793: @node Aliases,  , Deferred Words, Defining Words
1.44      crook    6794: @subsection Aliases
                   6795: @cindex aliases
1.1       anton    6796: 
1.44      crook    6797: The defining word @code{Alias} allows you to define a word by name that
                   6798: has the same behaviour as some other word. Here are two situation where
                   6799: this can be useful:
1.1       anton    6800: 
1.44      crook    6801: @itemize @bullet
                   6802: @item
                   6803: When you want access to a word's definition from a different word list
                   6804: (for an example of this, see the definition of the @code{Root} word list
                   6805: in the Gforth source).
                   6806: @item
                   6807: When you want to create a synonym; a definition that can be known by
                   6808: either of two names (for example, @code{THEN} and @code{ENDIF} are
                   6809: aliases).
                   6810: @end itemize
1.1       anton    6811: 
1.69      anton    6812: Like deferred words, an alias has default compilation and interpretation
                   6813: semantics at the beginning (not the modifications of the other word),
                   6814: but you can change them in the usual ways (@code{immediate},
                   6815: @code{compile-only}). For example:
1.1       anton    6816: 
                   6817: @example
1.44      crook    6818: : foo ... ; immediate
                   6819: 
                   6820: ' foo Alias bar \ bar is not an immediate word
                   6821: ' foo Alias fooby immediate \ fooby is an immediate word
1.1       anton    6822: @end example
                   6823: 
1.44      crook    6824: Words that are aliases have the same xt, different headers in the
                   6825: dictionary, and consequently different name tokens (@pxref{Tokens for
                   6826: Words}) and possibly different immediate flags.  An alias can only have
                   6827: default or immediate compilation semantics; you can define aliases for
                   6828: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1       anton    6829: 
1.44      crook    6830: doc-alias
1.1       anton    6831: 
                   6832: 
1.47      crook    6833: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
                   6834: @section Interpretation and Compilation Semantics
1.26      crook    6835: @cindex semantics, interpretation and compilation
1.1       anton    6836: 
1.71      anton    6837: @c !! state and ' are used without explanation
                   6838: @c example for immediate/compile-only? or is the tutorial enough
                   6839: 
1.26      crook    6840: @cindex interpretation semantics
1.71      anton    6841: The @dfn{interpretation semantics} of a (named) word are what the text
1.26      crook    6842: interpreter does when it encounters the word in interpret state. It also
                   6843: appears in some other contexts, e.g., the execution token returned by
1.71      anton    6844: @code{' @i{word}} identifies the interpretation semantics of @i{word}
                   6845: (in other words, @code{' @i{word} execute} is equivalent to
1.29      crook    6846: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    6847: 
1.26      crook    6848: @cindex compilation semantics
1.71      anton    6849: The @dfn{compilation semantics} of a (named) word are what the text
                   6850: interpreter does when it encounters the word in compile state. It also
                   6851: appears in other contexts, e.g, @code{POSTPONE @i{word}}
                   6852: compiles@footnote{In standard terminology, ``appends to the current
                   6853: definition''.} the compilation semantics of @i{word}.
1.1       anton    6854: 
1.26      crook    6855: @cindex execution semantics
                   6856: The standard also talks about @dfn{execution semantics}. They are used
                   6857: only for defining the interpretation and compilation semantics of many
                   6858: words. By default, the interpretation semantics of a word are to
                   6859: @code{execute} its execution semantics, and the compilation semantics of
                   6860: a word are to @code{compile,} its execution semantics.@footnote{In
                   6861: standard terminology: The default interpretation semantics are its
                   6862: execution semantics; the default compilation semantics are to append its
                   6863: execution semantics to the execution semantics of the current
                   6864: definition.}
                   6865: 
1.71      anton    6866: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
                   6867: the text interpreter, ticked, or @code{postpone}d, so they have no
                   6868: interpretation or compilation semantics.  Their behaviour is represented
                   6869: by their XT (@pxref{Tokens for Words}), and we call it execution
                   6870: semantics, too.
                   6871: 
1.26      crook    6872: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   6873: 
                   6874: @cindex immediate words
                   6875: @cindex compile-only words
                   6876: You can change the semantics of the most-recently defined word:
                   6877: 
1.44      crook    6878: 
1.26      crook    6879: doc-immediate
                   6880: doc-compile-only
                   6881: doc-restrict
                   6882: 
1.82      anton    6883: By convention, words with non-default compilation semantics (e.g.,
                   6884: immediate words) often have names surrounded with brackets (e.g.,
                   6885: @code{[']}, @pxref{Execution token}).
1.44      crook    6886: 
1.26      crook    6887: Note that ticking (@code{'}) a compile-only word gives an error
                   6888: (``Interpreting a compile-only word'').
1.1       anton    6889: 
1.47      crook    6890: @menu
1.67      anton    6891: * Combined words::              
1.47      crook    6892: @end menu
1.44      crook    6893: 
1.71      anton    6894: 
1.48      anton    6895: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44      crook    6896: @subsection Combined Words
                   6897: @cindex combined words
                   6898: 
                   6899: Gforth allows you to define @dfn{combined words} -- words that have an
                   6900: arbitrary combination of interpretation and compilation semantics.
                   6901: 
1.26      crook    6902: doc-interpret/compile:
1.1       anton    6903: 
1.26      crook    6904: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   6905: recommend that you do not define such words, as cute as they may be:
                   6906: they make it hard to get at both parts of the word in some contexts.
                   6907: E.g., assume you want to get an execution token for the compilation
                   6908: part. Instead, define two words, one that embodies the interpretation
                   6909: part, and one that embodies the compilation part.  Once you have done
                   6910: that, you can define a combined word with @code{interpret/compile:} for
                   6911: the convenience of your users.
1.1       anton    6912: 
1.26      crook    6913: You might try to use this feature to provide an optimizing
                   6914: implementation of the default compilation semantics of a word. For
                   6915: example, by defining:
1.1       anton    6916: @example
1.26      crook    6917: :noname
                   6918:    foo bar ;
                   6919: :noname
                   6920:    POSTPONE foo POSTPONE bar ;
1.29      crook    6921: interpret/compile: opti-foobar
1.1       anton    6922: @end example
1.26      crook    6923: 
1.23      crook    6924: @noindent
1.26      crook    6925: as an optimizing version of:
                   6926: 
1.1       anton    6927: @example
1.26      crook    6928: : foobar
                   6929:     foo bar ;
1.1       anton    6930: @end example
                   6931: 
1.26      crook    6932: Unfortunately, this does not work correctly with @code{[compile]},
                   6933: because @code{[compile]} assumes that the compilation semantics of all
                   6934: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    6935: opti-foobar} would compile compilation semantics, whereas
                   6936: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    6937: 
1.26      crook    6938: @cindex state-smart words (are a bad idea)
1.82      anton    6939: @anchor{state-smartness}
1.29      crook    6940: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    6941: by @code{interpret/compile:} (words are state-smart if they check
                   6942: @code{STATE} during execution). E.g., they would try to code
                   6943: @code{foobar} like this:
1.1       anton    6944: 
1.26      crook    6945: @example
                   6946: : foobar
                   6947:   STATE @@
                   6948:   IF ( compilation state )
                   6949:     POSTPONE foo POSTPONE bar
                   6950:   ELSE
                   6951:     foo bar
                   6952:   ENDIF ; immediate
                   6953: @end example
1.1       anton    6954: 
1.26      crook    6955: Although this works if @code{foobar} is only processed by the text
                   6956: interpreter, it does not work in other contexts (like @code{'} or
                   6957: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   6958: for a state-smart word, not for the interpretation semantics of the
                   6959: original @code{foobar}; when you execute this execution token (directly
                   6960: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   6961: state, the result will not be what you expected (i.e., it will not
                   6962: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   6963: write them@footnote{For a more detailed discussion of this topic, see
1.66      anton    6964: M. Anton Ertl,
                   6965: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
                   6966: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1       anton    6967: 
1.26      crook    6968: @cindex defining words with arbitrary semantics combinations
                   6969: It is also possible to write defining words that define words with
                   6970: arbitrary combinations of interpretation and compilation semantics. In
                   6971: general, they look like this:
1.1       anton    6972: 
1.26      crook    6973: @example
                   6974: : def-word
                   6975:     create-interpret/compile
1.29      crook    6976:     @i{code1}
1.26      crook    6977: interpretation>
1.29      crook    6978:     @i{code2}
1.26      crook    6979: <interpretation
                   6980: compilation>
1.29      crook    6981:     @i{code3}
1.26      crook    6982: <compilation ;
                   6983: @end example
1.1       anton    6984: 
1.29      crook    6985: For a @i{word} defined with @code{def-word}, the interpretation
                   6986: semantics are to push the address of the body of @i{word} and perform
                   6987: @i{code2}, and the compilation semantics are to push the address of
                   6988: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    6989: can also be defined like this (except that the defined constants don't
                   6990: behave correctly when @code{[compile]}d):
1.1       anton    6991: 
1.26      crook    6992: @example
                   6993: : constant ( n "name" -- )
                   6994:     create-interpret/compile
                   6995:     ,
                   6996: interpretation> ( -- n )
                   6997:     @@
                   6998: <interpretation
                   6999: compilation> ( compilation. -- ; run-time. -- n )
                   7000:     @@ postpone literal
                   7001: <compilation ;
                   7002: @end example
1.1       anton    7003: 
1.44      crook    7004: 
1.26      crook    7005: doc-create-interpret/compile
                   7006: doc-interpretation>
                   7007: doc-<interpretation
                   7008: doc-compilation>
                   7009: doc-<compilation
1.1       anton    7010: 
1.44      crook    7011: 
1.29      crook    7012: Words defined with @code{interpret/compile:} and
1.26      crook    7013: @code{create-interpret/compile} have an extended header structure that
                   7014: differs from other words; however, unless you try to access them with
                   7015: plain address arithmetic, you should not notice this. Words for
                   7016: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    7017: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   7018: with @code{create-interpret/compile}.
1.1       anton    7019: 
1.44      crook    7020: 
1.47      crook    7021: @c -------------------------------------------------------------
1.81      anton    7022: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47      crook    7023: @section Tokens for Words
                   7024: @cindex tokens for words
                   7025: 
                   7026: This section describes the creation and use of tokens that represent
                   7027: words.
                   7028: 
1.71      anton    7029: @menu
                   7030: * Execution token::             represents execution/interpretation semantics
                   7031: * Compilation token::           represents compilation semantics
                   7032: * Name token::                  represents named words
                   7033: @end menu
1.47      crook    7034: 
1.71      anton    7035: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
                   7036: @subsection Execution token
1.47      crook    7037: 
                   7038: @cindex xt
                   7039: @cindex execution token
1.71      anton    7040: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
                   7041: You can use @code{execute} to invoke this behaviour.
1.47      crook    7042: 
1.71      anton    7043: @cindex tick (')
                   7044: You can use @code{'} to get an execution token that represents the
                   7045: interpretation semantics of a named word:
1.47      crook    7046: 
                   7047: @example
1.97      anton    7048: 5 ' .   ( n xt ) 
                   7049: execute ( )      \ execute the xt (i.e., ".")
1.71      anton    7050: @end example
1.47      crook    7051: 
1.71      anton    7052: doc-'
                   7053: 
                   7054: @code{'} parses at run-time; there is also a word @code{[']} that parses
                   7055: when it is compiled, and compiles the resulting XT:
                   7056: 
                   7057: @example
                   7058: : foo ['] . execute ;
                   7059: 5 foo
                   7060: : bar ' execute ; \ by contrast,
                   7061: 5 bar .           \ ' parses "." when bar executes
                   7062: @end example
                   7063: 
                   7064: doc-[']
                   7065: 
                   7066: If you want the execution token of @i{word}, write @code{['] @i{word}}
                   7067: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
                   7068: @code{'} and @code{[']} behave somewhat unusually by complaining about
                   7069: compile-only words (because these words have no interpretation
                   7070: semantics).  You might get what you want by using @code{COMP' @i{word}
                   7071: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
                   7072: token}).
                   7073: 
1.116     anton    7074: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71      anton    7075: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
                   7076: for the only behaviour the word has (the execution semantics).  For
1.116     anton    7077: named words, @code{latestxt} produces an XT for the same behaviour it
1.71      anton    7078: would produce if the word was defined anonymously.
                   7079: 
                   7080: @example
                   7081: :noname ." hello" ;
                   7082: execute
1.47      crook    7083: @end example
                   7084: 
1.71      anton    7085: An XT occupies one cell and can be manipulated like any other cell.
                   7086: 
1.47      crook    7087: @cindex code field address
                   7088: @cindex CFA
1.71      anton    7089: In ANS Forth the XT is just an abstract data type (i.e., defined by the
                   7090: operations that produce or consume it).  For old hands: In Gforth, the
                   7091: XT is implemented as a code field address (CFA).
                   7092: 
                   7093: doc-execute
                   7094: doc-perform
                   7095: 
                   7096: @node Compilation token, Name token, Execution token, Tokens for Words
                   7097: @subsection Compilation token
1.47      crook    7098: 
                   7099: @cindex compilation token
1.71      anton    7100: @cindex CT (compilation token)
                   7101: Gforth represents the compilation semantics of a named word by a
1.47      crook    7102: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   7103: @i{xt} is an execution token. The compilation semantics represented by
                   7104: the compilation token can be performed with @code{execute}, which
                   7105: consumes the whole compilation token, with an additional stack effect
                   7106: determined by the represented compilation semantics.
                   7107: 
                   7108: At present, the @i{w} part of a compilation token is an execution token,
                   7109: and the @i{xt} part represents either @code{execute} or
                   7110: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   7111: word. If the word has default compilation semantics, the @i{xt} will
                   7112: represent @code{compile,}. Otherwise (e.g., for immediate words), the
                   7113: @i{xt} will represent @code{execute}.}. However, don't rely on that
                   7114: knowledge, unless necessary; future versions of Gforth may introduce
                   7115: unusual compilation tokens (e.g., a compilation token that represents
                   7116: the compilation semantics of a literal).
                   7117: 
1.71      anton    7118: You can perform the compilation semantics represented by the compilation
                   7119: token with @code{execute}.  You can compile the compilation semantics
                   7120: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
                   7121: equivalent to @code{postpone @i{word}}.
                   7122: 
                   7123: doc-[comp']
                   7124: doc-comp'
                   7125: doc-postpone,
                   7126: 
                   7127: @node Name token,  , Compilation token, Tokens for Words
                   7128: @subsection Name token
1.47      crook    7129: 
                   7130: @cindex name token
1.116     anton    7131: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
                   7132: token is an abstract data type that occurs as argument or result of the
                   7133: words below.
                   7134: 
                   7135: @c !! put this elswhere?
1.47      crook    7136: @cindex name field address
                   7137: @cindex NFA
1.116     anton    7138: The closest thing to the nt in older Forth systems is the name field
                   7139: address (NFA), but there are significant differences: in older Forth
                   7140: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
                   7141: LFA, NFA, CFA, PFA) and there were words for getting from one to the
                   7142: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
                   7143: is a link field in the structure identified by the name token, but
                   7144: searching usually uses a hash table external to these structures; the
                   7145: name in Gforth has a cell-wide count-and-flags field, and the nt is not
                   7146: implemented as the address of that count field.
1.47      crook    7147: 
                   7148: doc-find-name
1.116     anton    7149: doc-latest
                   7150: doc->name
1.47      crook    7151: doc-name>int
                   7152: doc-name?int
                   7153: doc-name>comp
                   7154: doc-name>string
1.109     anton    7155: doc-id.
                   7156: doc-.name
                   7157: doc-.id
1.47      crook    7158: 
1.81      anton    7159: @c ----------------------------------------------------------
                   7160: @node Compiling words, The Text Interpreter, Tokens for Words, Words
                   7161: @section Compiling words
                   7162: @cindex compiling words
                   7163: @cindex macros
                   7164: 
                   7165: In contrast to most other languages, Forth has no strict boundary
1.82      anton    7166: between compilation and run-time.  E.g., you can run arbitrary code
                   7167: between defining words (or for computing data used by defining words
                   7168: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
                   7169: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
                   7170: running arbitrary code while compiling a colon definition (exception:
                   7171: you must not allot dictionary space).
                   7172: 
                   7173: @menu
                   7174: * Literals::                    Compiling data values
                   7175: * Macros::                      Compiling words
                   7176: @end menu
                   7177: 
                   7178: @node Literals, Macros, Compiling words, Compiling words
                   7179: @subsection Literals
                   7180: @cindex Literals
                   7181: 
                   7182: The simplest and most frequent example is to compute a literal during
                   7183: compilation.  E.g., the following definition prints an array of strings,
                   7184: one string per line:
                   7185: 
                   7186: @example
                   7187: : .strings ( addr u -- ) \ gforth
                   7188:     2* cells bounds U+DO
                   7189:        cr i 2@@ type
                   7190:     2 cells +LOOP ;  
                   7191: @end example
1.81      anton    7192: 
1.82      anton    7193: With a simple-minded compiler like Gforth's, this computes @code{2
                   7194: cells} on every loop iteration.  You can compute this value once and for
                   7195: all at compile time and compile it into the definition like this:
                   7196: 
                   7197: @example
                   7198: : .strings ( addr u -- ) \ gforth
                   7199:     2* cells bounds U+DO
                   7200:        cr i 2@@ type
                   7201:     [ 2 cells ] literal +LOOP ;  
                   7202: @end example
                   7203: 
                   7204: @code{[} switches the text interpreter to interpret state (you will get
                   7205: an @code{ok} prompt if you type this example interactively and insert a
                   7206: newline between @code{[} and @code{]}), so it performs the
                   7207: interpretation semantics of @code{2 cells}; this computes a number.
                   7208: @code{]} switches the text interpreter back into compile state.  It then
                   7209: performs @code{Literal}'s compilation semantics, which are to compile
                   7210: this number into the current word.  You can decompile the word with
                   7211: @code{see .strings} to see the effect on the compiled code.
1.81      anton    7212: 
1.82      anton    7213: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
                   7214: *} in this way.
1.81      anton    7215: 
1.82      anton    7216: doc-[
                   7217: doc-]
1.81      anton    7218: doc-literal
                   7219: doc-]L
1.82      anton    7220: 
                   7221: There are also words for compiling other data types than single cells as
                   7222: literals:
                   7223: 
1.81      anton    7224: doc-2literal
                   7225: doc-fliteral
1.82      anton    7226: doc-sliteral
                   7227: 
                   7228: @cindex colon-sys, passing data across @code{:}
                   7229: @cindex @code{:}, passing data across
                   7230: You might be tempted to pass data from outside a colon definition to the
                   7231: inside on the data stack.  This does not work, because @code{:} puhes a
                   7232: colon-sys, making stuff below unaccessible.  E.g., this does not work:
                   7233: 
                   7234: @example
                   7235: 5 : foo literal ; \ error: "unstructured"
                   7236: @end example
                   7237: 
                   7238: Instead, you have to pass the value in some other way, e.g., through a
                   7239: variable:
                   7240: 
                   7241: @example
                   7242: variable temp
                   7243: 5 temp !
                   7244: : foo [ temp @@ ] literal ;
                   7245: @end example
                   7246: 
                   7247: 
                   7248: @node Macros,  , Literals, Compiling words
                   7249: @subsection Macros
                   7250: @cindex Macros
                   7251: @cindex compiling compilation semantics
                   7252: 
                   7253: @code{Literal} and friends compile data values into the current
                   7254: definition.  You can also write words that compile other words into the
                   7255: current definition.  E.g.,
                   7256: 
                   7257: @example
                   7258: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
                   7259:   POSTPONE + ;
                   7260: 
                   7261: : foo ( n1 n2 -- n )
                   7262:   [ compile-+ ] ;
                   7263: 1 2 foo .
                   7264: @end example
                   7265: 
                   7266: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
                   7267: What happens in this example?  @code{Postpone} compiles the compilation
                   7268: semantics of @code{+} into @code{compile-+}; later the text interpreter
                   7269: executes @code{compile-+} and thus the compilation semantics of +, which
                   7270: compile (the execution semantics of) @code{+} into
                   7271: @code{foo}.@footnote{A recent RFI answer requires that compiling words
                   7272: should only be executed in compile state, so this example is not
                   7273: guaranteed to work on all standard systems, but on any decent system it
                   7274: will work.}
                   7275: 
                   7276: doc-postpone
                   7277: doc-[compile]
                   7278: 
                   7279: Compiling words like @code{compile-+} are usually immediate (or similar)
                   7280: so you do not have to switch to interpret state to execute them;
                   7281: mopifying the last example accordingly produces:
                   7282: 
                   7283: @example
                   7284: : [compile-+] ( compilation: --; interpretation: -- )
                   7285:   \ compiled code: ( n1 n2 -- n )
                   7286:   POSTPONE + ; immediate
                   7287: 
                   7288: : foo ( n1 n2 -- n )
                   7289:   [compile-+] ;
                   7290: 1 2 foo .
                   7291: @end example
                   7292: 
                   7293: Immediate compiling words are similar to macros in other languages (in
                   7294: particular, Lisp).  The important differences to macros in, e.g., C are:
                   7295: 
                   7296: @itemize @bullet
                   7297: 
                   7298: @item
                   7299: You use the same language for defining and processing macros, not a
                   7300: separate preprocessing language and processor.
                   7301: 
                   7302: @item
                   7303: Consequently, the full power of Forth is available in macro definitions.
                   7304: E.g., you can perform arbitrarily complex computations, or generate
                   7305: different code conditionally or in a loop (e.g., @pxref{Advanced macros
                   7306: Tutorial}).  This power is very useful when writing a parser generators
                   7307: or other code-generating software.
                   7308: 
                   7309: @item
                   7310: Macros defined using @code{postpone} etc. deal with the language at a
                   7311: higher level than strings; name binding happens at macro definition
                   7312: time, so you can avoid the pitfalls of name collisions that can happen
                   7313: in C macros.  Of course, Forth is a liberal language and also allows to
                   7314: shoot yourself in the foot with text-interpreted macros like
                   7315: 
                   7316: @example
                   7317: : [compile-+] s" +" evaluate ; immediate
                   7318: @end example
                   7319: 
                   7320: Apart from binding the name at macro use time, using @code{evaluate}
                   7321: also makes your definition @code{state}-smart (@pxref{state-smartness}).
                   7322: @end itemize
                   7323: 
                   7324: You may want the macro to compile a number into a word.  The word to do
                   7325: it is @code{literal}, but you have to @code{postpone} it, so its
                   7326: compilation semantics take effect when the macro is executed, not when
                   7327: it is compiled:
                   7328: 
                   7329: @example
                   7330: : [compile-5] ( -- ) \ compiled code: ( -- n )
                   7331:   5 POSTPONE literal ; immediate
                   7332: 
                   7333: : foo [compile-5] ;
                   7334: foo .
                   7335: @end example
                   7336: 
                   7337: You may want to pass parameters to a macro, that the macro should
                   7338: compile into the current definition.  If the parameter is a number, then
                   7339: you can use @code{postpone literal} (similar for other values).
                   7340: 
                   7341: If you want to pass a word that is to be compiled, the usual way is to
                   7342: pass an execution token and @code{compile,} it:
                   7343: 
                   7344: @example
                   7345: : twice1 ( xt -- ) \ compiled code: ... -- ...
                   7346:   dup compile, compile, ;
                   7347: 
                   7348: : 2+ ( n1 -- n2 )
                   7349:   [ ' 1+ twice1 ] ;
                   7350: @end example
                   7351: 
                   7352: doc-compile,
                   7353: 
                   7354: An alternative available in Gforth, that allows you to pass compile-only
                   7355: words as parameters is to use the compilation token (@pxref{Compilation
                   7356: token}).  The same example in this technique:
                   7357: 
                   7358: @example
                   7359: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
                   7360:   2dup 2>r execute 2r> execute ;
                   7361: 
                   7362: : 2+ ( n1 -- n2 )
                   7363:   [ comp' 1+ twice ] ;
                   7364: @end example
                   7365: 
                   7366: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
                   7367: works even if the executed compilation semantics has an effect on the
                   7368: data stack.
                   7369: 
                   7370: You can also define complete definitions with these words; this provides
                   7371: an alternative to using @code{does>} (@pxref{User-defined Defining
                   7372: Words}).  E.g., instead of
                   7373: 
                   7374: @example
                   7375: : curry+ ( n1 "name" -- )
                   7376:     CREATE ,
                   7377: DOES> ( n2 -- n1+n2 )
                   7378:     @@ + ;
                   7379: @end example
                   7380: 
                   7381: you could define
                   7382: 
                   7383: @example
                   7384: : curry+ ( n1 "name" -- )
                   7385:   \ name execution: ( n2 -- n1+n2 )
                   7386:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81      anton    7387: 
1.82      anton    7388: -3 curry+ 3-
                   7389: see 3-
                   7390: @end example
1.81      anton    7391: 
1.82      anton    7392: The sequence @code{>r : r>} is necessary, because @code{:} puts a
                   7393: colon-sys on the data stack that makes everything below it unaccessible.
1.81      anton    7394: 
1.82      anton    7395: This way of writing defining words is sometimes more, sometimes less
                   7396: convenient than using @code{does>} (@pxref{Advanced does> usage
                   7397: example}).  One advantage of this method is that it can be optimized
                   7398: better, because the compiler knows that the value compiled with
                   7399: @code{literal} is fixed, whereas the data associated with a
                   7400: @code{create}d word can be changed.
1.47      crook    7401: 
1.26      crook    7402: @c ----------------------------------------------------------
1.111     anton    7403: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26      crook    7404: @section  The Text Interpreter
                   7405: @cindex interpreter - outer
                   7406: @cindex text interpreter
                   7407: @cindex outer interpreter
1.1       anton    7408: 
1.34      anton    7409: @c Should we really describe all these ugly details?  IMO the text
                   7410: @c interpreter should be much cleaner, but that may not be possible within
                   7411: @c ANS Forth. - anton
1.44      crook    7412: @c nac-> I wanted to explain how it works to show how you can exploit
                   7413: @c it in your own programs. When I was writing a cross-compiler, figuring out
                   7414: @c some of these gory details was very helpful to me. None of the textbooks
                   7415: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
                   7416: @c seems to positively avoid going into too much detail for some of
                   7417: @c the internals.
1.34      anton    7418: 
1.71      anton    7419: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
                   7420: @c it is; for the ugly details, I would prefer another place.  I wonder
                   7421: @c whether we should have a chapter before "Words" that describes some
                   7422: @c basic concepts referred to in words, and a chapter after "Words" that
                   7423: @c describes implementation details.
                   7424: 
1.29      crook    7425: The text interpreter@footnote{This is an expanded version of the
                   7426: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34      anton    7427: that processes input from the current input device. It is also called
                   7428: the outer interpreter, in contrast to the inner interpreter
                   7429: (@pxref{Engine}) which executes the compiled Forth code on interpretive
                   7430: implementations.
1.27      crook    7431: 
1.29      crook    7432: @cindex interpret state
                   7433: @cindex compile state
                   7434: The text interpreter operates in one of two states: @dfn{interpret
                   7435: state} and @dfn{compile state}. The current state is defined by the
1.71      anton    7436: aptly-named variable @code{state}.
1.29      crook    7437: 
                   7438: This section starts by describing how the text interpreter behaves when
                   7439: it is in interpret state, processing input from the user input device --
                   7440: the keyboard. This is the mode that a Forth system is in after it starts
                   7441: up.
                   7442: 
                   7443: @cindex input buffer
                   7444: @cindex terminal input buffer
                   7445: The text interpreter works from an area of memory called the @dfn{input
                   7446: buffer}@footnote{When the text interpreter is processing input from the
                   7447: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   7448: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   7449: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    7450: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    7451: leading spaces (called @dfn{delimiters}) then parses a string (a
                   7452: sequence of non-space characters) until it reaches either a space
                   7453: character or the end of the buffer. Having parsed a string, it makes two
                   7454: attempts to process it:
1.27      crook    7455: 
1.29      crook    7456: @cindex dictionary
1.27      crook    7457: @itemize @bullet
                   7458: @item
1.29      crook    7459: It looks for the string in a @dfn{dictionary} of definitions. If the
                   7460: string is found, the string names a @dfn{definition} (also known as a
                   7461: @dfn{word}) and the dictionary search returns information that allows
                   7462: the text interpreter to perform the word's @dfn{interpretation
                   7463: semantics}. In most cases, this simply means that the word will be
                   7464: executed.
1.27      crook    7465: @item
                   7466: If the string is not found in the dictionary, the text interpreter
1.29      crook    7467: attempts to treat it as a number, using the rules described in
                   7468: @ref{Number Conversion}. If the string represents a legal number in the
                   7469: current radix, the number is pushed onto a parameter stack (the data
                   7470: stack for integers, the floating-point stack for floating-point
                   7471: numbers).
                   7472: @end itemize
                   7473: 
                   7474: If both attempts fail, or if the word is found in the dictionary but has
                   7475: no interpretation semantics@footnote{This happens if the word was
                   7476: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   7477: remainder of the input buffer, issues an error message and waits for
                   7478: more input. If one of the attempts succeeds, the text interpreter
                   7479: repeats the parsing process until the whole of the input buffer has been
                   7480: processed, at which point it prints the status message ``@code{ ok}''
                   7481: and waits for more input.
                   7482: 
1.71      anton    7483: @c anton: this should be in the input stream subsection (or below it)
                   7484: 
1.29      crook    7485: @cindex parse area
                   7486: The text interpreter keeps track of its position in the input buffer by
                   7487: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   7488: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   7489: of the input buffer. The region from offset @code{>IN @@} to the end of
                   7490: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   7491: the text interpreter processes the contents of the input buffer by
                   7492: parsing strings from the parse area until the parse area is empty.}.
                   7493: This example shows how @code{>IN} changes as the text interpreter parses
                   7494: the input buffer:
                   7495: 
                   7496: @example
                   7497: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   7498:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   7499: 
                   7500: 1 2 3 remaining + remaining . 
                   7501: 
                   7502: : foo 1 2 3 remaining SWAP remaining ;
                   7503: @end example
                   7504: 
                   7505: @noindent
                   7506: The result is:
                   7507: 
                   7508: @example
                   7509: ->+ remaining .<-
                   7510: ->.<-5  ok
                   7511: 
                   7512: ->SWAP remaining ;-<
                   7513: ->;<-  ok
                   7514: @end example
                   7515: 
                   7516: @cindex parsing words
                   7517: The value of @code{>IN} can also be modified by a word in the input
                   7518: buffer that is executed by the text interpreter.  This means that a word
                   7519: can ``trick'' the text interpreter into either skipping a section of the
                   7520: input buffer@footnote{This is how parsing words work.} or into parsing a
                   7521: section twice. For example:
1.27      crook    7522: 
1.29      crook    7523: @example
1.71      anton    7524: : lat ." <<foo>>" ;
                   7525: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29      crook    7526: @end example
                   7527: 
                   7528: @noindent
                   7529: When @code{flat} is executed, this output is produced@footnote{Exercise
                   7530: for the reader: what would happen if the @code{3} were replaced with
                   7531: @code{4}?}:
                   7532: 
                   7533: @example
1.71      anton    7534: <<bar>><<foo>>
1.29      crook    7535: @end example
                   7536: 
1.71      anton    7537: This technique can be used to work around some of the interoperability
                   7538: problems of parsing words.  Of course, it's better to avoid parsing
                   7539: words where possible.
                   7540: 
1.29      crook    7541: @noindent
                   7542: Two important notes about the behaviour of the text interpreter:
1.27      crook    7543: 
                   7544: @itemize @bullet
                   7545: @item
                   7546: It processes each input string to completion before parsing additional
1.29      crook    7547: characters from the input buffer.
                   7548: @item
                   7549: It treats the input buffer as a read-only region (and so must your code).
                   7550: @end itemize
                   7551: 
                   7552: @noindent
                   7553: When the text interpreter is in compile state, its behaviour changes in
                   7554: these ways:
                   7555: 
                   7556: @itemize @bullet
                   7557: @item
                   7558: If a parsed string is found in the dictionary, the text interpreter will
                   7559: perform the word's @dfn{compilation semantics}. In most cases, this
                   7560: simply means that the execution semantics of the word will be appended
                   7561: to the current definition.
1.27      crook    7562: @item
1.29      crook    7563: When a number is encountered, it is compiled into the current definition
                   7564: (as a literal) rather than being pushed onto a parameter stack.
                   7565: @item
                   7566: If an error occurs, @code{state} is modified to put the text interpreter
                   7567: back into interpret state.
                   7568: @item
                   7569: Each time a line is entered from the keyboard, Gforth prints
                   7570: ``@code{ compiled}'' rather than `` @code{ok}''.
                   7571: @end itemize
                   7572: 
                   7573: @cindex text interpreter - input sources
                   7574: When the text interpreter is using an input device other than the
                   7575: keyboard, its behaviour changes in these ways:
                   7576: 
                   7577: @itemize @bullet
                   7578: @item
                   7579: When the parse area is empty, the text interpreter attempts to refill
                   7580: the input buffer from the input source. When the input source is
1.71      anton    7581: exhausted, the input source is set back to the previous input source.
1.29      crook    7582: @item
                   7583: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   7584: time the parse area is emptied.
                   7585: @item
                   7586: If an error occurs, the input source is set back to the user input
                   7587: device.
1.27      crook    7588: @end itemize
1.21      crook    7589: 
1.49      anton    7590: You can read about this in more detail in @ref{Input Sources}.
1.44      crook    7591: 
1.26      crook    7592: doc->in
1.27      crook    7593: doc-source
                   7594: 
1.26      crook    7595: doc-tib
                   7596: doc-#tib
1.1       anton    7597: 
1.44      crook    7598: 
1.26      crook    7599: @menu
1.67      anton    7600: * Input Sources::               
                   7601: * Number Conversion::           
                   7602: * Interpret/Compile states::    
                   7603: * Interpreter Directives::      
1.26      crook    7604: @end menu
1.1       anton    7605: 
1.29      crook    7606: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   7607: @subsection Input Sources
                   7608: @cindex input sources
                   7609: @cindex text interpreter - input sources
                   7610: 
1.44      crook    7611: By default, the text interpreter processes input from the user input
1.29      crook    7612: device (the keyboard) when Forth starts up. The text interpreter can
                   7613: process input from any of these sources:
                   7614: 
                   7615: @itemize @bullet
                   7616: @item
                   7617: The user input device -- the keyboard.
                   7618: @item
                   7619: A file, using the words described in @ref{Forth source files}.
                   7620: @item
                   7621: A block, using the words described in @ref{Blocks}.
                   7622: @item
                   7623: A text string, using @code{evaluate}.
                   7624: @end itemize
                   7625: 
                   7626: A program can identify the current input device from the values of
                   7627: @code{source-id} and @code{blk}.
                   7628: 
1.44      crook    7629: 
1.29      crook    7630: doc-source-id
                   7631: doc-blk
                   7632: 
                   7633: doc-save-input
                   7634: doc-restore-input
                   7635: 
                   7636: doc-evaluate
1.111     anton    7637: doc-query
1.1       anton    7638: 
1.29      crook    7639: 
1.44      crook    7640: 
1.29      crook    7641: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    7642: @subsection Number Conversion
                   7643: @cindex number conversion
                   7644: @cindex double-cell numbers, input format
                   7645: @cindex input format for double-cell numbers
                   7646: @cindex single-cell numbers, input format
                   7647: @cindex input format for single-cell numbers
                   7648: @cindex floating-point numbers, input format
                   7649: @cindex input format for floating-point numbers
1.1       anton    7650: 
1.29      crook    7651: This section describes the rules that the text interpreter uses when it
                   7652: tries to convert a string into a number.
1.1       anton    7653: 
1.26      crook    7654: Let <digit> represent any character that is a legal digit in the current
1.29      crook    7655: number base@footnote{For example, 0-9 when the number base is decimal or
                   7656: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    7657: 
1.26      crook    7658: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    7659: 
1.29      crook    7660: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   7661: in the braces (@i{a} or @i{b} or neither).
1.1       anton    7662: 
1.26      crook    7663: Let * represent any number of instances of the previous character
                   7664: (including none).
1.1       anton    7665: 
1.26      crook    7666: Let any other character represent itself.
1.1       anton    7667: 
1.29      crook    7668: @noindent
1.26      crook    7669: Now, the conversion rules are:
1.21      crook    7670: 
1.26      crook    7671: @itemize @bullet
                   7672: @item
                   7673: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    7674: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    7675: @item
                   7676: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    7677: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    7678: arithmetic. Examples are -45 -5681 -0
                   7679: @item
                   7680: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    7681: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   7682: (all three of these represent the same number).
1.26      crook    7683: @item
                   7684: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    7685: double-precision (double-cell-sized) negative integer, and is
1.26      crook    7686: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    7687: -34.65 (all three of these represent the same number).
1.26      crook    7688: @item
1.29      crook    7689: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   7690: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35      anton    7691: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    7692: number) +12.E-4
1.26      crook    7693: @end itemize
1.1       anton    7694: 
1.26      crook    7695: By default, the number base used for integer number conversion is given
1.35      anton    7696: by the contents of the variable @code{base}.  Note that a lot of
                   7697: confusion can result from unexpected values of @code{base}.  If you
                   7698: change @code{base} anywhere, make sure to save the old value and restore
                   7699: it afterwards.  In general I recommend keeping @code{base} decimal, and
                   7700: using the prefixes described below for the popular non-decimal bases.
1.1       anton    7701: 
1.29      crook    7702: doc-dpl
1.26      crook    7703: doc-base
                   7704: doc-hex
                   7705: doc-decimal
1.1       anton    7706: 
1.26      crook    7707: @cindex '-prefix for character strings
                   7708: @cindex &-prefix for decimal numbers
1.133     anton    7709: @cindex #-prefix for decimal numbers
1.26      crook    7710: @cindex %-prefix for binary numbers
                   7711: @cindex $-prefix for hexadecimal numbers
1.133     anton    7712: @cindex 0x-prefix for hexadecimal numbers
1.35      anton    7713: Gforth allows you to override the value of @code{base} by using a
1.29      crook    7714: prefix@footnote{Some Forth implementations provide a similar scheme by
                   7715: implementing @code{$} etc. as parsing words that process the subsequent
                   7716: number in the input stream and push it onto the stack. For example, see
                   7717: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   7718: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   7719: is required between the prefix and the number.} before the first digit
1.133     anton    7720: of an (integer) number. The following prefixes are supported:
1.1       anton    7721: 
1.26      crook    7722: @itemize @bullet
                   7723: @item
1.35      anton    7724: @code{&} -- decimal
1.26      crook    7725: @item
1.133     anton    7726: @code{#} -- decimal
                   7727: @item
1.35      anton    7728: @code{%} -- binary
1.26      crook    7729: @item
1.35      anton    7730: @code{$} -- hexadecimal
1.26      crook    7731: @item
1.133     anton    7732: @code{0x} -- hexadecimal, if base<33.
                   7733: @item
                   7734: @code{'} -- numeric value (e.g., ASCII code) of next character; an
                   7735: optional @code{'} may be present after the character.
1.26      crook    7736: @end itemize
1.1       anton    7737: 
1.26      crook    7738: Here are some examples, with the equivalent decimal number shown after
                   7739: in braces:
1.1       anton    7740: 
1.26      crook    7741: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133     anton    7742: 'A (65),
                   7743: -'a' (-97),
1.26      crook    7744: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    7745: 
1.26      crook    7746: @cindex number conversion - traps for the unwary
1.29      crook    7747: @noindent
1.26      crook    7748: Number conversion has a number of traps for the unwary:
1.1       anton    7749: 
1.26      crook    7750: @itemize @bullet
                   7751: @item
                   7752: You cannot determine the current number base using the code sequence
1.35      anton    7753: @code{base @@ .} -- the number base is always 10 in the current number
                   7754: base. Instead, use something like @code{base @@ dec.}
1.26      crook    7755: @item
                   7756: If the number base is set to a value greater than 14 (for example,
                   7757: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   7758: it to be intepreted as either a single-precision integer or a
                   7759: floating-point number (Gforth treats it as an integer). The ambiguity
                   7760: can be resolved by explicitly stating the sign of the mantissa and/or
                   7761: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   7762: ambiguity arises; either representation will be treated as a
                   7763: floating-point number.
                   7764: @item
1.29      crook    7765: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    7766: It is used to specify file types.
                   7767: @item
1.72      anton    7768: ANS Forth requires the @code{.} of a double-precision number to be the
                   7769: final character in the string.  Gforth allows the @code{.} to be
                   7770: anywhere after the first digit.
1.26      crook    7771: @item
                   7772: The number conversion process does not check for overflow.
                   7773: @item
1.72      anton    7774: In an ANS Forth program @code{base} is required to be decimal when
                   7775: converting floating-point numbers.  In Gforth, number conversion to
                   7776: floating-point numbers always uses base &10, irrespective of the value
                   7777: of @code{base}.
1.26      crook    7778: @end itemize
1.1       anton    7779: 
1.49      anton    7780: You can read numbers into your programs with the words described in
                   7781: @ref{Input}.
1.1       anton    7782: 
1.82      anton    7783: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26      crook    7784: @subsection Interpret/Compile states
                   7785: @cindex Interpret/Compile states
1.1       anton    7786: 
1.29      crook    7787: A standard program is not permitted to change @code{state}
                   7788: explicitly. However, it can change @code{state} implicitly, using the
                   7789: words @code{[} and @code{]}. When @code{[} is executed it switches
                   7790: @code{state} to interpret state, and therefore the text interpreter
                   7791: starts interpreting. When @code{]} is executed it switches @code{state}
                   7792: to compile state and therefore the text interpreter starts
1.44      crook    7793: compiling. The most common usage for these words is for switching into
                   7794: interpret state and back from within a colon definition; this technique
1.49      anton    7795: can be used to compile a literal (for an example, @pxref{Literals}) or
                   7796: for conditional compilation (for an example, @pxref{Interpreter
                   7797: Directives}).
1.44      crook    7798: 
1.35      anton    7799: 
                   7800: @c This is a bad example: It's non-standard, and it's not necessary.
                   7801: @c However, I can't think of a good example for switching into compile
                   7802: @c state when there is no current word (@code{state}-smart words are not a
                   7803: @c good reason).  So maybe we should use an example for switching into
                   7804: @c interpret @code{state} in a colon def. - anton
1.44      crook    7805: @c nac-> I agree. I started out by putting in the example, then realised
                   7806: @c that it was non-ANS, so wrote more words around it. I hope this
                   7807: @c re-written version is acceptable to you. I do want to keep the example
                   7808: @c as it is helpful for showing what is and what is not portable, particularly
                   7809: @c where it outlaws a style in common use.
                   7810: 
1.72      anton    7811: @c anton: it's more important to show what's portable.  After we have done
1.83      anton    7812: @c that, we can also show what's not.  In any case, I have written a
                   7813: @c section Compiling Words which also deals with [ ].
1.35      anton    7814: 
1.95      anton    7815: @c  !! The following example does not work in Gforth 0.5.9 or later.
1.29      crook    7816: 
1.95      anton    7817: @c  @code{[} and @code{]} also give you the ability to switch into compile
                   7818: @c  state and back, but we cannot think of any useful Standard application
                   7819: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
                   7820: 
                   7821: @c  @example
                   7822: @c  : AA ." this is A" ;
                   7823: @c  : BB ." this is B" ;
                   7824: @c  : CC ." this is C" ;
                   7825: 
                   7826: @c  create table ] aa bb cc [
                   7827: 
                   7828: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   7829: @c    cells table + @@ execute ;
                   7830: @c  @end example
                   7831: 
                   7832: @c  This example builds a jump table; @code{0 go} will display ``@code{this
                   7833: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
                   7834: @c  defining @code{table} like this:
                   7835: 
                   7836: @c  @example
                   7837: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
                   7838: @c  @end example
                   7839: 
                   7840: @c  The problem with this code is that the definition of @code{table} is not
                   7841: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
                   7842: @c  @i{may} work on systems where code space and data space co-incide, the
                   7843: @c  Standard only allows data space to be assigned for a @code{CREATE}d
                   7844: @c  word. In addition, the Standard only allows @code{@@} to access data
                   7845: @c  space, whilst this example is using it to access code space. The only
                   7846: @c  portable, Standard way to build this table is to build it in data space,
                   7847: @c  like this:
                   7848: 
                   7849: @c  @example
                   7850: @c  create table ' aa , ' bb , ' cc ,
                   7851: @c  @end example
1.29      crook    7852: 
1.95      anton    7853: @c  doc-state
1.44      crook    7854: 
1.29      crook    7855: 
1.82      anton    7856: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
1.26      crook    7857: @subsection Interpreter Directives
                   7858: @cindex interpreter directives
1.72      anton    7859: @cindex conditional compilation
1.1       anton    7860: 
1.29      crook    7861: These words are usually used in interpret state; typically to control
                   7862: which parts of a source file are processed by the text
1.26      crook    7863: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   7864: supplements these with a rich set of immediate control structure words
                   7865: to compensate for the fact that the non-immediate versions can only be
1.29      crook    7866: used in compile state (@pxref{Control Structures}). Typical usages:
                   7867: 
                   7868: @example
1.72      anton    7869: FALSE Constant HAVE-ASSEMBLER
1.29      crook    7870: .
                   7871: .
1.72      anton    7872: HAVE-ASSEMBLER [IF]
1.29      crook    7873: : ASSEMBLER-FEATURE
                   7874:   ...
                   7875: ;
                   7876: [ENDIF]
                   7877: .
                   7878: .
                   7879: : SEE
                   7880:   ... \ general-purpose SEE code
1.72      anton    7881:   [ HAVE-ASSEMBLER [IF] ]
1.29      crook    7882:   ... \ assembler-specific SEE code
                   7883:   [ [ENDIF] ]
                   7884: ;
                   7885: @end example
1.1       anton    7886: 
1.44      crook    7887: 
1.26      crook    7888: doc-[IF]
                   7889: doc-[ELSE]
                   7890: doc-[THEN]
                   7891: doc-[ENDIF]
1.1       anton    7892: 
1.26      crook    7893: doc-[IFDEF]
                   7894: doc-[IFUNDEF]
1.1       anton    7895: 
1.26      crook    7896: doc-[?DO]
                   7897: doc-[DO]
                   7898: doc-[FOR]
                   7899: doc-[LOOP]
                   7900: doc-[+LOOP]
                   7901: doc-[NEXT]
1.1       anton    7902: 
1.26      crook    7903: doc-[BEGIN]
                   7904: doc-[UNTIL]
                   7905: doc-[AGAIN]
                   7906: doc-[WHILE]
                   7907: doc-[REPEAT]
1.1       anton    7908: 
1.27      crook    7909: 
1.26      crook    7910: @c -------------------------------------------------------------
1.111     anton    7911: @node The Input Stream, Word Lists, The Text Interpreter, Words
                   7912: @section The Input Stream
                   7913: @cindex input stream
                   7914: 
                   7915: @c !! integrate this better with the "Text Interpreter" section
                   7916: The text interpreter reads from the input stream, which can come from
                   7917: several sources (@pxref{Input Sources}).  Some words, in particular
                   7918: defining words, but also words like @code{'}, read parameters from the
                   7919: input stream instead of from the stack.
                   7920: 
                   7921: Such words are called parsing words, because they parse the input
                   7922: stream.  Parsing words are hard to use in other words, because it is
                   7923: hard to pass program-generated parameters through the input stream.
                   7924: They also usually have an unintuitive combination of interpretation and
                   7925: compilation semantics when implemented naively, leading to various
                   7926: approaches that try to produce a more intuitive behaviour
                   7927: (@pxref{Combined words}).
                   7928: 
                   7929: It should be obvious by now that parsing words are a bad idea.  If you
                   7930: want to implement a parsing word for convenience, also provide a factor
                   7931: of the word that does not parse, but takes the parameters on the stack.
                   7932: To implement the parsing word on top if it, you can use the following
                   7933: words:
                   7934: 
                   7935: @c anton: these belong in the input stream section
                   7936: doc-parse
1.138     anton    7937: doc-parse-name
1.111     anton    7938: doc-parse-word
                   7939: doc-name
                   7940: doc-word
                   7941: doc-\"-parse
                   7942: doc-refill
                   7943: 
                   7944: Conversely, if you have the bad luck (or lack of foresight) to have to
                   7945: deal with parsing words without having such factors, how do you pass a
                   7946: string that is not in the input stream to it?
                   7947: 
                   7948: doc-execute-parsing
                   7949: 
1.146     anton    7950: A definition of this word in ANS Forth is provided in
                   7951: @file{compat/execute-parsing.fs}.
                   7952: 
1.111     anton    7953: If you want to run a parsing word on a file, the following word should
                   7954: help:
                   7955: 
                   7956: doc-execute-parsing-file
                   7957: 
                   7958: @c -------------------------------------------------------------
                   7959: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26      crook    7960: @section Word Lists
                   7961: @cindex word lists
1.32      anton    7962: @cindex header space
1.1       anton    7963: 
1.36      anton    7964: A wordlist is a list of named words; you can add new words and look up
                   7965: words by name (and you can remove words in a restricted way with
                   7966: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
                   7967: 
                   7968: @cindex search order stack
                   7969: The text interpreter searches the wordlists present in the search order
                   7970: (a stack of wordlists), from the top to the bottom.  Within each
                   7971: wordlist, the search starts conceptually at the newest word; i.e., if
                   7972: two words in a wordlist have the same name, the newer word is found.
1.1       anton    7973: 
1.26      crook    7974: @cindex compilation word list
1.36      anton    7975: New words are added to the @dfn{compilation wordlist} (aka current
                   7976: wordlist).
1.1       anton    7977: 
1.36      anton    7978: @cindex wid
                   7979: A word list is identified by a cell-sized word list identifier (@i{wid})
                   7980: in much the same way as a file is identified by a file handle. The
                   7981: numerical value of the wid has no (portable) meaning, and might change
                   7982: from session to session.
1.1       anton    7983: 
1.29      crook    7984: The ANS Forth ``Search order'' word set is intended to provide a set of
                   7985: low-level tools that allow various different schemes to be
1.74      anton    7986: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26      crook    7987: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
1.45      crook    7988: Forth.
1.1       anton    7989: 
1.27      crook    7990: @comment TODO: locals section refers to here, saying that every word list (aka
                   7991: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78      anton    7992: @c anton: but better in a separate subsection on wordlist internals
1.1       anton    7993: 
1.45      crook    7994: @comment TODO: document markers, reveal, tables, mappedwordlist
                   7995: 
                   7996: @comment the gforthman- prefix is used to pick out the true definition of a
1.27      crook    7997: @comment word from the source files, rather than some alias.
1.44      crook    7998: 
1.26      crook    7999: doc-forth-wordlist
                   8000: doc-definitions
                   8001: doc-get-current
                   8002: doc-set-current
                   8003: doc-get-order
1.45      crook    8004: doc---gforthman-set-order
1.26      crook    8005: doc-wordlist
1.30      anton    8006: doc-table
1.79      anton    8007: doc->order
1.36      anton    8008: doc-previous
1.26      crook    8009: doc-also
1.45      crook    8010: doc---gforthman-forth
1.26      crook    8011: doc-only
1.45      crook    8012: doc---gforthman-order
1.15      anton    8013: 
1.26      crook    8014: doc-find
                   8015: doc-search-wordlist
1.15      anton    8016: 
1.26      crook    8017: doc-words
                   8018: doc-vlist
1.44      crook    8019: @c doc-words-deferred
1.1       anton    8020: 
1.74      anton    8021: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26      crook    8022: doc-root
                   8023: doc-vocabulary
                   8024: doc-seal
                   8025: doc-vocs
                   8026: doc-current
                   8027: doc-context
1.1       anton    8028: 
1.44      crook    8029: 
1.26      crook    8030: @menu
1.75      anton    8031: * Vocabularies::                
1.67      anton    8032: * Why use word lists?::         
1.75      anton    8033: * Word list example::           
1.26      crook    8034: @end menu
                   8035: 
1.75      anton    8036: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
                   8037: @subsection Vocabularies
                   8038: @cindex Vocabularies, detailed explanation
                   8039: 
                   8040: Here is an example of creating and using a new wordlist using ANS
                   8041: Forth words:
                   8042: 
                   8043: @example
                   8044: wordlist constant my-new-words-wordlist
                   8045: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
                   8046: 
                   8047: \ add it to the search order
                   8048: also my-new-words
                   8049: 
                   8050: \ alternatively, add it to the search order and make it
                   8051: \ the compilation word list
                   8052: also my-new-words definitions
                   8053: \ type "order" to see the problem
                   8054: @end example
                   8055: 
                   8056: The problem with this example is that @code{order} has no way to
                   8057: associate the name @code{my-new-words} with the wid of the word list (in
                   8058: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   8059: that has no associated name). There is no Standard way of associating a
                   8060: name with a wid.
                   8061: 
                   8062: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   8063: associates a name with a wid:
                   8064: 
                   8065: @example
                   8066: vocabulary my-new-words
                   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: my-new-words definitions
                   8074: \ type "order" to see that the problem is solved
                   8075: @end example
                   8076: 
                   8077: 
                   8078: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26      crook    8079: @subsection Why use word lists?
                   8080: @cindex word lists - why use them?
                   8081: 
1.74      anton    8082: Here are some reasons why people use wordlists:
1.26      crook    8083: 
                   8084: @itemize @bullet
1.74      anton    8085: 
                   8086: @c anton: Gforth's hashing implementation makes the search speed
                   8087: @c independent from the number of words.  But it is linear with the number
                   8088: @c of wordlists that have to be searched, so in effect using more wordlists
                   8089: @c actually slows down compilation.
                   8090: 
                   8091: @c @item
                   8092: @c To improve compilation speed by reducing the number of header space
                   8093: @c entries that must be searched. This is achieved by creating a new
                   8094: @c word list that contains all of the definitions that are used in the
                   8095: @c definition of a Forth system but which would not usually be used by
                   8096: @c programs running on that system. That word list would be on the search
                   8097: @c list when the Forth system was compiled but would be removed from the
                   8098: @c search list for normal operation. This can be a useful technique for
                   8099: @c low-performance systems (for example, 8-bit processors in embedded
                   8100: @c systems) but is unlikely to be necessary in high-performance desktop
                   8101: @c systems.
                   8102: 
1.26      crook    8103: @item
                   8104: To prevent a set of words from being used outside the context in which
                   8105: they are valid. Two classic examples of this are an integrated editor
                   8106: (all of the edit commands are defined in a separate word list; the
                   8107: search order is set to the editor word list when the editor is invoked;
                   8108: the old search order is restored when the editor is terminated) and an
                   8109: integrated assembler (the op-codes for the machine are defined in a
                   8110: separate word list which is used when a @code{CODE} word is defined).
1.74      anton    8111: 
                   8112: @item
                   8113: To organize the words of an application or library into a user-visible
                   8114: set (in @code{forth-wordlist} or some other common wordlist) and a set
                   8115: of helper words used just for the implementation (hidden in a separate
1.75      anton    8116: wordlist).  This keeps @code{words}' output smaller, separates
                   8117: implementation and interface, and reduces the chance of name conflicts
                   8118: within the common wordlist.
1.74      anton    8119: 
1.26      crook    8120: @item
                   8121: To prevent a name-space clash between multiple definitions with the same
                   8122: name. For example, when building a cross-compiler you might have a word
                   8123: @code{IF} that generates conditional code for your target system. By
                   8124: placing this definition in a different word list you can control whether
                   8125: the host system's @code{IF} or the target system's @code{IF} get used in
                   8126: any particular context by controlling the order of the word lists on the
                   8127: search order stack.
1.74      anton    8128: 
1.26      crook    8129: @end itemize
1.1       anton    8130: 
1.74      anton    8131: The downsides of using wordlists are:
                   8132: 
                   8133: @itemize
                   8134: 
                   8135: @item
                   8136: Debugging becomes more cumbersome.
                   8137: 
                   8138: @item
                   8139: Name conflicts worked around with wordlists are still there, and you
                   8140: have to arrange the search order carefully to get the desired results;
                   8141: if you forget to do that, you get hard-to-find errors (as in any case
                   8142: where you read the code differently from the compiler; @code{see} can
1.75      anton    8143: help seeing which of several possible words the name resolves to in such
                   8144: cases).  @code{See} displays just the name of the words, not what
                   8145: wordlist they belong to, so it might be misleading.  Using unique names
                   8146: is a better approach to avoid name conflicts.
1.74      anton    8147: 
                   8148: @item
                   8149: You have to explicitly undo any changes to the search order.  In many
                   8150: cases it would be more convenient if this happened implicitly.  Gforth
                   8151: currently does not provide such a feature, but it may do so in the
                   8152: future.
                   8153: @end itemize
                   8154: 
                   8155: 
1.75      anton    8156: @node Word list example,  , Why use word lists?, Word Lists
                   8157: @subsection Word list example
                   8158: @cindex word lists - example
1.1       anton    8159: 
1.74      anton    8160: The following example is from the
                   8161: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   8162: garbage collector} and uses wordlists to separate public words from
                   8163: helper words:
                   8164: 
                   8165: @example
                   8166: get-current ( wid )
                   8167: vocabulary garbage-collector also garbage-collector definitions
                   8168: ... \ define helper words
                   8169: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
                   8170: ... \ define the public (i.e., API) words
                   8171:     \ they can refer to the helper words
                   8172: previous \ restore original search order (helper words become invisible)
                   8173: @end example
                   8174: 
1.26      crook    8175: @c -------------------------------------------------------------
                   8176: @node Environmental Queries, Files, Word Lists, Words
                   8177: @section Environmental Queries
                   8178: @cindex environmental queries
1.21      crook    8179: 
1.26      crook    8180: ANS Forth introduced the idea of ``environmental queries'' as a way
                   8181: for a program running on a system to determine certain characteristics of the system.
                   8182: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    8183: 
1.32      anton    8184: The Standard requires that the header space used for environmental queries
                   8185: be distinct from the header space used for definitions.
1.21      crook    8186: 
1.26      crook    8187: Typically, environmental queries are supported by creating a set of
1.29      crook    8188: definitions in a word list that is @i{only} used during environmental
1.26      crook    8189: queries; that is what Gforth does. There is no Standard way of adding
                   8190: definitions to the set of recognised environmental queries, but any
                   8191: implementation that supports the loading of optional word sets must have
                   8192: some mechanism for doing this (after loading the word set, the
                   8193: associated environmental query string must return @code{true}). In
                   8194: Gforth, the word list used to honour environmental queries can be
                   8195: manipulated just like any other word list.
1.21      crook    8196: 
1.44      crook    8197: 
1.26      crook    8198: doc-environment?
                   8199: doc-environment-wordlist
1.21      crook    8200: 
1.26      crook    8201: doc-gforth
                   8202: doc-os-class
1.21      crook    8203: 
1.44      crook    8204: 
1.26      crook    8205: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   8206: returning two items on the stack, querying it using @code{environment?}
                   8207: will return an additional item; the @code{true} flag that shows that the
                   8208: string was recognised.
1.21      crook    8209: 
1.26      crook    8210: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    8211: 
1.26      crook    8212: Here are some examples of using environmental queries:
1.21      crook    8213: 
1.26      crook    8214: @example
                   8215: s" address-unit-bits" environment? 0=
                   8216: [IF]
                   8217:      cr .( environmental attribute address-units-bits unknown... ) cr
1.75      anton    8218: [ELSE]
                   8219:      drop \ ensure balanced stack effect
1.26      crook    8220: [THEN]
1.21      crook    8221: 
1.75      anton    8222: \ this might occur in the prelude of a standard program that uses THROW
                   8223: s" exception" environment? [IF]
                   8224:    0= [IF]
                   8225:       : throw abort" exception thrown" ;
                   8226:    [THEN]
                   8227: [ELSE] \ we don't know, so make sure
                   8228:    : throw abort" exception thrown" ;
                   8229: [THEN]
1.21      crook    8230: 
1.26      crook    8231: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   8232:                         [ELSE] .( Not Gforth..) [THEN]
1.75      anton    8233: 
                   8234: \ a program using v*
                   8235: s" gforth" environment? [IF]
                   8236:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
                   8237:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8238:      >r swap 2swap swap 0e r> 0 ?DO
                   8239:        dup f@ over + 2swap dup f@ f* f+ over + 2swap
                   8240:      LOOP
                   8241:      2drop 2drop ; 
                   8242:   [THEN]
                   8243: [ELSE] \ 
                   8244:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8245:   ...
                   8246: [THEN]
1.26      crook    8247: @end example
1.21      crook    8248: 
1.26      crook    8249: Here is an example of adding a definition to the environment word list:
1.21      crook    8250: 
1.26      crook    8251: @example
                   8252: get-current environment-wordlist set-current
                   8253: true constant block
                   8254: true constant block-ext
                   8255: set-current
                   8256: @end example
1.21      crook    8257: 
1.26      crook    8258: You can see what definitions are in the environment word list like this:
1.21      crook    8259: 
1.26      crook    8260: @example
1.79      anton    8261: environment-wordlist >order words previous
1.26      crook    8262: @end example
1.21      crook    8263: 
                   8264: 
1.26      crook    8265: @c -------------------------------------------------------------
                   8266: @node Files, Blocks, Environmental Queries, Words
                   8267: @section Files
1.28      crook    8268: @cindex files
                   8269: @cindex I/O - file-handling
1.21      crook    8270: 
1.26      crook    8271: Gforth provides facilities for accessing files that are stored in the
                   8272: host operating system's file-system. Files that are processed by Gforth
                   8273: can be divided into two categories:
1.21      crook    8274: 
1.23      crook    8275: @itemize @bullet
                   8276: @item
1.29      crook    8277: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    8278: @item
1.29      crook    8279: Files that are processed by some other program (@dfn{general files}).
1.26      crook    8280: @end itemize
                   8281: 
                   8282: @menu
1.48      anton    8283: * Forth source files::          
                   8284: * General files::               
1.167     anton    8285: * Redirection::                 
1.48      anton    8286: * Search Paths::                
1.26      crook    8287: @end menu
                   8288: 
                   8289: @c -------------------------------------------------------------
                   8290: @node Forth source files, General files, Files, Files
                   8291: @subsection Forth source files
                   8292: @cindex including files
                   8293: @cindex Forth source files
1.21      crook    8294: 
1.26      crook    8295: The simplest way to interpret the contents of a file is to use one of
                   8296: these two formats:
1.21      crook    8297: 
1.26      crook    8298: @example
                   8299: include mysource.fs
                   8300: s" mysource.fs" included
                   8301: @end example
1.21      crook    8302: 
1.75      anton    8303: You usually want to include a file only if it is not included already
1.26      crook    8304: (by, say, another source file). In that case, you can use one of these
1.45      crook    8305: three formats:
1.21      crook    8306: 
1.26      crook    8307: @example
                   8308: require mysource.fs
                   8309: needs mysource.fs
                   8310: s" mysource.fs" required
                   8311: @end example
1.21      crook    8312: 
1.26      crook    8313: @cindex stack effect of included files
                   8314: @cindex including files, stack effect
1.45      crook    8315: It is good practice to write your source files such that interpreting them
                   8316: does not change the stack. Source files designed in this way can be used with
1.26      crook    8317: @code{required} and friends without complications. For example:
1.21      crook    8318: 
1.26      crook    8319: @example
1.75      anton    8320: 1024 require foo.fs drop
1.26      crook    8321: @end example
1.21      crook    8322: 
1.75      anton    8323: Here you want to pass the argument 1024 (e.g., a buffer size) to
                   8324: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
                   8325: ), which allows its use with @code{require}.  Of course with such
                   8326: parameters to required files, you have to ensure that the first
                   8327: @code{require} fits for all uses (i.e., @code{require} it early in the
                   8328: master load file).
1.44      crook    8329: 
1.26      crook    8330: doc-include-file
                   8331: doc-included
1.28      crook    8332: doc-included?
1.26      crook    8333: doc-include
                   8334: doc-required
                   8335: doc-require
                   8336: doc-needs
1.75      anton    8337: @c doc-init-included-files @c internal
                   8338: doc-sourcefilename
                   8339: doc-sourceline#
1.44      crook    8340: 
1.26      crook    8341: A definition in ANS Forth for @code{required} is provided in
                   8342: @file{compat/required.fs}.
1.21      crook    8343: 
1.26      crook    8344: @c -------------------------------------------------------------
1.167     anton    8345: @node General files, Redirection, Forth source files, Files
1.26      crook    8346: @subsection General files
                   8347: @cindex general files
                   8348: @cindex file-handling
1.21      crook    8349: 
1.75      anton    8350: Files are opened/created by name and type. The following file access
                   8351: methods (FAMs) are recognised:
1.44      crook    8352: 
1.75      anton    8353: @cindex fam (file access method)
1.26      crook    8354: doc-r/o
                   8355: doc-r/w
                   8356: doc-w/o
                   8357: doc-bin
1.1       anton    8358: 
1.44      crook    8359: 
1.26      crook    8360: When a file is opened/created, it returns a file identifier,
1.29      crook    8361: @i{wfileid} that is used for all other file commands. All file
                   8362: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    8363: successful operation and an implementation-defined non-zero value in the
                   8364: case of an error.
1.21      crook    8365: 
1.44      crook    8366: 
1.26      crook    8367: doc-open-file
                   8368: doc-create-file
1.21      crook    8369: 
1.26      crook    8370: doc-close-file
                   8371: doc-delete-file
                   8372: doc-rename-file
                   8373: doc-read-file
                   8374: doc-read-line
1.154     anton    8375: doc-key-file
                   8376: doc-key?-file
1.26      crook    8377: doc-write-file
                   8378: doc-write-line
                   8379: doc-emit-file
                   8380: doc-flush-file
1.21      crook    8381: 
1.26      crook    8382: doc-file-status
                   8383: doc-file-position
                   8384: doc-reposition-file
                   8385: doc-file-size
                   8386: doc-resize-file
1.21      crook    8387: 
1.93      anton    8388: doc-slurp-file
                   8389: doc-slurp-fid
1.112     anton    8390: doc-stdin
                   8391: doc-stdout
                   8392: doc-stderr
1.44      crook    8393: 
1.26      crook    8394: @c ---------------------------------------------------------
1.167     anton    8395: @node Redirection, Search Paths, General files, Files
                   8396: @subsection Redirection
                   8397: @cindex Redirection
                   8398: @cindex Input Redirection
                   8399: @cindex Output Redirection
                   8400: 
                   8401: You can redirect the output of @code{type} and @code{emit} and all the
                   8402: words that use them (all output words that don't have an explicit
                   8403: target file) to an arbitrary file with the @code{>outfile
                   8404: ... outfile<} construct, used like this:
                   8405: 
                   8406: @example
                   8407: : print-some-warning ( n -- )
                   8408:   stderr >outfile cr ." warning# " . outfile< ;
                   8409: @end example
                   8410: 
                   8411: After the @code{outfile<}, the original output direction is restored;
                   8412: this construct is nestable and safe against exceptions.  Similarly,
                   8413: there is a construct @code{>infile ... infile<} for redirecting the
                   8414: input of @code{key} and its users (any input word that does not take a
                   8415: file explicitly).
                   8416: 
                   8417: If you do not want to redirect the input or output to a file, you can
                   8418: also make use of the fact that @code{key}, @code{emit} and @code{type}
                   8419: are deferred words (@pxref{Deferred Words}).  However, in that case
                   8420: you have to worry about the restoration and the protection against
                   8421: exceptions yourself; also, note that for redirecting the output in
                   8422: this way, you have to redirect both @code{emit} and @code{type}.
                   8423: 
                   8424: doc->outfile
                   8425: doc-outfile<
                   8426: doc->infile
                   8427: doc-infile<
                   8428: 
                   8429: @c ---------------------------------------------------------
                   8430: @node Search Paths,  , Redirection, Files
1.26      crook    8431: @subsection Search Paths
                   8432: @cindex path for @code{included}
                   8433: @cindex file search path
                   8434: @cindex @code{include} search path
                   8435: @cindex search path for files
1.21      crook    8436: 
1.26      crook    8437: If you specify an absolute filename (i.e., a filename starting with
                   8438: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   8439: @samp{C:...})) for @code{included} and friends, that file is included
                   8440: just as you would expect.
1.21      crook    8441: 
1.75      anton    8442: If the filename starts with @file{./}, this refers to the directory that
                   8443: the present file was @code{included} from.  This allows files to include
                   8444: other files relative to their own position (irrespective of the current
                   8445: working directory or the absolute position).  This feature is essential
                   8446: for libraries consisting of several files, where a file may include
                   8447: other files from the library.  It corresponds to @code{#include "..."}
                   8448: in C. If the current input source is not a file, @file{.} refers to the
                   8449: directory of the innermost file being included, or, if there is no file
                   8450: being included, to the current working directory.
                   8451: 
                   8452: For relative filenames (not starting with @file{./}), Gforth uses a
                   8453: search path similar to Forth's search order (@pxref{Word Lists}). It
                   8454: tries to find the given filename in the directories present in the path,
                   8455: and includes the first one it finds. There are separate search paths for
                   8456: Forth source files and general files.  If the search path contains the
                   8457: directory @file{.}, this refers to the directory of the current file, or
                   8458: the working directory, as if the file had been specified with @file{./}.
1.21      crook    8459: 
1.26      crook    8460: Use @file{~+} to refer to the current working directory (as in the
                   8461: @code{bash}).
1.1       anton    8462: 
1.75      anton    8463: @c anton: fold the following subsubsections into this subsection?
1.1       anton    8464: 
1.48      anton    8465: @menu
1.75      anton    8466: * Source Search Paths::         
1.48      anton    8467: * General Search Paths::        
                   8468: @end menu
                   8469: 
1.26      crook    8470: @c ---------------------------------------------------------
1.75      anton    8471: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
                   8472: @subsubsection Source Search Paths
                   8473: @cindex search path control, source files
1.5       anton    8474: 
1.26      crook    8475: The search path is initialized when you start Gforth (@pxref{Invoking
1.75      anton    8476: Gforth}). You can display it and change it using @code{fpath} in
                   8477: combination with the general path handling words.
1.5       anton    8478: 
1.75      anton    8479: doc-fpath
                   8480: @c the functionality of the following words is easily available through
                   8481: @c   fpath and the general path words.  The may go away.
                   8482: @c doc-.fpath
                   8483: @c doc-fpath+
                   8484: @c doc-fpath=
                   8485: @c doc-open-fpath-file
1.44      crook    8486: 
                   8487: @noindent
1.26      crook    8488: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    8489: 
1.26      crook    8490: @example
1.75      anton    8491: fpath path= /usr/lib/forth/|./
1.26      crook    8492: require timer.fs
                   8493: @end example
1.5       anton    8494: 
1.75      anton    8495: 
1.26      crook    8496: @c ---------------------------------------------------------
1.75      anton    8497: @node General Search Paths,  , Source Search Paths, Search Paths
1.26      crook    8498: @subsubsection General Search Paths
1.75      anton    8499: @cindex search path control, source files
1.5       anton    8500: 
1.26      crook    8501: Your application may need to search files in several directories, like
                   8502: @code{included} does. To facilitate this, Gforth allows you to define
                   8503: and use your own search paths, by providing generic equivalents of the
                   8504: Forth search path words:
1.5       anton    8505: 
1.75      anton    8506: doc-open-path-file
                   8507: doc-path-allot
                   8508: doc-clear-path
                   8509: doc-also-path
1.26      crook    8510: doc-.path
                   8511: doc-path+
                   8512: doc-path=
1.5       anton    8513: 
1.75      anton    8514: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44      crook    8515: 
1.75      anton    8516: Here's an example of creating an empty search path:
                   8517: @c
1.26      crook    8518: @example
1.75      anton    8519: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26      crook    8520: @end example
1.5       anton    8521: 
1.26      crook    8522: @c -------------------------------------------------------------
                   8523: @node Blocks, Other I/O, Files, Words
                   8524: @section Blocks
1.28      crook    8525: @cindex I/O - blocks
                   8526: @cindex blocks
                   8527: 
                   8528: When you run Gforth on a modern desk-top computer, it runs under the
                   8529: control of an operating system which provides certain services.  One of
                   8530: these services is @var{file services}, which allows Forth source code
                   8531: and data to be stored in files and read into Gforth (@pxref{Files}).
                   8532: 
                   8533: Traditionally, Forth has been an important programming language on
                   8534: systems where it has interfaced directly to the underlying hardware with
                   8535: no intervening operating system. Forth provides a mechanism, called
1.29      crook    8536: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    8537: 
                   8538: A block is a 1024-byte data area, which can be used to hold data or
                   8539: Forth source code. No structure is imposed on the contents of the
                   8540: block. A block is identified by its number; blocks are numbered
                   8541: contiguously from 1 to an implementation-defined maximum.
                   8542: 
                   8543: A typical system that used blocks but no operating system might use a
                   8544: single floppy-disk drive for mass storage, with the disks formatted to
                   8545: provide 256-byte sectors. Blocks would be implemented by assigning the
                   8546: first four sectors of the disk to block 1, the second four sectors to
                   8547: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   8548: would not contain any file system information, just the set of blocks.
                   8549: 
1.29      crook    8550: @cindex blocks file
1.28      crook    8551: On systems that do provide file services, blocks are typically
1.29      crook    8552: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    8553: file}.  The size of the blocks file will be an exact multiple of 1024
                   8554: bytes, corresponding to the number of blocks it contains. This is the
                   8555: mechanism that Gforth uses.
                   8556: 
1.29      crook    8557: @cindex @file{blocks.fb}
1.75      anton    8558: Only one blocks file can be open at a time. If you use block words without
1.28      crook    8559: having specified a blocks file, Gforth defaults to the blocks file
                   8560: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75      anton    8561: locate a blocks file (@pxref{Source Search Paths}).
1.28      crook    8562: 
1.29      crook    8563: @cindex block buffers
1.28      crook    8564: When you read and write blocks under program control, Gforth uses a
1.29      crook    8565: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    8566: not used when you use @code{load} to interpret the contents of a block.
                   8567: 
1.75      anton    8568: The behaviour of the block buffers is analagous to that of a cache.
                   8569: Each block buffer has three states:
1.28      crook    8570: 
                   8571: @itemize @bullet
                   8572: @item
                   8573: Unassigned
                   8574: @item
                   8575: Assigned-clean
                   8576: @item
                   8577: Assigned-dirty
                   8578: @end itemize
                   8579: 
1.29      crook    8580: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    8581: block, the block (specified by its block number) must be assigned to a
                   8582: block buffer.
                   8583: 
                   8584: The assignment of a block to a block buffer is performed by @code{block}
                   8585: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   8586: contents of a block. Use @code{buffer} when you don't care about the
                   8587: existing contents of the block@footnote{The ANS Forth definition of
1.35      anton    8588: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28      crook    8589: with the particular block is already stored in a block buffer due to an
                   8590: earlier @code{block} command, @code{buffer} will return that block
                   8591: buffer and the existing contents of the block will be
                   8592: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    8593: block buffer for the block.}.
1.28      crook    8594: 
1.47      crook    8595: Once a block has been assigned to a block buffer using @code{block} or
1.75      anton    8596: @code{buffer}, that block buffer becomes the @i{current block
                   8597: buffer}. Data may only be manipulated (read or written) within the
                   8598: current block buffer.
1.47      crook    8599: 
                   8600: When the contents of the current block buffer has been modified it is
1.48      anton    8601: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75      anton    8602: either abandon the changes (by doing nothing) or mark the block as
                   8603: changed (assigned-dirty), using @code{update}. Using @code{update} does
                   8604: not change the blocks file; it simply changes a block buffer's state to
                   8605: @i{assigned-dirty}.  The block will be written implicitly when it's
                   8606: buffer is needed for another block, or explicitly by @code{flush} or
                   8607: @code{save-buffers}.
                   8608: 
                   8609: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
                   8610: blocks file on disk. Leaving Gforth with @code{bye} also performs a
                   8611: @code{flush}.
1.28      crook    8612: 
1.29      crook    8613: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    8614: algorithm to assign a block buffer to a block. That means that any
                   8615: particular block can only be assigned to one specific block buffer,
1.29      crook    8616: called (for the particular operation) the @i{victim buffer}. If the
1.47      crook    8617: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
                   8618: the new block immediately. If it is @i{assigned-dirty} its current
                   8619: contents are written back to the blocks file on disk before it is
1.28      crook    8620: allocated to the new block.
                   8621: 
                   8622: Although no structure is imposed on the contents of a block, it is
                   8623: traditional to display the contents as 16 lines each of 64 characters.  A
                   8624: block provides a single, continuous stream of input (for example, it
                   8625: acts as a single parse area) -- there are no end-of-line characters
                   8626: within a block, and no end-of-file character at the end of a
                   8627: block. There are two consequences of this:
1.26      crook    8628: 
1.28      crook    8629: @itemize @bullet
                   8630: @item
                   8631: The last character of one line wraps straight into the first character
                   8632: of the following line
                   8633: @item
                   8634: The word @code{\} -- comment to end of line -- requires special
                   8635: treatment; in the context of a block it causes all characters until the
                   8636: end of the current 64-character ``line'' to be ignored.
                   8637: @end itemize
                   8638: 
                   8639: In Gforth, when you use @code{block} with a non-existent block number,
1.45      crook    8640: the current blocks file will be extended to the appropriate size and the
1.28      crook    8641: block buffer will be initialised with spaces.
                   8642: 
1.47      crook    8643: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
                   8644: for details) but doesn't encourage the use of blocks; the mechanism is
                   8645: only provided for backward compatibility -- ANS Forth requires blocks to
                   8646: be available when files are.
1.28      crook    8647: 
                   8648: Common techniques that are used when working with blocks include:
                   8649: 
                   8650: @itemize @bullet
                   8651: @item
                   8652: A screen editor that allows you to edit blocks without leaving the Forth
                   8653: environment.
                   8654: @item
                   8655: Shadow screens; where every code block has an associated block
                   8656: containing comments (for example: code in odd block numbers, comments in
                   8657: even block numbers). Typically, the block editor provides a convenient
                   8658: mechanism to toggle between code and comments.
                   8659: @item
                   8660: Load blocks; a single block (typically block 1) contains a number of
                   8661: @code{thru} commands which @code{load} the whole of the application.
                   8662: @end itemize
1.26      crook    8663: 
1.29      crook    8664: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   8665: integrated into a Forth programming environment.
1.26      crook    8666: 
                   8667: @comment TODO what about errors on open-blocks?
1.44      crook    8668: 
1.26      crook    8669: doc-open-blocks
                   8670: doc-use
1.75      anton    8671: doc-block-offset
1.26      crook    8672: doc-get-block-fid
                   8673: doc-block-position
1.28      crook    8674: 
1.75      anton    8675: doc-list
1.28      crook    8676: doc-scr
                   8677: 
1.45      crook    8678: doc---gforthman-block
1.28      crook    8679: doc-buffer
                   8680: 
1.75      anton    8681: doc-empty-buffers
                   8682: doc-empty-buffer
1.26      crook    8683: doc-update
1.28      crook    8684: doc-updated?
1.26      crook    8685: doc-save-buffers
1.75      anton    8686: doc-save-buffer
1.26      crook    8687: doc-flush
1.28      crook    8688: 
1.26      crook    8689: doc-load
                   8690: doc-thru
                   8691: doc-+load
                   8692: doc-+thru
1.45      crook    8693: doc---gforthman--->
1.26      crook    8694: doc-block-included
                   8695: 
1.44      crook    8696: 
1.26      crook    8697: @c -------------------------------------------------------------
1.126     pazsan   8698: @node Other I/O, OS command line arguments, Blocks, Words
1.26      crook    8699: @section Other I/O
1.28      crook    8700: @cindex I/O - keyboard and display
1.26      crook    8701: 
                   8702: @menu
                   8703: * Simple numeric output::       Predefined formats
                   8704: * Formatted numeric output::    Formatted (pictured) output
                   8705: * String Formats::              How Forth stores strings in memory
1.67      anton    8706: * Displaying characters and strings::  Other stuff
1.26      crook    8707: * Input::                       Input
1.112     anton    8708: * Pipes::                       How to create your own pipes
1.149     pazsan   8709: * Xchars and Unicode::          Non-ASCII characters
1.26      crook    8710: @end menu
                   8711: 
                   8712: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   8713: @subsection Simple numeric output
1.28      crook    8714: @cindex numeric output - simple/free-format
1.5       anton    8715: 
1.26      crook    8716: The simplest output functions are those that display numbers from the
                   8717: data or floating-point stacks. Floating-point output is always displayed
                   8718: using base 10. Numbers displayed from the data stack use the value stored
                   8719: in @code{base}.
1.5       anton    8720: 
1.44      crook    8721: 
1.26      crook    8722: doc-.
                   8723: doc-dec.
                   8724: doc-hex.
                   8725: doc-u.
                   8726: doc-.r
                   8727: doc-u.r
                   8728: doc-d.
                   8729: doc-ud.
                   8730: doc-d.r
                   8731: doc-ud.r
                   8732: doc-f.
                   8733: doc-fe.
                   8734: doc-fs.
1.111     anton    8735: doc-f.rdp
1.44      crook    8736: 
1.26      crook    8737: Examples of printing the number 1234.5678E23 in the different floating-point output
                   8738: formats are shown below:
1.5       anton    8739: 
                   8740: @example
1.26      crook    8741: f. 123456779999999000000000000.
                   8742: fe. 123.456779999999E24
                   8743: fs. 1.23456779999999E26
1.5       anton    8744: @end example
                   8745: 
                   8746: 
1.26      crook    8747: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   8748: @subsection Formatted numeric output
1.28      crook    8749: @cindex formatted numeric output
1.26      crook    8750: @cindex pictured numeric output
1.28      crook    8751: @cindex numeric output - formatted
1.26      crook    8752: 
1.29      crook    8753: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    8754: output} for formatted printing of integers.  In this technique, digits
                   8755: are extracted from the number (using the current output radix defined by
                   8756: @code{base}), converted to ASCII codes and appended to a string that is
                   8757: built in a scratch-pad area of memory (@pxref{core-idef,
                   8758: Implementation-defined options, Implementation-defined
                   8759: options}). Arbitrary characters can be appended to the string during the
                   8760: extraction process. The completed string is specified by an address
                   8761: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   8762: under program control.
1.5       anton    8763: 
1.75      anton    8764: All of the integer output words described in the previous section
                   8765: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
                   8766: numeric output.
1.5       anton    8767: 
1.47      crook    8768: Three important things to remember about pictured numeric output:
1.5       anton    8769: 
1.26      crook    8770: @itemize @bullet
                   8771: @item
1.28      crook    8772: It always operates on double-precision numbers; to display a
1.49      anton    8773: single-precision number, convert it first (for ways of doing this
                   8774: @pxref{Double precision}).
1.26      crook    8775: @item
1.28      crook    8776: It always treats the double-precision number as though it were
                   8777: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    8778: @item
                   8779: The string is built up from right to left; least significant digit first.
                   8780: @end itemize
1.5       anton    8781: 
1.44      crook    8782: 
1.26      crook    8783: doc-<#
1.47      crook    8784: doc-<<#
1.26      crook    8785: doc-#
                   8786: doc-#s
                   8787: doc-hold
                   8788: doc-sign
                   8789: doc-#>
1.47      crook    8790: doc-#>>
1.5       anton    8791: 
1.26      crook    8792: doc-represent
1.111     anton    8793: doc-f>str-rdp
                   8794: doc-f>buf-rdp
1.5       anton    8795: 
1.44      crook    8796: 
                   8797: @noindent
1.26      crook    8798: Here are some examples of using pictured numeric output:
1.5       anton    8799: 
                   8800: @example
1.26      crook    8801: : my-u. ( u -- )
                   8802:   \ Simplest use of pns.. behaves like Standard u. 
                   8803:   0              \ convert to unsigned double
1.75      anton    8804:   <<#            \ start conversion
1.26      crook    8805:   #s             \ convert all digits
                   8806:   #>             \ complete conversion
1.75      anton    8807:   TYPE SPACE     \ display, with trailing space
                   8808:   #>> ;          \ release hold area
1.5       anton    8809: 
1.26      crook    8810: : cents-only ( u -- )
                   8811:   0              \ convert to unsigned double
1.75      anton    8812:   <<#            \ start conversion
1.26      crook    8813:   # #            \ convert two least-significant digits
                   8814:   #>             \ complete conversion, discard other digits
1.75      anton    8815:   TYPE SPACE     \ display, with trailing space
                   8816:   #>> ;          \ release hold area
1.5       anton    8817: 
1.26      crook    8818: : dollars-and-cents ( u -- )
                   8819:   0              \ convert to unsigned double
1.75      anton    8820:   <<#            \ start conversion
1.26      crook    8821:   # #            \ convert two least-significant digits
                   8822:   [char] . hold  \ insert decimal point
                   8823:   #s             \ convert remaining digits
                   8824:   [char] $ hold  \ append currency symbol
                   8825:   #>             \ complete conversion
1.75      anton    8826:   TYPE SPACE     \ display, with trailing space
                   8827:   #>> ;          \ release hold area
1.5       anton    8828: 
1.26      crook    8829: : my-. ( n -- )
                   8830:   \ handling negatives.. behaves like Standard .
                   8831:   s>d            \ convert to signed double
                   8832:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    8833:   <<#            \ start conversion
1.26      crook    8834:   #s             \ convert all digits
                   8835:   rot sign       \ get at sign byte, append "-" if needed
                   8836:   #>             \ complete conversion
1.75      anton    8837:   TYPE SPACE     \ display, with trailing space
                   8838:   #>> ;          \ release hold area
1.5       anton    8839: 
1.26      crook    8840: : account. ( n -- )
1.75      anton    8841:   \ accountants don't like minus signs, they use parentheses
1.26      crook    8842:   \ for negative numbers
                   8843:   s>d            \ convert to signed double
                   8844:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    8845:   <<#            \ start conversion
1.26      crook    8846:   2 pick         \ get copy of sign byte
                   8847:   0< IF [char] ) hold THEN \ right-most character of output
                   8848:   #s             \ convert all digits
                   8849:   rot            \ get at sign byte
                   8850:   0< IF [char] ( hold THEN
                   8851:   #>             \ complete conversion
1.75      anton    8852:   TYPE SPACE     \ display, with trailing space
                   8853:   #>> ;          \ release hold area
                   8854: 
1.5       anton    8855: @end example
                   8856: 
1.26      crook    8857: Here are some examples of using these words:
1.5       anton    8858: 
                   8859: @example
1.26      crook    8860: 1 my-u. 1
                   8861: hex -1 my-u. decimal FFFFFFFF
                   8862: 1 cents-only 01
                   8863: 1234 cents-only 34
                   8864: 2 dollars-and-cents $0.02
                   8865: 1234 dollars-and-cents $12.34
                   8866: 123 my-. 123
                   8867: -123 my. -123
                   8868: 123 account. 123
                   8869: -456 account. (456)
1.5       anton    8870: @end example
                   8871: 
                   8872: 
1.26      crook    8873: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   8874: @subsection String Formats
1.27      crook    8875: @cindex strings - see character strings
                   8876: @cindex character strings - formats
1.28      crook    8877: @cindex I/O - see character strings
1.75      anton    8878: @cindex counted strings
                   8879: 
                   8880: @c anton: this does not really belong here; maybe the memory section,
                   8881: @c  or the principles chapter
1.26      crook    8882: 
1.27      crook    8883: Forth commonly uses two different methods for representing character
                   8884: strings:
1.26      crook    8885: 
                   8886: @itemize @bullet
                   8887: @item
                   8888: @cindex address of counted string
1.45      crook    8889: @cindex counted string
1.29      crook    8890: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   8891: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   8892: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    8893: memory.
                   8894: @item
1.29      crook    8895: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   8896: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    8897: first byte of the string.
                   8898: @end itemize
                   8899: 
                   8900: ANS Forth encourages the use of the second format when representing
1.75      anton    8901: strings.
1.26      crook    8902: 
1.44      crook    8903: 
1.26      crook    8904: doc-count
                   8905: 
1.44      crook    8906: 
1.49      anton    8907: For words that move, copy and search for strings see @ref{Memory
                   8908: Blocks}. For words that display characters and strings see
                   8909: @ref{Displaying characters and strings}.
1.26      crook    8910: 
                   8911: @node Displaying characters and strings, Input, String Formats, Other I/O
                   8912: @subsection Displaying characters and strings
1.27      crook    8913: @cindex characters - compiling and displaying
                   8914: @cindex character strings - compiling and displaying
1.26      crook    8915: 
                   8916: This section starts with a glossary of Forth words and ends with a set
                   8917: of examples.
                   8918: 
1.44      crook    8919: 
1.26      crook    8920: doc-bl
                   8921: doc-space
                   8922: doc-spaces
                   8923: doc-emit
                   8924: doc-toupper
                   8925: doc-."
                   8926: doc-.(
1.98      anton    8927: doc-.\"
1.26      crook    8928: doc-type
1.44      crook    8929: doc-typewhite
1.26      crook    8930: doc-cr
1.27      crook    8931: @cindex cursor control
1.26      crook    8932: doc-at-xy
                   8933: doc-page
                   8934: doc-s"
1.98      anton    8935: doc-s\"
1.26      crook    8936: doc-c"
                   8937: doc-char
                   8938: doc-[char]
                   8939: 
1.44      crook    8940: 
                   8941: @noindent
1.26      crook    8942: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    8943: 
                   8944: @example
1.26      crook    8945: .( text-1)
                   8946: : my-word
                   8947:   ." text-2" cr
                   8948:   .( text-3)
                   8949: ;
                   8950: 
                   8951: ." text-4"
                   8952: 
                   8953: : my-char
                   8954:   [char] ALPHABET emit
                   8955:   char emit
                   8956: ;
1.5       anton    8957: @end example
                   8958: 
1.26      crook    8959: When you load this code into Gforth, the following output is generated:
1.5       anton    8960: 
1.26      crook    8961: @example
1.30      anton    8962: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    8963: @end example
1.5       anton    8964: 
1.26      crook    8965: @itemize @bullet
                   8966: @item
                   8967: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   8968: is an immediate word; it behaves in the same way whether it is used inside
                   8969: or outside a colon definition.
                   8970: @item
                   8971: Message @code{text-4} is displayed because of Gforth's added interpretation
                   8972: semantics for @code{."}.
                   8973: @item
1.29      crook    8974: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    8975: performs the compilation semantics for @code{."} within the definition of
                   8976: @code{my-word}.
                   8977: @end itemize
1.5       anton    8978: 
1.26      crook    8979: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    8980: 
1.26      crook    8981: @example
1.30      anton    8982: @kbd{my-word @key{RET}} text-2
1.26      crook    8983:  ok
1.30      anton    8984: @kbd{my-char fred @key{RET}} Af ok
                   8985: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    8986: @end example
1.5       anton    8987: 
                   8988: @itemize @bullet
                   8989: @item
1.26      crook    8990: Message @code{text-2} is displayed because of the run-time behaviour of
                   8991: @code{."}.
                   8992: @item
                   8993: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   8994: on the stack at run-time. @code{emit} always displays the character
                   8995: when @code{my-char} is executed.
                   8996: @item
                   8997: @code{char} parses a string at run-time and the second @code{emit} displays
                   8998: the first character of the string.
1.5       anton    8999: @item
1.26      crook    9000: If you type @code{see my-char} you can see that @code{[char]} discarded
                   9001: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   9002: definition of @code{my-char}.
1.5       anton    9003: @end itemize
                   9004: 
                   9005: 
                   9006: 
1.112     anton    9007: @node Input, Pipes, Displaying characters and strings, Other I/O
1.26      crook    9008: @subsection Input
                   9009: @cindex input
1.28      crook    9010: @cindex I/O - see input
                   9011: @cindex parsing a string
1.5       anton    9012: 
1.49      anton    9013: For ways of storing character strings in memory see @ref{String Formats}.
1.5       anton    9014: 
1.27      crook    9015: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29      crook    9016: @comment then index them
1.27      crook    9017: 
1.44      crook    9018: 
1.27      crook    9019: doc-key
                   9020: doc-key?
1.45      crook    9021: doc-ekey
1.141     anton    9022: doc-ekey>char
1.45      crook    9023: doc-ekey?
1.141     anton    9024: 
                   9025: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
                   9026: you need the ANSI.SYS driver to get that behaviour).  These are the
                   9027: keyboard events produced by various common keys:
                   9028: 
                   9029: doc-k-left
                   9030: doc-k-right
                   9031: doc-k-up       
                   9032: doc-k-down     
                   9033: doc-k-home     
                   9034: doc-k-end      
                   9035: doc-k-prior
                   9036: doc-k-next
                   9037: doc-k-insert
                   9038: doc-k-delete
                   9039: 
                   9040: The function keys (aka keypad keys) are:
                   9041: 
                   9042: doc-k1
                   9043: doc-k2
                   9044: doc-k3
                   9045: doc-k4
                   9046: doc-k5
                   9047: doc-k6
                   9048: doc-k7
                   9049: doc-k8
                   9050: doc-k9
                   9051: doc-k10
                   9052: doc-k11
                   9053: doc-k12
                   9054: 
                   9055: Note that K11 and K12 are not as widely available.  The shifted
                   9056: function keys are also not very widely available:
                   9057: 
                   9058: doc-s-k1
                   9059: doc-s-k2
                   9060: doc-s-k3
                   9061: doc-s-k4
                   9062: doc-s-k5
                   9063: doc-s-k6
                   9064: doc-s-k7
                   9065: doc-s-k8
                   9066: doc-s-k9
                   9067: doc-s-k10
                   9068: doc-s-k11
                   9069: doc-s-k12
                   9070: 
                   9071: Words for inputting one line from the keyboard:
                   9072: 
                   9073: doc-accept
                   9074: doc-edit-line
                   9075: 
                   9076: Conversion words:
                   9077: 
1.143     anton    9078: doc-s>number?
                   9079: doc-s>unumber?
1.26      crook    9080: doc->number
                   9081: doc->float
1.143     anton    9082: 
1.141     anton    9083: 
1.27      crook    9084: @comment obsolescent words..
1.141     anton    9085: Obsolescent input and conversion words:
                   9086: 
1.27      crook    9087: doc-convert
1.26      crook    9088: doc-expect
1.27      crook    9089: doc-span
1.5       anton    9090: 
                   9091: 
1.149     pazsan   9092: @node Pipes, Xchars and Unicode, Input, Other I/O
1.112     anton    9093: @subsection Pipes
                   9094: @cindex pipes, creating your own
                   9095: 
                   9096: In addition to using Gforth in pipes created by other processes
                   9097: (@pxref{Gforth in pipes}), you can create your own pipe with
                   9098: @code{open-pipe}, and read from or write to it.
                   9099: 
                   9100: doc-open-pipe
                   9101: doc-close-pipe
                   9102: 
                   9103: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
                   9104: you don't catch this exception, Gforth will catch it and exit, usually
                   9105: silently (@pxref{Gforth in pipes}).  Since you probably do not want
                   9106: this, you should wrap a @code{catch} or @code{try} block around the code
                   9107: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
                   9108: problem yourself, and then return to regular processing.
                   9109: 
                   9110: doc-broken-pipe-error
                   9111: 
1.155     anton    9112: @node Xchars and Unicode,  , Pipes, Other I/O
                   9113: @subsection Xchars and Unicode
1.149     pazsan   9114: 
                   9115: This chapter needs completion
1.112     anton    9116: 
1.121     anton    9117: @node OS command line arguments, Locals, Other I/O, Words
                   9118: @section OS command line arguments
                   9119: @cindex OS command line arguments
                   9120: @cindex command line arguments, OS
                   9121: @cindex arguments, OS command line
                   9122: 
                   9123: The usual way to pass arguments to Gforth programs on the command line
                   9124: is via the @option{-e} option, e.g.
                   9125: 
                   9126: @example
                   9127: gforth -e "123 456" foo.fs -e bye
                   9128: @end example
                   9129: 
                   9130: However, you may want to interpret the command-line arguments directly.
                   9131: In that case, you can access the (image-specific) command-line arguments
1.123     anton    9132: through @code{next-arg}:
1.121     anton    9133: 
1.123     anton    9134: doc-next-arg
1.121     anton    9135: 
1.123     anton    9136: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121     anton    9137: 
                   9138: @example
                   9139: : echo ( -- )
1.122     anton    9140:     begin
1.123     anton    9141:        next-arg 2dup 0 0 d<> while
                   9142:            type space
                   9143:     repeat
                   9144:     2drop ;
1.121     anton    9145: 
                   9146: echo cr bye
                   9147: @end example
                   9148: 
                   9149: This can be invoked with
                   9150: 
                   9151: @example
                   9152: gforth echo.fs hello world
                   9153: @end example
1.123     anton    9154: 
                   9155: and it will print
                   9156: 
                   9157: @example
                   9158: hello world
                   9159: @end example
                   9160: 
                   9161: The next lower level of dealing with the OS command line are the
                   9162: following words:
                   9163: 
                   9164: doc-arg
                   9165: doc-shift-args
                   9166: 
                   9167: Finally, at the lowest level Gforth provides the following words:
                   9168: 
                   9169: doc-argc
                   9170: doc-argv
1.121     anton    9171: 
1.78      anton    9172: @c -------------------------------------------------------------
1.126     pazsan   9173: @node Locals, Structures, OS command line arguments, Words
1.78      anton    9174: @section Locals
                   9175: @cindex locals
                   9176: 
                   9177: Local variables can make Forth programming more enjoyable and Forth
                   9178: programs easier to read. Unfortunately, the locals of ANS Forth are
                   9179: laden with restrictions. Therefore, we provide not only the ANS Forth
                   9180: locals wordset, but also our own, more powerful locals wordset (we
                   9181: implemented the ANS Forth locals wordset through our locals wordset).
1.44      crook    9182: 
1.78      anton    9183: The ideas in this section have also been published in M. Anton Ertl,
                   9184: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
                   9185: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12      anton    9186: 
                   9187: @menu
1.78      anton    9188: * Gforth locals::               
                   9189: * ANS Forth locals::            
1.5       anton    9190: @end menu
                   9191: 
1.78      anton    9192: @node Gforth locals, ANS Forth locals, Locals, Locals
                   9193: @subsection Gforth locals
                   9194: @cindex Gforth locals
                   9195: @cindex locals, Gforth style
1.5       anton    9196: 
1.78      anton    9197: Locals can be defined with
1.44      crook    9198: 
1.78      anton    9199: @example
                   9200: @{ local1 local2 ... -- comment @}
                   9201: @end example
                   9202: or
                   9203: @example
                   9204: @{ local1 local2 ... @}
                   9205: @end example
1.5       anton    9206: 
1.78      anton    9207: E.g.,
                   9208: @example
                   9209: : max @{ n1 n2 -- n3 @}
                   9210:  n1 n2 > if
                   9211:    n1
                   9212:  else
                   9213:    n2
                   9214:  endif ;
                   9215: @end example
1.44      crook    9216: 
1.78      anton    9217: The similarity of locals definitions with stack comments is intended. A
                   9218: locals definition often replaces the stack comment of a word. The order
                   9219: of the locals corresponds to the order in a stack comment and everything
                   9220: after the @code{--} is really a comment.
1.77      anton    9221: 
1.78      anton    9222: This similarity has one disadvantage: It is too easy to confuse locals
                   9223: declarations with stack comments, causing bugs and making them hard to
                   9224: find. However, this problem can be avoided by appropriate coding
                   9225: conventions: Do not use both notations in the same program. If you do,
                   9226: they should be distinguished using additional means, e.g. by position.
1.77      anton    9227: 
1.78      anton    9228: @cindex types of locals
                   9229: @cindex locals types
                   9230: The name of the local may be preceded by a type specifier, e.g.,
                   9231: @code{F:} for a floating point value:
1.5       anton    9232: 
1.78      anton    9233: @example
                   9234: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   9235: \ complex multiplication
                   9236:  Ar Br f* Ai Bi f* f-
                   9237:  Ar Bi f* Ai Br f* f+ ;
                   9238: @end example
1.44      crook    9239: 
1.78      anton    9240: @cindex flavours of locals
                   9241: @cindex locals flavours
                   9242: @cindex value-flavoured locals
                   9243: @cindex variable-flavoured locals
                   9244: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   9245: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   9246: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   9247: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   9248: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   9249: produces its address (which becomes invalid when the variable's scope is
                   9250: left). E.g., the standard word @code{emit} can be defined in terms of
                   9251: @code{type} like this:
1.5       anton    9252: 
1.78      anton    9253: @example
                   9254: : emit @{ C^ char* -- @}
                   9255:     char* 1 type ;
                   9256: @end example
1.5       anton    9257: 
1.78      anton    9258: @cindex default type of locals
                   9259: @cindex locals, default type
                   9260: A local without type specifier is a @code{W:} local. Both flavours of
                   9261: locals are initialized with values from the data or FP stack.
1.44      crook    9262: 
1.78      anton    9263: Currently there is no way to define locals with user-defined data
                   9264: structures, but we are working on it.
1.5       anton    9265: 
1.78      anton    9266: Gforth allows defining locals everywhere in a colon definition. This
                   9267: poses the following questions:
1.5       anton    9268: 
1.78      anton    9269: @menu
                   9270: * Where are locals visible by name?::  
                   9271: * How long do locals live?::    
                   9272: * Locals programming style::    
                   9273: * Locals implementation::       
                   9274: @end menu
1.44      crook    9275: 
1.78      anton    9276: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   9277: @subsubsection Where are locals visible by name?
                   9278: @cindex locals visibility
                   9279: @cindex visibility of locals
                   9280: @cindex scope of locals
1.5       anton    9281: 
1.78      anton    9282: Basically, the answer is that locals are visible where you would expect
                   9283: it in block-structured languages, and sometimes a little longer. If you
                   9284: want to restrict the scope of a local, enclose its definition in
                   9285: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    9286: 
                   9287: 
1.78      anton    9288: doc-scope
                   9289: doc-endscope
1.5       anton    9290: 
                   9291: 
1.78      anton    9292: These words behave like control structure words, so you can use them
                   9293: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   9294: arbitrary ways.
1.77      anton    9295: 
1.78      anton    9296: If you want a more exact answer to the visibility question, here's the
                   9297: basic principle: A local is visible in all places that can only be
                   9298: reached through the definition of the local@footnote{In compiler
                   9299: construction terminology, all places dominated by the definition of the
                   9300: local.}. In other words, it is not visible in places that can be reached
                   9301: without going through the definition of the local. E.g., locals defined
                   9302: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   9303: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   9304: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77      anton    9305: 
1.78      anton    9306: The reasoning behind this solution is: We want to have the locals
                   9307: visible as long as it is meaningful. The user can always make the
                   9308: visibility shorter by using explicit scoping. In a place that can
                   9309: only be reached through the definition of a local, the meaning of a
                   9310: local name is clear. In other places it is not: How is the local
                   9311: initialized at the control flow path that does not contain the
                   9312: definition? Which local is meant, if the same name is defined twice in
                   9313: two independent control flow paths?
1.77      anton    9314: 
1.78      anton    9315: This should be enough detail for nearly all users, so you can skip the
                   9316: rest of this section. If you really must know all the gory details and
                   9317: options, read on.
1.77      anton    9318: 
1.78      anton    9319: In order to implement this rule, the compiler has to know which places
                   9320: are unreachable. It knows this automatically after @code{AHEAD},
                   9321: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   9322: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   9323: compiler that the control flow never reaches that place. If
                   9324: @code{UNREACHABLE} is not used where it could, the only consequence is
                   9325: that the visibility of some locals is more limited than the rule above
                   9326: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   9327: lie to the compiler), buggy code will be produced.
1.77      anton    9328: 
1.5       anton    9329: 
1.78      anton    9330: doc-unreachable
1.5       anton    9331: 
1.23      crook    9332: 
1.78      anton    9333: Another problem with this rule is that at @code{BEGIN}, the compiler
                   9334: does not know which locals will be visible on the incoming
                   9335: back-edge. All problems discussed in the following are due to this
                   9336: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   9337: loops as examples; the discussion also applies to @code{?DO} and other
                   9338: loops). Perhaps the most insidious example is:
1.26      crook    9339: @example
1.78      anton    9340: AHEAD
                   9341: BEGIN
                   9342:   x
                   9343: [ 1 CS-ROLL ] THEN
                   9344:   @{ x @}
                   9345:   ...
                   9346: UNTIL
1.26      crook    9347: @end example
1.23      crook    9348: 
1.78      anton    9349: This should be legal according to the visibility rule. The use of
                   9350: @code{x} can only be reached through the definition; but that appears
                   9351: textually below the use.
                   9352: 
                   9353: From this example it is clear that the visibility rules cannot be fully
                   9354: implemented without major headaches. Our implementation treats common
                   9355: cases as advertised and the exceptions are treated in a safe way: The
                   9356: compiler makes a reasonable guess about the locals visible after a
                   9357: @code{BEGIN}; if it is too pessimistic, the
                   9358: user will get a spurious error about the local not being defined; if the
                   9359: compiler is too optimistic, it will notice this later and issue a
                   9360: warning. In the case above the compiler would complain about @code{x}
                   9361: being undefined at its use. You can see from the obscure examples in
                   9362: this section that it takes quite unusual control structures to get the
                   9363: compiler into trouble, and even then it will often do fine.
1.23      crook    9364: 
1.78      anton    9365: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   9366: is that all locals visible before the @code{BEGIN} will also be
                   9367: visible after the @code{BEGIN}. This guess is valid for all loops that
                   9368: are entered only through the @code{BEGIN}, in particular, for normal
                   9369: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   9370: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   9371: compiler. When the branch to the @code{BEGIN} is finally generated by
                   9372: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   9373: warns the user if it was too optimistic:
1.26      crook    9374: @example
1.78      anton    9375: IF
                   9376:   @{ x @}
                   9377: BEGIN
                   9378:   \ x ? 
                   9379: [ 1 cs-roll ] THEN
                   9380:   ...
                   9381: UNTIL
1.26      crook    9382: @end example
1.23      crook    9383: 
1.78      anton    9384: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   9385: optimistically assumes that it lives until the @code{THEN}. It notices
                   9386: this difference when it compiles the @code{UNTIL} and issues a
                   9387: warning. The user can avoid the warning, and make sure that @code{x}
                   9388: is not used in the wrong area by using explicit scoping:
                   9389: @example
                   9390: IF
                   9391:   SCOPE
                   9392:   @{ x @}
                   9393:   ENDSCOPE
                   9394: BEGIN
                   9395: [ 1 cs-roll ] THEN
                   9396:   ...
                   9397: UNTIL
                   9398: @end example
1.23      crook    9399: 
1.78      anton    9400: Since the guess is optimistic, there will be no spurious error messages
                   9401: about undefined locals.
1.44      crook    9402: 
1.78      anton    9403: If the @code{BEGIN} is not reachable from above (e.g., after
                   9404: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   9405: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   9406: defined later. Therefore, the compiler assumes that no locals are
                   9407: visible after the @code{BEGIN}. However, the user can use
                   9408: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   9409: visible at the BEGIN as at the point where the top control-flow stack
                   9410: item was created.
1.23      crook    9411: 
1.44      crook    9412: 
1.78      anton    9413: doc-assume-live
1.26      crook    9414: 
1.23      crook    9415: 
1.78      anton    9416: @noindent
                   9417: E.g.,
                   9418: @example
                   9419: @{ x @}
                   9420: AHEAD
                   9421: ASSUME-LIVE
                   9422: BEGIN
                   9423:   x
                   9424: [ 1 CS-ROLL ] THEN
                   9425:   ...
                   9426: UNTIL
                   9427: @end example
1.44      crook    9428: 
1.78      anton    9429: Other cases where the locals are defined before the @code{BEGIN} can be
                   9430: handled by inserting an appropriate @code{CS-ROLL} before the
                   9431: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   9432: behind the @code{ASSUME-LIVE}).
1.23      crook    9433: 
1.78      anton    9434: Cases where locals are defined after the @code{BEGIN} (but should be
                   9435: visible immediately after the @code{BEGIN}) can only be handled by
                   9436: rearranging the loop. E.g., the ``most insidious'' example above can be
                   9437: arranged into:
                   9438: @example
                   9439: BEGIN
                   9440:   @{ x @}
                   9441:   ... 0=
                   9442: WHILE
                   9443:   x
                   9444: REPEAT
                   9445: @end example
1.44      crook    9446: 
1.78      anton    9447: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
                   9448: @subsubsection How long do locals live?
                   9449: @cindex locals lifetime
                   9450: @cindex lifetime of locals
1.23      crook    9451: 
1.78      anton    9452: The right answer for the lifetime question would be: A local lives at
                   9453: least as long as it can be accessed. For a value-flavoured local this
                   9454: means: until the end of its visibility. However, a variable-flavoured
                   9455: local could be accessed through its address far beyond its visibility
                   9456: scope. Ultimately, this would mean that such locals would have to be
                   9457: garbage collected. Since this entails un-Forth-like implementation
                   9458: complexities, I adopted the same cowardly solution as some other
                   9459: languages (e.g., C): The local lives only as long as it is visible;
                   9460: afterwards its address is invalid (and programs that access it
                   9461: afterwards are erroneous).
1.23      crook    9462: 
1.78      anton    9463: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
                   9464: @subsubsection Locals programming style
                   9465: @cindex locals programming style
                   9466: @cindex programming style, locals
1.23      crook    9467: 
1.78      anton    9468: The freedom to define locals anywhere has the potential to change
                   9469: programming styles dramatically. In particular, the need to use the
                   9470: return stack for intermediate storage vanishes. Moreover, all stack
                   9471: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   9472: determined arguments) can be eliminated: If the stack items are in the
                   9473: wrong order, just write a locals definition for all of them; then
                   9474: write the items in the order you want.
1.23      crook    9475: 
1.78      anton    9476: This seems a little far-fetched and eliminating stack manipulations is
                   9477: unlikely to become a conscious programming objective. Still, the number
                   9478: of stack manipulations will be reduced dramatically if local variables
                   9479: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
                   9480: a traditional implementation of @code{max}).
1.23      crook    9481: 
1.78      anton    9482: This shows one potential benefit of locals: making Forth programs more
                   9483: readable. Of course, this benefit will only be realized if the
                   9484: programmers continue to honour the principle of factoring instead of
                   9485: using the added latitude to make the words longer.
1.23      crook    9486: 
1.78      anton    9487: @cindex single-assignment style for locals
                   9488: Using @code{TO} can and should be avoided.  Without @code{TO},
                   9489: every value-flavoured local has only a single assignment and many
                   9490: advantages of functional languages apply to Forth. I.e., programs are
                   9491: easier to analyse, to optimize and to read: It is clear from the
                   9492: definition what the local stands for, it does not turn into something
                   9493: different later.
1.23      crook    9494: 
1.78      anton    9495: E.g., a definition using @code{TO} might look like this:
                   9496: @example
                   9497: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9498:  u1 u2 min 0
                   9499:  ?do
                   9500:    addr1 c@@ addr2 c@@ -
                   9501:    ?dup-if
                   9502:      unloop exit
                   9503:    then
                   9504:    addr1 char+ TO addr1
                   9505:    addr2 char+ TO addr2
                   9506:  loop
                   9507:  u1 u2 - ;
1.26      crook    9508: @end example
1.78      anton    9509: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   9510: every loop iteration. @code{strcmp} is a typical example of the
                   9511: readability problems of using @code{TO}. When you start reading
                   9512: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   9513: string. Only near the end of the loop you realize that it is something
                   9514: else.
1.23      crook    9515: 
1.78      anton    9516: This can be avoided by defining two locals at the start of the loop that
                   9517: are initialized with the right value for the current iteration.
                   9518: @example
                   9519: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9520:  addr1 addr2
                   9521:  u1 u2 min 0 
                   9522:  ?do @{ s1 s2 @}
                   9523:    s1 c@@ s2 c@@ -
                   9524:    ?dup-if
                   9525:      unloop exit
                   9526:    then
                   9527:    s1 char+ s2 char+
                   9528:  loop
                   9529:  2drop
                   9530:  u1 u2 - ;
                   9531: @end example
                   9532: Here it is clear from the start that @code{s1} has a different value
                   9533: in every loop iteration.
1.23      crook    9534: 
1.78      anton    9535: @node Locals implementation,  , Locals programming style, Gforth locals
                   9536: @subsubsection Locals implementation
                   9537: @cindex locals implementation
                   9538: @cindex implementation of locals
1.23      crook    9539: 
1.78      anton    9540: @cindex locals stack
                   9541: Gforth uses an extra locals stack. The most compelling reason for
                   9542: this is that the return stack is not float-aligned; using an extra stack
                   9543: also eliminates the problems and restrictions of using the return stack
                   9544: as locals stack. Like the other stacks, the locals stack grows toward
                   9545: lower addresses. A few primitives allow an efficient implementation:
                   9546: 
                   9547: 
                   9548: doc-@local#
                   9549: doc-f@local#
                   9550: doc-laddr#
                   9551: doc-lp+!#
                   9552: doc-lp!
                   9553: doc->l
                   9554: doc-f>l
                   9555: 
                   9556: 
                   9557: In addition to these primitives, some specializations of these
                   9558: primitives for commonly occurring inline arguments are provided for
                   9559: efficiency reasons, e.g., @code{@@local0} as specialization of
                   9560: @code{@@local#} for the inline argument 0. The following compiling words
                   9561: compile the right specialized version, or the general version, as
                   9562: appropriate:
1.23      crook    9563: 
1.5       anton    9564: 
1.107     dvdkhlng 9565: @c doc-compile-@local
                   9566: @c doc-compile-f@local
1.78      anton    9567: doc-compile-lp+!
1.5       anton    9568: 
                   9569: 
1.78      anton    9570: Combinations of conditional branches and @code{lp+!#} like
                   9571: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   9572: is taken) are provided for efficiency and correctness in loops.
1.5       anton    9573: 
1.78      anton    9574: A special area in the dictionary space is reserved for keeping the
                   9575: local variable names. @code{@{} switches the dictionary pointer to this
                   9576: area and @code{@}} switches it back and generates the locals
                   9577: initializing code. @code{W:} etc.@ are normal defining words. This
                   9578: special area is cleared at the start of every colon definition.
1.5       anton    9579: 
1.78      anton    9580: @cindex word list for defining locals
                   9581: A special feature of Gforth's dictionary is used to implement the
                   9582: definition of locals without type specifiers: every word list (aka
                   9583: vocabulary) has its own methods for searching
                   9584: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   9585: with a special search method: When it is searched for a word, it
                   9586: actually creates that word using @code{W:}. @code{@{} changes the search
                   9587: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   9588: and then the word list for defining locals without type specifiers.
1.5       anton    9589: 
1.78      anton    9590: The lifetime rules support a stack discipline within a colon
                   9591: definition: The lifetime of a local is either nested with other locals
                   9592: lifetimes or it does not overlap them.
1.23      crook    9593: 
1.78      anton    9594: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   9595: pointer manipulation is generated. Between control structure words
                   9596: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   9597: is the simplest of the other three control flow words. It has to
                   9598: restore the locals stack depth of the corresponding @code{BEGIN}
                   9599: before branching. The code looks like this:
                   9600: @format
                   9601: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   9602: @code{branch} <begin>
                   9603: @end format
1.26      crook    9604: 
1.78      anton    9605: @code{UNTIL} is a little more complicated: If it branches back, it
                   9606: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   9607: the locals stack must not be changed. The compiler generates the
                   9608: following code:
                   9609: @format
                   9610: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   9611: @end format
                   9612: The locals stack pointer is only adjusted if the branch is taken.
1.44      crook    9613: 
1.78      anton    9614: @code{THEN} can produce somewhat inefficient code:
                   9615: @format
                   9616: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   9617: <orig target>:
                   9618: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   9619: @end format
                   9620: The second @code{lp+!#} adjusts the locals stack pointer from the
                   9621: level at the @i{orig} point to the level after the @code{THEN}. The
                   9622: first @code{lp+!#} adjusts the locals stack pointer from the current
                   9623: level to the level at the orig point, so the complete effect is an
                   9624: adjustment from the current level to the right level after the
                   9625: @code{THEN}.
1.26      crook    9626: 
1.78      anton    9627: @cindex locals information on the control-flow stack
                   9628: @cindex control-flow stack items, locals information
                   9629: In a conventional Forth implementation a dest control-flow stack entry
                   9630: is just the target address and an orig entry is just the address to be
                   9631: patched. Our locals implementation adds a word list to every orig or dest
                   9632: item. It is the list of locals visible (or assumed visible) at the point
                   9633: described by the entry. Our implementation also adds a tag to identify
                   9634: the kind of entry, in particular to differentiate between live and dead
                   9635: (reachable and unreachable) orig entries.
1.26      crook    9636: 
1.78      anton    9637: A few unusual operations have to be performed on locals word lists:
1.44      crook    9638: 
1.5       anton    9639: 
1.78      anton    9640: doc-common-list
                   9641: doc-sub-list?
                   9642: doc-list-size
1.52      anton    9643: 
                   9644: 
1.78      anton    9645: Several features of our locals word list implementation make these
                   9646: operations easy to implement: The locals word lists are organised as
                   9647: linked lists; the tails of these lists are shared, if the lists
                   9648: contain some of the same locals; and the address of a name is greater
                   9649: than the address of the names behind it in the list.
1.5       anton    9650: 
1.78      anton    9651: Another important implementation detail is the variable
                   9652: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   9653: determine if they can be reached directly or only through the branch
                   9654: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   9655: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   9656: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5       anton    9657: 
1.78      anton    9658: Counted loops are similar to other loops in most respects, but
                   9659: @code{LEAVE} requires special attention: It performs basically the same
                   9660: service as @code{AHEAD}, but it does not create a control-flow stack
                   9661: entry. Therefore the information has to be stored elsewhere;
                   9662: traditionally, the information was stored in the target fields of the
                   9663: branches created by the @code{LEAVE}s, by organizing these fields into a
                   9664: linked list. Unfortunately, this clever trick does not provide enough
                   9665: space for storing our extended control flow information. Therefore, we
                   9666: introduce another stack, the leave stack. It contains the control-flow
                   9667: stack entries for all unresolved @code{LEAVE}s.
1.44      crook    9668: 
1.78      anton    9669: Local names are kept until the end of the colon definition, even if
                   9670: they are no longer visible in any control-flow path. In a few cases
                   9671: this may lead to increased space needs for the locals name area, but
                   9672: usually less than reclaiming this space would cost in code size.
1.5       anton    9673: 
1.44      crook    9674: 
1.78      anton    9675: @node ANS Forth locals,  , Gforth locals, Locals
                   9676: @subsection ANS Forth locals
                   9677: @cindex locals, ANS Forth style
1.5       anton    9678: 
1.78      anton    9679: The ANS Forth locals wordset does not define a syntax for locals, but
                   9680: words that make it possible to define various syntaxes. One of the
                   9681: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   9682: wordset, i.e.:
1.29      crook    9683: 
                   9684: @example
1.78      anton    9685: @{ local1 local2 ... -- comment @}
                   9686: @end example
                   9687: @noindent
                   9688: or
                   9689: @example
                   9690: @{ local1 local2 ... @}
1.29      crook    9691: @end example
                   9692: 
1.78      anton    9693: The order of the locals corresponds to the order in a stack comment. The
                   9694: restrictions are:
1.5       anton    9695: 
1.78      anton    9696: @itemize @bullet
                   9697: @item
                   9698: Locals can only be cell-sized values (no type specifiers are allowed).
                   9699: @item
                   9700: Locals can be defined only outside control structures.
                   9701: @item
                   9702: Locals can interfere with explicit usage of the return stack. For the
                   9703: exact (and long) rules, see the standard. If you don't use return stack
                   9704: accessing words in a definition using locals, you will be all right. The
                   9705: purpose of this rule is to make locals implementation on the return
                   9706: stack easier.
                   9707: @item
                   9708: The whole definition must be in one line.
                   9709: @end itemize
1.5       anton    9710: 
1.78      anton    9711: Locals defined in ANS Forth behave like @code{VALUE}s
                   9712: (@pxref{Values}). I.e., they are initialized from the stack. Using their
                   9713: name produces their value. Their value can be changed using @code{TO}.
1.77      anton    9714: 
1.78      anton    9715: Since the syntax above is supported by Gforth directly, you need not do
                   9716: anything to use it. If you want to port a program using this syntax to
                   9717: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   9718: syntax on the other system.
1.5       anton    9719: 
1.78      anton    9720: Note that a syntax shown in the standard, section A.13 looks
                   9721: similar, but is quite different in having the order of locals
                   9722: reversed. Beware!
1.5       anton    9723: 
1.78      anton    9724: The ANS Forth locals wordset itself consists of one word:
1.5       anton    9725: 
1.78      anton    9726: doc-(local)
1.5       anton    9727: 
1.78      anton    9728: The ANS Forth locals extension wordset defines a syntax using
                   9729: @code{locals|}, but it is so awful that we strongly recommend not to use
                   9730: it. We have implemented this syntax to make porting to Gforth easy, but
                   9731: do not document it here. The problem with this syntax is that the locals
                   9732: are defined in an order reversed with respect to the standard stack
                   9733: comment notation, making programs harder to read, and easier to misread
                   9734: and miswrite. The only merit of this syntax is that it is easy to
                   9735: implement using the ANS Forth locals wordset.
1.53      anton    9736: 
                   9737: 
1.78      anton    9738: @c ----------------------------------------------------------
                   9739: @node Structures, Object-oriented Forth, Locals, Words
                   9740: @section  Structures
                   9741: @cindex structures
                   9742: @cindex records
1.53      anton    9743: 
1.78      anton    9744: This section presents the structure package that comes with Gforth. A
                   9745: version of the package implemented in ANS Forth is available in
                   9746: @file{compat/struct.fs}. This package was inspired by a posting on
                   9747: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   9748: possibly John Hayes). A version of this section has been published in
                   9749: M. Anton Ertl,
                   9750: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
                   9751: Another Forth Structures Package}, Forth Dimensions 19(3), pages
                   9752: 13--16. Marcel Hendrix provided helpful comments.
1.53      anton    9753: 
1.78      anton    9754: @menu
                   9755: * Why explicit structure support?::  
                   9756: * Structure Usage::             
                   9757: * Structure Naming Convention::  
                   9758: * Structure Implementation::    
                   9759: * Structure Glossary::          
                   9760: @end menu
1.55      anton    9761: 
1.78      anton    9762: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   9763: @subsection Why explicit structure support?
1.53      anton    9764: 
1.78      anton    9765: @cindex address arithmetic for structures
                   9766: @cindex structures using address arithmetic
                   9767: If we want to use a structure containing several fields, we could simply
                   9768: reserve memory for it, and access the fields using address arithmetic
                   9769: (@pxref{Address arithmetic}). As an example, consider a structure with
                   9770: the following fields
1.57      anton    9771: 
1.78      anton    9772: @table @code
                   9773: @item a
                   9774: is a float
                   9775: @item b
                   9776: is a cell
                   9777: @item c
                   9778: is a float
                   9779: @end table
1.57      anton    9780: 
1.78      anton    9781: Given the (float-aligned) base address of the structure we get the
                   9782: address of the field
1.52      anton    9783: 
1.78      anton    9784: @table @code
                   9785: @item a
                   9786: without doing anything further.
                   9787: @item b
                   9788: with @code{float+}
                   9789: @item c
                   9790: with @code{float+ cell+ faligned}
                   9791: @end table
1.52      anton    9792: 
1.78      anton    9793: It is easy to see that this can become quite tiring. 
1.52      anton    9794: 
1.78      anton    9795: Moreover, it is not very readable, because seeing a
                   9796: @code{cell+} tells us neither which kind of structure is
                   9797: accessed nor what field is accessed; we have to somehow infer the kind
                   9798: of structure, and then look up in the documentation, which field of
                   9799: that structure corresponds to that offset.
1.53      anton    9800: 
1.78      anton    9801: Finally, this kind of address arithmetic also causes maintenance
                   9802: troubles: If you add or delete a field somewhere in the middle of the
                   9803: structure, you have to find and change all computations for the fields
                   9804: afterwards.
1.52      anton    9805: 
1.78      anton    9806: So, instead of using @code{cell+} and friends directly, how
                   9807: about storing the offsets in constants:
1.52      anton    9808: 
1.78      anton    9809: @example
                   9810: 0 constant a-offset
                   9811: 0 float+ constant b-offset
                   9812: 0 float+ cell+ faligned c-offset
                   9813: @end example
1.64      pazsan   9814: 
1.78      anton    9815: Now we can get the address of field @code{x} with @code{x-offset
                   9816: +}. This is much better in all respects. Of course, you still
                   9817: have to change all later offset definitions if you add a field. You can
                   9818: fix this by declaring the offsets in the following way:
1.57      anton    9819: 
1.78      anton    9820: @example
                   9821: 0 constant a-offset
                   9822: a-offset float+ constant b-offset
                   9823: b-offset cell+ faligned constant c-offset
                   9824: @end example
1.57      anton    9825: 
1.78      anton    9826: Since we always use the offsets with @code{+}, we could use a defining
                   9827: word @code{cfield} that includes the @code{+} in the action of the
                   9828: defined word:
1.64      pazsan   9829: 
1.78      anton    9830: @example
                   9831: : cfield ( n "name" -- )
                   9832:     create ,
                   9833: does> ( name execution: addr1 -- addr2 )
                   9834:     @@ + ;
1.64      pazsan   9835: 
1.78      anton    9836: 0 cfield a
                   9837: 0 a float+ cfield b
                   9838: 0 b cell+ faligned cfield c
                   9839: @end example
1.64      pazsan   9840: 
1.78      anton    9841: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64      pazsan   9842: 
1.78      anton    9843: The structure field words now can be used quite nicely. However,
                   9844: their definition is still a bit cumbersome: We have to repeat the
                   9845: name, the information about size and alignment is distributed before
                   9846: and after the field definitions etc.  The structure package presented
                   9847: here addresses these problems.
1.64      pazsan   9848: 
1.78      anton    9849: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   9850: @subsection Structure Usage
                   9851: @cindex structure usage
1.57      anton    9852: 
1.78      anton    9853: @cindex @code{field} usage
                   9854: @cindex @code{struct} usage
                   9855: @cindex @code{end-struct} usage
                   9856: You can define a structure for a (data-less) linked list with:
1.57      anton    9857: @example
1.78      anton    9858: struct
                   9859:     cell% field list-next
                   9860: end-struct list%
1.57      anton    9861: @end example
                   9862: 
1.78      anton    9863: With the address of the list node on the stack, you can compute the
                   9864: address of the field that contains the address of the next node with
                   9865: @code{list-next}. E.g., you can determine the length of a list
                   9866: with:
1.57      anton    9867: 
                   9868: @example
1.78      anton    9869: : list-length ( list -- n )
                   9870: \ "list" is a pointer to the first element of a linked list
                   9871: \ "n" is the length of the list
                   9872:     0 BEGIN ( list1 n1 )
                   9873:         over
                   9874:     WHILE ( list1 n1 )
                   9875:         1+ swap list-next @@ swap
                   9876:     REPEAT
                   9877:     nip ;
1.57      anton    9878: @end example
                   9879: 
1.78      anton    9880: You can reserve memory for a list node in the dictionary with
                   9881: @code{list% %allot}, which leaves the address of the list node on the
                   9882: stack. For the equivalent allocation on the heap you can use @code{list%
                   9883: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   9884: use @code{list% %allocate}). You can get the the size of a list
                   9885: node with @code{list% %size} and its alignment with @code{list%
                   9886: %alignment}.
                   9887: 
                   9888: Note that in ANS Forth the body of a @code{create}d word is
                   9889: @code{aligned} but not necessarily @code{faligned};
                   9890: therefore, if you do a:
1.57      anton    9891: 
                   9892: @example
1.78      anton    9893: create @emph{name} foo% %allot drop
1.57      anton    9894: @end example
                   9895: 
1.78      anton    9896: @noindent
                   9897: then the memory alloted for @code{foo%} is guaranteed to start at the
                   9898: body of @code{@emph{name}} only if @code{foo%} contains only character,
                   9899: cell and double fields.  Therefore, if your structure contains floats,
                   9900: better use
1.57      anton    9901: 
                   9902: @example
1.78      anton    9903: foo% %allot constant @emph{name}
1.57      anton    9904: @end example
                   9905: 
1.78      anton    9906: @cindex structures containing structures
                   9907: You can include a structure @code{foo%} as a field of
                   9908: another structure, like this:
1.65      anton    9909: @example
1.78      anton    9910: struct
                   9911: ...
                   9912:     foo% field ...
                   9913: ...
                   9914: end-struct ...
1.65      anton    9915: @end example
1.52      anton    9916: 
1.78      anton    9917: @cindex structure extension
                   9918: @cindex extended records
                   9919: Instead of starting with an empty structure, you can extend an
                   9920: existing structure. E.g., a plain linked list without data, as defined
                   9921: above, is hardly useful; You can extend it to a linked list of integers,
                   9922: like this:@footnote{This feature is also known as @emph{extended
                   9923: records}. It is the main innovation in the Oberon language; in other
                   9924: words, adding this feature to Modula-2 led Wirth to create a new
                   9925: language, write a new compiler etc.  Adding this feature to Forth just
                   9926: required a few lines of code.}
1.52      anton    9927: 
1.78      anton    9928: @example
                   9929: list%
                   9930:     cell% field intlist-int
                   9931: end-struct intlist%
                   9932: @end example
1.55      anton    9933: 
1.78      anton    9934: @code{intlist%} is a structure with two fields:
                   9935: @code{list-next} and @code{intlist-int}.
1.55      anton    9936: 
1.78      anton    9937: @cindex structures containing arrays
                   9938: You can specify an array type containing @emph{n} elements of
                   9939: type @code{foo%} like this:
1.55      anton    9940: 
                   9941: @example
1.78      anton    9942: foo% @emph{n} *
1.56      anton    9943: @end example
1.55      anton    9944: 
1.78      anton    9945: You can use this array type in any place where you can use a normal
                   9946: type, e.g., when defining a @code{field}, or with
                   9947: @code{%allot}.
                   9948: 
                   9949: @cindex first field optimization
                   9950: The first field is at the base address of a structure and the word for
                   9951: this field (e.g., @code{list-next}) actually does not change the address
                   9952: on the stack. You may be tempted to leave it away in the interest of
                   9953: run-time and space efficiency. This is not necessary, because the
                   9954: structure package optimizes this case: If you compile a first-field
                   9955: words, no code is generated. So, in the interest of readability and
                   9956: maintainability you should include the word for the field when accessing
                   9957: the field.
1.52      anton    9958: 
                   9959: 
1.78      anton    9960: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   9961: @subsection Structure Naming Convention
                   9962: @cindex structure naming convention
1.52      anton    9963: 
1.78      anton    9964: The field names that come to (my) mind are often quite generic, and,
                   9965: if used, would cause frequent name clashes. E.g., many structures
                   9966: probably contain a @code{counter} field. The structure names
                   9967: that come to (my) mind are often also the logical choice for the names
                   9968: of words that create such a structure.
1.52      anton    9969: 
1.78      anton    9970: Therefore, I have adopted the following naming conventions: 
1.52      anton    9971: 
1.78      anton    9972: @itemize @bullet
                   9973: @cindex field naming convention
                   9974: @item
                   9975: The names of fields are of the form
                   9976: @code{@emph{struct}-@emph{field}}, where
                   9977: @code{@emph{struct}} is the basic name of the structure, and
                   9978: @code{@emph{field}} is the basic name of the field. You can
                   9979: think of field words as converting the (address of the)
                   9980: structure into the (address of the) field.
1.52      anton    9981: 
1.78      anton    9982: @cindex structure naming convention
                   9983: @item
                   9984: The names of structures are of the form
                   9985: @code{@emph{struct}%}, where
                   9986: @code{@emph{struct}} is the basic name of the structure.
                   9987: @end itemize
1.52      anton    9988: 
1.78      anton    9989: This naming convention does not work that well for fields of extended
                   9990: structures; e.g., the integer list structure has a field
                   9991: @code{intlist-int}, but has @code{list-next}, not
                   9992: @code{intlist-next}.
1.53      anton    9993: 
1.78      anton    9994: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   9995: @subsection Structure Implementation
                   9996: @cindex structure implementation
                   9997: @cindex implementation of structures
1.52      anton    9998: 
1.78      anton    9999: The central idea in the implementation is to pass the data about the
                   10000: structure being built on the stack, not in some global
                   10001: variable. Everything else falls into place naturally once this design
                   10002: decision is made.
1.53      anton    10003: 
1.78      anton    10004: The type description on the stack is of the form @emph{align
                   10005: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   10006: very simple.
1.53      anton    10007: 
1.78      anton    10008: @code{field} is a defining word that uses @code{Create}
                   10009: and @code{DOES>}. The body of the field contains the offset
                   10010: of the field, and the normal @code{DOES>} action is simply:
1.53      anton    10011: 
                   10012: @example
1.78      anton    10013: @@ +
1.53      anton    10014: @end example
                   10015: 
1.78      anton    10016: @noindent
                   10017: i.e., add the offset to the address, giving the stack effect
                   10018: @i{addr1 -- addr2} for a field.
                   10019: 
                   10020: @cindex first field optimization, implementation
                   10021: This simple structure is slightly complicated by the optimization
                   10022: for fields with offset 0, which requires a different
                   10023: @code{DOES>}-part (because we cannot rely on there being
                   10024: something on the stack if such a field is invoked during
                   10025: compilation). Therefore, we put the different @code{DOES>}-parts
                   10026: in separate words, and decide which one to invoke based on the
                   10027: offset. For a zero offset, the field is basically a noop; it is
                   10028: immediate, and therefore no code is generated when it is compiled.
1.53      anton    10029: 
1.78      anton    10030: @node Structure Glossary,  , Structure Implementation, Structures
                   10031: @subsection Structure Glossary
                   10032: @cindex structure glossary
1.53      anton    10033: 
1.5       anton    10034: 
1.78      anton    10035: doc-%align
                   10036: doc-%alignment
                   10037: doc-%alloc
                   10038: doc-%allocate
                   10039: doc-%allot
                   10040: doc-cell%
                   10041: doc-char%
                   10042: doc-dfloat%
                   10043: doc-double%
                   10044: doc-end-struct
                   10045: doc-field
                   10046: doc-float%
                   10047: doc-naligned
                   10048: doc-sfloat%
                   10049: doc-%size
                   10050: doc-struct
1.54      anton    10051: 
                   10052: 
1.26      crook    10053: @c -------------------------------------------------------------
1.78      anton    10054: @node Object-oriented Forth, Programming Tools, Structures, Words
                   10055: @section Object-oriented Forth
                   10056: 
                   10057: Gforth comes with three packages for object-oriented programming:
                   10058: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   10059: is preloaded, so you have to @code{include} them before use. The most
                   10060: important differences between these packages (and others) are discussed
                   10061: in @ref{Comparison with other object models}. All packages are written
                   10062: in ANS Forth and can be used with any other ANS Forth.
1.5       anton    10063: 
1.78      anton    10064: @menu
                   10065: * Why object-oriented programming?::  
                   10066: * Object-Oriented Terminology::  
                   10067: * Objects::                     
                   10068: * OOF::                         
                   10069: * Mini-OOF::                    
                   10070: * Comparison with other object models::  
                   10071: @end menu
1.5       anton    10072: 
1.78      anton    10073: @c ----------------------------------------------------------------
                   10074: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
                   10075: @subsection Why object-oriented programming?
                   10076: @cindex object-oriented programming motivation
                   10077: @cindex motivation for object-oriented programming
1.44      crook    10078: 
1.78      anton    10079: Often we have to deal with several data structures (@emph{objects}),
                   10080: that have to be treated similarly in some respects, but differently in
                   10081: others. Graphical objects are the textbook example: circles, triangles,
                   10082: dinosaurs, icons, and others, and we may want to add more during program
                   10083: development. We want to apply some operations to any graphical object,
                   10084: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   10085: has to do something different for every kind of object.
                   10086: @comment TODO add some other operations eg perimeter, area
                   10087: @comment and tie in to concrete examples later..
1.5       anton    10088: 
1.78      anton    10089: We could implement @code{draw} as a big @code{CASE}
                   10090: control structure that executes the appropriate code depending on the
                   10091: kind of object to be drawn. This would be not be very elegant, and,
                   10092: moreover, we would have to change @code{draw} every time we add
                   10093: a new kind of graphical object (say, a spaceship).
1.44      crook    10094: 
1.78      anton    10095: What we would rather do is: When defining spaceships, we would tell
                   10096: the system: ``Here's how you @code{draw} a spaceship; you figure
                   10097: out the rest''.
1.5       anton    10098: 
1.78      anton    10099: This is the problem that all systems solve that (rightfully) call
                   10100: themselves object-oriented; the object-oriented packages presented here
                   10101: solve this problem (and not much else).
                   10102: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44      crook    10103: 
1.78      anton    10104: @c ------------------------------------------------------------------------
                   10105: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
                   10106: @subsection Object-Oriented Terminology
                   10107: @cindex object-oriented terminology
                   10108: @cindex terminology for object-oriented programming
1.5       anton    10109: 
1.78      anton    10110: This section is mainly for reference, so you don't have to understand
                   10111: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   10112: short:
1.44      crook    10113: 
1.78      anton    10114: @table @emph
                   10115: @cindex class
                   10116: @item class
                   10117: a data structure definition with some extras.
1.5       anton    10118: 
1.78      anton    10119: @cindex object
                   10120: @item object
                   10121: an instance of the data structure described by the class definition.
1.5       anton    10122: 
1.78      anton    10123: @cindex instance variables
                   10124: @item instance variables
                   10125: fields of the data structure.
1.5       anton    10126: 
1.78      anton    10127: @cindex selector
                   10128: @cindex method selector
                   10129: @cindex virtual function
                   10130: @item selector
                   10131: (or @emph{method selector}) a word (e.g.,
                   10132: @code{draw}) that performs an operation on a variety of data
                   10133: structures (classes). A selector describes @emph{what} operation to
                   10134: perform. In C++ terminology: a (pure) virtual function.
1.5       anton    10135: 
1.78      anton    10136: @cindex method
                   10137: @item method
                   10138: the concrete definition that performs the operation
                   10139: described by the selector for a specific class. A method specifies
                   10140: @emph{how} the operation is performed for a specific class.
1.5       anton    10141: 
1.78      anton    10142: @cindex selector invocation
                   10143: @cindex message send
                   10144: @cindex invoking a selector
                   10145: @item selector invocation
                   10146: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   10147: is used for determining which method is used. In Smalltalk terminology:
                   10148: a message (consisting of the selector and the other arguments) is sent
                   10149: to the object.
1.5       anton    10150: 
1.78      anton    10151: @cindex receiving object
                   10152: @item receiving object
                   10153: the object used for determining the method executed by a selector
                   10154: invocation. In the @file{objects.fs} model, it is the object that is on
                   10155: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   10156: the Smalltalk @emph{message} terminology.)
1.5       anton    10157: 
1.78      anton    10158: @cindex child class
                   10159: @cindex parent class
                   10160: @cindex inheritance
                   10161: @item child class
                   10162: a class that has (@emph{inherits}) all properties (instance variables,
                   10163: selectors, methods) from a @emph{parent class}. In Smalltalk
                   10164: terminology: The subclass inherits from the superclass. In C++
                   10165: terminology: The derived class inherits from the base class.
1.5       anton    10166: 
1.78      anton    10167: @end table
1.5       anton    10168: 
1.78      anton    10169: @c If you wonder about the message sending terminology, it comes from
                   10170: @c a time when each object had it's own task and objects communicated via
                   10171: @c message passing; eventually the Smalltalk developers realized that
                   10172: @c they can do most things through simple (indirect) calls. They kept the
                   10173: @c terminology.
1.5       anton    10174: 
1.78      anton    10175: @c --------------------------------------------------------------
                   10176: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   10177: @subsection The @file{objects.fs} model
                   10178: @cindex objects
                   10179: @cindex object-oriented programming
1.26      crook    10180: 
1.78      anton    10181: @cindex @file{objects.fs}
                   10182: @cindex @file{oof.fs}
1.26      crook    10183: 
1.78      anton    10184: This section describes the @file{objects.fs} package. This material also
                   10185: has been published in M. Anton Ertl,
                   10186: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
                   10187: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
                   10188: 37--43.
                   10189: @c McKewan's and Zsoter's packages
1.26      crook    10190: 
1.78      anton    10191: This section assumes that you have read @ref{Structures}.
1.5       anton    10192: 
1.78      anton    10193: The techniques on which this model is based have been used to implement
                   10194: the parser generator, Gray, and have also been used in Gforth for
                   10195: implementing the various flavours of word lists (hashed or not,
                   10196: case-sensitive or not, special-purpose word lists for locals etc.).
1.5       anton    10197: 
                   10198: 
1.26      crook    10199: @menu
1.78      anton    10200: * Properties of the Objects model::  
                   10201: * Basic Objects Usage::         
                   10202: * The Objects base class::      
                   10203: * Creating objects::            
                   10204: * Object-Oriented Programming Style::  
                   10205: * Class Binding::               
                   10206: * Method conveniences::         
                   10207: * Classes and Scoping::         
                   10208: * Dividing classes::            
                   10209: * Object Interfaces::           
                   10210: * Objects Implementation::      
                   10211: * Objects Glossary::            
1.26      crook    10212: @end menu
1.5       anton    10213: 
1.78      anton    10214: Marcel Hendrix provided helpful comments on this section.
1.5       anton    10215: 
1.78      anton    10216: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   10217: @subsubsection Properties of the @file{objects.fs} model
                   10218: @cindex @file{objects.fs} properties
1.5       anton    10219: 
1.78      anton    10220: @itemize @bullet
                   10221: @item
                   10222: It is straightforward to pass objects on the stack. Passing
                   10223: selectors on the stack is a little less convenient, but possible.
1.44      crook    10224: 
1.78      anton    10225: @item
                   10226: Objects are just data structures in memory, and are referenced by their
                   10227: address. You can create words for objects with normal defining words
                   10228: like @code{constant}. Likewise, there is no difference between instance
                   10229: variables that contain objects and those that contain other data.
1.5       anton    10230: 
1.78      anton    10231: @item
                   10232: Late binding is efficient and easy to use.
1.44      crook    10233: 
1.78      anton    10234: @item
                   10235: It avoids parsing, and thus avoids problems with state-smartness
                   10236: and reduced extensibility; for convenience there are a few parsing
                   10237: words, but they have non-parsing counterparts. There are also a few
                   10238: defining words that parse. This is hard to avoid, because all standard
                   10239: defining words parse (except @code{:noname}); however, such
                   10240: words are not as bad as many other parsing words, because they are not
                   10241: state-smart.
1.5       anton    10242: 
1.78      anton    10243: @item
                   10244: It does not try to incorporate everything. It does a few things and does
                   10245: them well (IMO). In particular, this model was not designed to support
                   10246: information hiding (although it has features that may help); you can use
                   10247: a separate package for achieving this.
1.5       anton    10248: 
1.78      anton    10249: @item
                   10250: It is layered; you don't have to learn and use all features to use this
                   10251: model. Only a few features are necessary (@pxref{Basic Objects Usage},
                   10252: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
                   10253: are optional and independent of each other.
1.5       anton    10254: 
1.78      anton    10255: @item
                   10256: An implementation in ANS Forth is available.
1.5       anton    10257: 
1.78      anton    10258: @end itemize
1.5       anton    10259: 
1.44      crook    10260: 
1.78      anton    10261: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   10262: @subsubsection Basic @file{objects.fs} Usage
                   10263: @cindex basic objects usage
                   10264: @cindex objects, basic usage
1.5       anton    10265: 
1.78      anton    10266: You can define a class for graphical objects like this:
1.44      crook    10267: 
1.78      anton    10268: @cindex @code{class} usage
                   10269: @cindex @code{end-class} usage
                   10270: @cindex @code{selector} usage
1.5       anton    10271: @example
1.78      anton    10272: object class \ "object" is the parent class
                   10273:   selector draw ( x y graphical -- )
                   10274: end-class graphical
                   10275: @end example
                   10276: 
                   10277: This code defines a class @code{graphical} with an
                   10278: operation @code{draw}.  We can perform the operation
                   10279: @code{draw} on any @code{graphical} object, e.g.:
                   10280: 
                   10281: @example
                   10282: 100 100 t-rex draw
1.26      crook    10283: @end example
1.5       anton    10284: 
1.78      anton    10285: @noindent
                   10286: where @code{t-rex} is a word (say, a constant) that produces a
                   10287: graphical object.
                   10288: 
                   10289: @comment TODO add a 2nd operation eg perimeter.. and use for
                   10290: @comment a concrete example
1.5       anton    10291: 
1.78      anton    10292: @cindex abstract class
                   10293: How do we create a graphical object? With the present definitions,
                   10294: we cannot create a useful graphical object. The class
                   10295: @code{graphical} describes graphical objects in general, but not
                   10296: any concrete graphical object type (C++ users would call it an
                   10297: @emph{abstract class}); e.g., there is no method for the selector
                   10298: @code{draw} in the class @code{graphical}.
1.5       anton    10299: 
1.78      anton    10300: For concrete graphical objects, we define child classes of the
                   10301: class @code{graphical}, e.g.:
1.5       anton    10302: 
1.78      anton    10303: @cindex @code{overrides} usage
                   10304: @cindex @code{field} usage in class definition
1.26      crook    10305: @example
1.78      anton    10306: graphical class \ "graphical" is the parent class
                   10307:   cell% field circle-radius
1.5       anton    10308: 
1.78      anton    10309: :noname ( x y circle -- )
                   10310:   circle-radius @@ draw-circle ;
                   10311: overrides draw
1.5       anton    10312: 
1.78      anton    10313: :noname ( n-radius circle -- )
                   10314:   circle-radius ! ;
                   10315: overrides construct
1.5       anton    10316: 
1.78      anton    10317: end-class circle
                   10318: @end example
1.44      crook    10319: 
1.78      anton    10320: Here we define a class @code{circle} as a child of @code{graphical},
                   10321: with field @code{circle-radius} (which behaves just like a field
                   10322: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   10323: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   10324: defined in @code{object}, the parent class of @code{graphical}).
1.5       anton    10325: 
1.78      anton    10326: Now we can create a circle on the heap (i.e.,
                   10327: @code{allocate}d memory) with:
1.44      crook    10328: 
1.78      anton    10329: @cindex @code{heap-new} usage
1.5       anton    10330: @example
1.78      anton    10331: 50 circle heap-new constant my-circle
1.5       anton    10332: @end example
                   10333: 
1.78      anton    10334: @noindent
                   10335: @code{heap-new} invokes @code{construct}, thus
                   10336: initializing the field @code{circle-radius} with 50. We can draw
                   10337: this new circle at (100,100) with:
1.5       anton    10338: 
                   10339: @example
1.78      anton    10340: 100 100 my-circle draw
1.5       anton    10341: @end example
                   10342: 
1.78      anton    10343: @cindex selector invocation, restrictions
                   10344: @cindex class definition, restrictions
                   10345: Note: You can only invoke a selector if the object on the TOS
                   10346: (the receiving object) belongs to the class where the selector was
                   10347: defined or one of its descendents; e.g., you can invoke
                   10348: @code{draw} only for objects belonging to @code{graphical}
                   10349: or its descendents (e.g., @code{circle}).  Immediately before
                   10350: @code{end-class}, the search order has to be the same as
                   10351: immediately after @code{class}.
                   10352: 
                   10353: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   10354: @subsubsection The @file{object.fs} base class
                   10355: @cindex @code{object} class
                   10356: 
                   10357: When you define a class, you have to specify a parent class.  So how do
                   10358: you start defining classes? There is one class available from the start:
                   10359: @code{object}. It is ancestor for all classes and so is the
                   10360: only class that has no parent. It has two selectors: @code{construct}
                   10361: and @code{print}.
                   10362: 
                   10363: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   10364: @subsubsection Creating objects
                   10365: @cindex creating objects
                   10366: @cindex object creation
                   10367: @cindex object allocation options
                   10368: 
                   10369: @cindex @code{heap-new} discussion
                   10370: @cindex @code{dict-new} discussion
                   10371: @cindex @code{construct} discussion
                   10372: You can create and initialize an object of a class on the heap with
                   10373: @code{heap-new} ( ... class -- object ) and in the dictionary
                   10374: (allocation with @code{allot}) with @code{dict-new} (
                   10375: ... class -- object ). Both words invoke @code{construct}, which
                   10376: consumes the stack items indicated by "..." above.
                   10377: 
                   10378: @cindex @code{init-object} discussion
                   10379: @cindex @code{class-inst-size} discussion
                   10380: If you want to allocate memory for an object yourself, you can get its
                   10381: alignment and size with @code{class-inst-size 2@@} ( class --
                   10382: align size ). Once you have memory for an object, you can initialize
                   10383: it with @code{init-object} ( ... class object -- );
                   10384: @code{construct} does only a part of the necessary work.
                   10385: 
                   10386: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   10387: @subsubsection Object-Oriented Programming Style
                   10388: @cindex object-oriented programming style
                   10389: @cindex programming style, object-oriented
1.5       anton    10390: 
1.78      anton    10391: This section is not exhaustive.
1.5       anton    10392: 
1.78      anton    10393: @cindex stack effects of selectors
                   10394: @cindex selectors and stack effects
                   10395: In general, it is a good idea to ensure that all methods for the
                   10396: same selector have the same stack effect: when you invoke a selector,
                   10397: you often have no idea which method will be invoked, so, unless all
                   10398: methods have the same stack effect, you will not know the stack effect
                   10399: of the selector invocation.
1.5       anton    10400: 
1.78      anton    10401: One exception to this rule is methods for the selector
                   10402: @code{construct}. We know which method is invoked, because we
                   10403: specify the class to be constructed at the same place. Actually, I
                   10404: defined @code{construct} as a selector only to give the users a
                   10405: convenient way to specify initialization. The way it is used, a
                   10406: mechanism different from selector invocation would be more natural
                   10407: (but probably would take more code and more space to explain).
1.5       anton    10408: 
1.78      anton    10409: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   10410: @subsubsection Class Binding
                   10411: @cindex class binding
                   10412: @cindex early binding
1.5       anton    10413: 
1.78      anton    10414: @cindex late binding
                   10415: Normal selector invocations determine the method at run-time depending
                   10416: on the class of the receiving object. This run-time selection is called
                   10417: @i{late binding}.
1.5       anton    10418: 
1.78      anton    10419: Sometimes it's preferable to invoke a different method. For example,
                   10420: you might want to use the simple method for @code{print}ing
                   10421: @code{object}s instead of the possibly long-winded @code{print} method
                   10422: of the receiver class. You can achieve this by replacing the invocation
                   10423: of @code{print} with:
1.5       anton    10424: 
1.78      anton    10425: @cindex @code{[bind]} usage
1.5       anton    10426: @example
1.78      anton    10427: [bind] object print
1.5       anton    10428: @end example
                   10429: 
1.78      anton    10430: @noindent
                   10431: in compiled code or:
                   10432: 
                   10433: @cindex @code{bind} usage
1.5       anton    10434: @example
1.78      anton    10435: bind object print
1.5       anton    10436: @end example
                   10437: 
1.78      anton    10438: @cindex class binding, alternative to
                   10439: @noindent
                   10440: in interpreted code. Alternatively, you can define the method with a
                   10441: name (e.g., @code{print-object}), and then invoke it through the
                   10442: name. Class binding is just a (often more convenient) way to achieve
                   10443: the same effect; it avoids name clutter and allows you to invoke
                   10444: methods directly without naming them first.
1.5       anton    10445: 
1.78      anton    10446: @cindex superclass binding
                   10447: @cindex parent class binding
                   10448: A frequent use of class binding is this: When we define a method
                   10449: for a selector, we often want the method to do what the selector does
                   10450: in the parent class, and a little more. There is a special word for
                   10451: this purpose: @code{[parent]}; @code{[parent]
                   10452: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   10453: selector}}, where @code{@emph{parent}} is the parent
                   10454: class of the current class. E.g., a method definition might look like:
1.44      crook    10455: 
1.78      anton    10456: @cindex @code{[parent]} usage
                   10457: @example
                   10458: :noname
                   10459:   dup [parent] foo \ do parent's foo on the receiving object
                   10460:   ... \ do some more
                   10461: ; overrides foo
                   10462: @end example
1.6       pazsan   10463: 
1.78      anton    10464: @cindex class binding as optimization
                   10465: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   10466: March 1997), Andrew McKewan presents class binding as an optimization
                   10467: technique. I recommend not using it for this purpose unless you are in
                   10468: an emergency. Late binding is pretty fast with this model anyway, so the
                   10469: benefit of using class binding is small; the cost of using class binding
                   10470: where it is not appropriate is reduced maintainability.
1.44      crook    10471: 
1.78      anton    10472: While we are at programming style questions: You should bind
                   10473: selectors only to ancestor classes of the receiving object. E.g., say,
                   10474: you know that the receiving object is of class @code{foo} or its
                   10475: descendents; then you should bind only to @code{foo} and its
                   10476: ancestors.
1.12      anton    10477: 
1.78      anton    10478: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   10479: @subsubsection Method conveniences
                   10480: @cindex method conveniences
1.44      crook    10481: 
1.78      anton    10482: In a method you usually access the receiving object pretty often.  If
                   10483: you define the method as a plain colon definition (e.g., with
                   10484: @code{:noname}), you may have to do a lot of stack
                   10485: gymnastics. To avoid this, you can define the method with @code{m:
                   10486: ... ;m}. E.g., you could define the method for
                   10487: @code{draw}ing a @code{circle} with
1.6       pazsan   10488: 
1.78      anton    10489: @cindex @code{this} usage
                   10490: @cindex @code{m:} usage
                   10491: @cindex @code{;m} usage
                   10492: @example
                   10493: m: ( x y circle -- )
                   10494:   ( x y ) this circle-radius @@ draw-circle ;m
                   10495: @end example
1.6       pazsan   10496: 
1.78      anton    10497: @cindex @code{exit} in @code{m: ... ;m}
                   10498: @cindex @code{exitm} discussion
                   10499: @cindex @code{catch} in @code{m: ... ;m}
                   10500: When this method is executed, the receiver object is removed from the
                   10501: stack; you can access it with @code{this} (admittedly, in this
                   10502: example the use of @code{m: ... ;m} offers no advantage). Note
                   10503: that I specify the stack effect for the whole method (i.e. including
                   10504: the receiver object), not just for the code between @code{m:}
                   10505: and @code{;m}. You cannot use @code{exit} in
                   10506: @code{m:...;m}; instead, use
                   10507: @code{exitm}.@footnote{Moreover, for any word that calls
                   10508: @code{catch} and was defined before loading
                   10509: @code{objects.fs}, you have to redefine it like I redefined
                   10510: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12      anton    10511: 
1.78      anton    10512: @cindex @code{inst-var} usage
                   10513: You will frequently use sequences of the form @code{this
                   10514: @emph{field}} (in the example above: @code{this
                   10515: circle-radius}). If you use the field only in this way, you can
                   10516: define it with @code{inst-var} and eliminate the
                   10517: @code{this} before the field name. E.g., the @code{circle}
                   10518: class above could also be defined with:
1.6       pazsan   10519: 
1.78      anton    10520: @example
                   10521: graphical class
                   10522:   cell% inst-var radius
1.6       pazsan   10523: 
1.78      anton    10524: m: ( x y circle -- )
                   10525:   radius @@ draw-circle ;m
                   10526: overrides draw
1.6       pazsan   10527: 
1.78      anton    10528: m: ( n-radius circle -- )
                   10529:   radius ! ;m
                   10530: overrides construct
1.6       pazsan   10531: 
1.78      anton    10532: end-class circle
                   10533: @end example
1.6       pazsan   10534: 
1.78      anton    10535: @code{radius} can only be used in @code{circle} and its
                   10536: descendent classes and inside @code{m:...;m}.
1.6       pazsan   10537: 
1.78      anton    10538: @cindex @code{inst-value} usage
                   10539: You can also define fields with @code{inst-value}, which is
                   10540: to @code{inst-var} what @code{value} is to
                   10541: @code{variable}.  You can change the value of such a field with
                   10542: @code{[to-inst]}.  E.g., we could also define the class
                   10543: @code{circle} like this:
1.44      crook    10544: 
1.78      anton    10545: @example
                   10546: graphical class
                   10547:   inst-value radius
1.6       pazsan   10548: 
1.78      anton    10549: m: ( x y circle -- )
                   10550:   radius draw-circle ;m
                   10551: overrides draw
1.44      crook    10552: 
1.78      anton    10553: m: ( n-radius circle -- )
                   10554:   [to-inst] radius ;m
                   10555: overrides construct
1.6       pazsan   10556: 
1.78      anton    10557: end-class circle
                   10558: @end example
1.6       pazsan   10559: 
1.78      anton    10560: @c !! :m is easy to confuse with m:.  Another name would be better.
1.6       pazsan   10561: 
1.78      anton    10562: @c Finally, you can define named methods with @code{:m}.  One use of this
                   10563: @c feature is the definition of words that occur only in one class and are
                   10564: @c not intended to be overridden, but which still need method context
                   10565: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
                   10566: @c would be bound frequently, if defined anonymously.
1.6       pazsan   10567: 
                   10568: 
1.78      anton    10569: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
                   10570: @subsubsection Classes and Scoping
                   10571: @cindex classes and scoping
                   10572: @cindex scoping and classes
1.6       pazsan   10573: 
1.78      anton    10574: Inheritance is frequent, unlike structure extension. This exacerbates
                   10575: the problem with the field name convention (@pxref{Structure Naming
                   10576: Convention}): One always has to remember in which class the field was
                   10577: originally defined; changing a part of the class structure would require
                   10578: changes for renaming in otherwise unaffected code.
1.6       pazsan   10579: 
1.78      anton    10580: @cindex @code{inst-var} visibility
                   10581: @cindex @code{inst-value} visibility
                   10582: To solve this problem, I added a scoping mechanism (which was not in my
                   10583: original charter): A field defined with @code{inst-var} (or
                   10584: @code{inst-value}) is visible only in the class where it is defined and in
                   10585: the descendent classes of this class.  Using such fields only makes
                   10586: sense in @code{m:}-defined methods in these classes anyway.
1.6       pazsan   10587: 
1.78      anton    10588: This scoping mechanism allows us to use the unadorned field name,
                   10589: because name clashes with unrelated words become much less likely.
1.6       pazsan   10590: 
1.78      anton    10591: @cindex @code{protected} discussion
                   10592: @cindex @code{private} discussion
                   10593: Once we have this mechanism, we can also use it for controlling the
                   10594: visibility of other words: All words defined after
                   10595: @code{protected} are visible only in the current class and its
                   10596: descendents. @code{public} restores the compilation
                   10597: (i.e. @code{current}) word list that was in effect before. If you
                   10598: have several @code{protected}s without an intervening
                   10599: @code{public} or @code{set-current}, @code{public}
                   10600: will restore the compilation word list in effect before the first of
                   10601: these @code{protected}s.
1.6       pazsan   10602: 
1.78      anton    10603: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
                   10604: @subsubsection Dividing classes
                   10605: @cindex Dividing classes
                   10606: @cindex @code{methods}...@code{end-methods}
1.6       pazsan   10607: 
1.78      anton    10608: You may want to do the definition of methods separate from the
                   10609: definition of the class, its selectors, fields, and instance variables,
                   10610: i.e., separate the implementation from the definition.  You can do this
                   10611: in the following way:
1.6       pazsan   10612: 
1.78      anton    10613: @example
                   10614: graphical class
                   10615:   inst-value radius
                   10616: end-class circle
1.6       pazsan   10617: 
1.78      anton    10618: ... \ do some other stuff
1.6       pazsan   10619: 
1.78      anton    10620: circle methods \ now we are ready
1.44      crook    10621: 
1.78      anton    10622: m: ( x y circle -- )
                   10623:   radius draw-circle ;m
                   10624: overrides draw
1.6       pazsan   10625: 
1.78      anton    10626: m: ( n-radius circle -- )
                   10627:   [to-inst] radius ;m
                   10628: overrides construct
1.44      crook    10629: 
1.78      anton    10630: end-methods
                   10631: @end example
1.7       pazsan   10632: 
1.78      anton    10633: You can use several @code{methods}...@code{end-methods} sections.  The
                   10634: only things you can do to the class in these sections are: defining
                   10635: methods, and overriding the class's selectors.  You must not define new
                   10636: selectors or fields.
1.7       pazsan   10637: 
1.78      anton    10638: Note that you often have to override a selector before using it.  In
                   10639: particular, you usually have to override @code{construct} with a new
                   10640: method before you can invoke @code{heap-new} and friends.  E.g., you
                   10641: must not create a circle before the @code{overrides construct} sequence
                   10642: in the example above.
1.7       pazsan   10643: 
1.78      anton    10644: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
                   10645: @subsubsection Object Interfaces
                   10646: @cindex object interfaces
                   10647: @cindex interfaces for objects
1.7       pazsan   10648: 
1.78      anton    10649: In this model you can only call selectors defined in the class of the
                   10650: receiving objects or in one of its ancestors. If you call a selector
                   10651: with a receiving object that is not in one of these classes, the
                   10652: result is undefined; if you are lucky, the program crashes
                   10653: immediately.
1.7       pazsan   10654: 
1.78      anton    10655: @cindex selectors common to hardly-related classes
                   10656: Now consider the case when you want to have a selector (or several)
                   10657: available in two classes: You would have to add the selector to a
                   10658: common ancestor class, in the worst case to @code{object}. You
                   10659: may not want to do this, e.g., because someone else is responsible for
                   10660: this ancestor class.
1.7       pazsan   10661: 
1.78      anton    10662: The solution for this problem is interfaces. An interface is a
                   10663: collection of selectors. If a class implements an interface, the
                   10664: selectors become available to the class and its descendents. A class
                   10665: can implement an unlimited number of interfaces. For the problem
                   10666: discussed above, we would define an interface for the selector(s), and
                   10667: both classes would implement the interface.
1.7       pazsan   10668: 
1.78      anton    10669: As an example, consider an interface @code{storage} for
                   10670: writing objects to disk and getting them back, and a class
                   10671: @code{foo} that implements it. The code would look like this:
1.7       pazsan   10672: 
1.78      anton    10673: @cindex @code{interface} usage
                   10674: @cindex @code{end-interface} usage
                   10675: @cindex @code{implementation} usage
                   10676: @example
                   10677: interface
                   10678:   selector write ( file object -- )
                   10679:   selector read1 ( file object -- )
                   10680: end-interface storage
1.13      pazsan   10681: 
1.78      anton    10682: bar class
                   10683:   storage implementation
1.13      pazsan   10684: 
1.78      anton    10685: ... overrides write
                   10686: ... overrides read1
                   10687: ...
                   10688: end-class foo
                   10689: @end example
1.13      pazsan   10690: 
1.78      anton    10691: @noindent
                   10692: (I would add a word @code{read} @i{( file -- object )} that uses
                   10693: @code{read1} internally, but that's beyond the point illustrated
                   10694: here.)
1.13      pazsan   10695: 
1.78      anton    10696: Note that you cannot use @code{protected} in an interface; and
                   10697: of course you cannot define fields.
1.13      pazsan   10698: 
1.78      anton    10699: In the Neon model, all selectors are available for all classes;
                   10700: therefore it does not need interfaces. The price you pay in this model
                   10701: is slower late binding, and therefore, added complexity to avoid late
                   10702: binding.
1.13      pazsan   10703: 
1.78      anton    10704: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   10705: @subsubsection @file{objects.fs} Implementation
                   10706: @cindex @file{objects.fs} implementation
1.13      pazsan   10707: 
1.78      anton    10708: @cindex @code{object-map} discussion
                   10709: An object is a piece of memory, like one of the data structures
                   10710: described with @code{struct...end-struct}. It has a field
                   10711: @code{object-map} that points to the method map for the object's
                   10712: class.
1.13      pazsan   10713: 
1.78      anton    10714: @cindex method map
                   10715: @cindex virtual function table
                   10716: The @emph{method map}@footnote{This is Self terminology; in C++
                   10717: terminology: virtual function table.} is an array that contains the
                   10718: execution tokens (@i{xt}s) of the methods for the object's class. Each
                   10719: selector contains an offset into a method map.
1.13      pazsan   10720: 
1.78      anton    10721: @cindex @code{selector} implementation, class
                   10722: @code{selector} is a defining word that uses
                   10723: @code{CREATE} and @code{DOES>}. The body of the
                   10724: selector contains the offset; the @code{DOES>} action for a
                   10725: class selector is, basically:
1.8       pazsan   10726: 
                   10727: @example
1.78      anton    10728: ( object addr ) @@ over object-map @@ + @@ execute
1.13      pazsan   10729: @end example
                   10730: 
1.78      anton    10731: Since @code{object-map} is the first field of the object, it
                   10732: does not generate any code. As you can see, calling a selector has a
                   10733: small, constant cost.
1.26      crook    10734: 
1.78      anton    10735: @cindex @code{current-interface} discussion
                   10736: @cindex class implementation and representation
                   10737: A class is basically a @code{struct} combined with a method
                   10738: map. During the class definition the alignment and size of the class
                   10739: are passed on the stack, just as with @code{struct}s, so
                   10740: @code{field} can also be used for defining class
                   10741: fields. However, passing more items on the stack would be
                   10742: inconvenient, so @code{class} builds a data structure in memory,
                   10743: which is accessed through the variable
                   10744: @code{current-interface}. After its definition is complete, the
                   10745: class is represented on the stack by a pointer (e.g., as parameter for
                   10746: a child class definition).
1.26      crook    10747: 
1.78      anton    10748: A new class starts off with the alignment and size of its parent,
                   10749: and a copy of the parent's method map. Defining new fields extends the
                   10750: size and alignment; likewise, defining new selectors extends the
                   10751: method map. @code{overrides} just stores a new @i{xt} in the method
                   10752: map at the offset given by the selector.
1.13      pazsan   10753: 
1.78      anton    10754: @cindex class binding, implementation
                   10755: Class binding just gets the @i{xt} at the offset given by the selector
                   10756: from the class's method map and @code{compile,}s (in the case of
                   10757: @code{[bind]}) it.
1.13      pazsan   10758: 
1.78      anton    10759: @cindex @code{this} implementation
                   10760: @cindex @code{catch} and @code{this}
                   10761: @cindex @code{this} and @code{catch}
                   10762: I implemented @code{this} as a @code{value}. At the
                   10763: start of an @code{m:...;m} method the old @code{this} is
                   10764: stored to the return stack and restored at the end; and the object on
                   10765: the TOS is stored @code{TO this}. This technique has one
                   10766: disadvantage: If the user does not leave the method via
                   10767: @code{;m}, but via @code{throw} or @code{exit},
                   10768: @code{this} is not restored (and @code{exit} may
                   10769: crash). To deal with the @code{throw} problem, I have redefined
                   10770: @code{catch} to save and restore @code{this}; the same
                   10771: should be done with any word that can catch an exception. As for
                   10772: @code{exit}, I simply forbid it (as a replacement, there is
                   10773: @code{exitm}).
1.13      pazsan   10774: 
1.78      anton    10775: @cindex @code{inst-var} implementation
                   10776: @code{inst-var} is just the same as @code{field}, with
                   10777: a different @code{DOES>} action:
1.13      pazsan   10778: @example
1.78      anton    10779: @@ this +
1.8       pazsan   10780: @end example
1.78      anton    10781: Similar for @code{inst-value}.
1.8       pazsan   10782: 
1.78      anton    10783: @cindex class scoping implementation
                   10784: Each class also has a word list that contains the words defined with
                   10785: @code{inst-var} and @code{inst-value}, and its protected
                   10786: words. It also has a pointer to its parent. @code{class} pushes
                   10787: the word lists of the class and all its ancestors onto the search order stack,
                   10788: and @code{end-class} drops them.
1.20      pazsan   10789: 
1.78      anton    10790: @cindex interface implementation
                   10791: An interface is like a class without fields, parent and protected
                   10792: words; i.e., it just has a method map. If a class implements an
                   10793: interface, its method map contains a pointer to the method map of the
                   10794: interface. The positive offsets in the map are reserved for class
                   10795: methods, therefore interface map pointers have negative
                   10796: offsets. Interfaces have offsets that are unique throughout the
                   10797: system, unlike class selectors, whose offsets are only unique for the
                   10798: classes where the selector is available (invokable).
1.20      pazsan   10799: 
1.78      anton    10800: This structure means that interface selectors have to perform one
                   10801: indirection more than class selectors to find their method. Their body
                   10802: contains the interface map pointer offset in the class method map, and
                   10803: the method offset in the interface method map. The
                   10804: @code{does>} action for an interface selector is, basically:
1.20      pazsan   10805: 
                   10806: @example
1.78      anton    10807: ( object selector-body )
                   10808: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   10809: swap object-map @@ + @@ ( object selector-body map )
                   10810: swap selector-offset @@ + @@ execute
1.20      pazsan   10811: @end example
                   10812: 
1.78      anton    10813: where @code{object-map} and @code{selector-offset} are
                   10814: first fields and generate no code.
1.20      pazsan   10815: 
1.78      anton    10816: As a concrete example, consider the following code:
1.20      pazsan   10817: 
                   10818: @example
1.78      anton    10819: interface
                   10820:   selector if1sel1
                   10821:   selector if1sel2
                   10822: end-interface if1
1.20      pazsan   10823: 
1.78      anton    10824: object class
                   10825:   if1 implementation
                   10826:   selector cl1sel1
                   10827:   cell% inst-var cl1iv1
1.20      pazsan   10828: 
1.78      anton    10829: ' m1 overrides construct
                   10830: ' m2 overrides if1sel1
                   10831: ' m3 overrides if1sel2
                   10832: ' m4 overrides cl1sel2
                   10833: end-class cl1
1.20      pazsan   10834: 
1.78      anton    10835: create obj1 object dict-new drop
                   10836: create obj2 cl1    dict-new drop
                   10837: @end example
1.20      pazsan   10838: 
1.78      anton    10839: The data structure created by this code (including the data structure
                   10840: for @code{object}) is shown in the
                   10841: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
                   10842: @comment TODO add this diagram..
1.20      pazsan   10843: 
1.78      anton    10844: @node Objects Glossary,  , Objects Implementation, Objects
                   10845: @subsubsection @file{objects.fs} Glossary
                   10846: @cindex @file{objects.fs} Glossary
1.20      pazsan   10847: 
                   10848: 
1.78      anton    10849: doc---objects-bind
                   10850: doc---objects-<bind>
                   10851: doc---objects-bind'
                   10852: doc---objects-[bind]
                   10853: doc---objects-class
                   10854: doc---objects-class->map
                   10855: doc---objects-class-inst-size
                   10856: doc---objects-class-override!
1.79      anton    10857: doc---objects-class-previous
                   10858: doc---objects-class>order
1.78      anton    10859: doc---objects-construct
                   10860: doc---objects-current'
                   10861: doc---objects-[current]
                   10862: doc---objects-current-interface
                   10863: doc---objects-dict-new
                   10864: doc---objects-end-class
                   10865: doc---objects-end-class-noname
                   10866: doc---objects-end-interface
                   10867: doc---objects-end-interface-noname
                   10868: doc---objects-end-methods
                   10869: doc---objects-exitm
                   10870: doc---objects-heap-new
                   10871: doc---objects-implementation
                   10872: doc---objects-init-object
                   10873: doc---objects-inst-value
                   10874: doc---objects-inst-var
                   10875: doc---objects-interface
                   10876: doc---objects-m:
                   10877: doc---objects-:m
                   10878: doc---objects-;m
                   10879: doc---objects-method
                   10880: doc---objects-methods
                   10881: doc---objects-object
                   10882: doc---objects-overrides
                   10883: doc---objects-[parent]
                   10884: doc---objects-print
                   10885: doc---objects-protected
                   10886: doc---objects-public
                   10887: doc---objects-selector
                   10888: doc---objects-this
                   10889: doc---objects-<to-inst>
                   10890: doc---objects-[to-inst]
                   10891: doc---objects-to-this
                   10892: doc---objects-xt-new
1.20      pazsan   10893: 
                   10894: 
1.78      anton    10895: @c -------------------------------------------------------------
                   10896: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   10897: @subsection The @file{oof.fs} model
                   10898: @cindex oof
                   10899: @cindex object-oriented programming
1.20      pazsan   10900: 
1.78      anton    10901: @cindex @file{objects.fs}
                   10902: @cindex @file{oof.fs}
1.20      pazsan   10903: 
1.78      anton    10904: This section describes the @file{oof.fs} package.
1.20      pazsan   10905: 
1.78      anton    10906: The package described in this section has been used in bigFORTH since 1991, and
                   10907: used for two large applications: a chromatographic system used to
                   10908: create new medicaments, and a graphic user interface library (MINOS).
1.20      pazsan   10909: 
1.78      anton    10910: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   10911: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   10912: 10(2), 1994.
1.20      pazsan   10913: 
1.78      anton    10914: @menu
                   10915: * Properties of the OOF model::  
                   10916: * Basic OOF Usage::             
                   10917: * The OOF base class::          
                   10918: * Class Declaration::           
                   10919: * Class Implementation::        
                   10920: @end menu
1.20      pazsan   10921: 
1.78      anton    10922: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   10923: @subsubsection Properties of the @file{oof.fs} model
                   10924: @cindex @file{oof.fs} properties
1.20      pazsan   10925: 
1.78      anton    10926: @itemize @bullet
                   10927: @item
                   10928: This model combines object oriented programming with information
                   10929: hiding. It helps you writing large application, where scoping is
                   10930: necessary, because it provides class-oriented scoping.
1.20      pazsan   10931: 
1.78      anton    10932: @item
                   10933: Named objects, object pointers, and object arrays can be created,
                   10934: selector invocation uses the ``object selector'' syntax. Selector invocation
                   10935: to objects and/or selectors on the stack is a bit less convenient, but
                   10936: possible.
1.44      crook    10937: 
1.78      anton    10938: @item
                   10939: Selector invocation and instance variable usage of the active object is
                   10940: straightforward, since both make use of the active object.
1.44      crook    10941: 
1.78      anton    10942: @item
                   10943: Late binding is efficient and easy to use.
1.20      pazsan   10944: 
1.78      anton    10945: @item
                   10946: State-smart objects parse selectors. However, extensibility is provided
                   10947: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20      pazsan   10948: 
1.78      anton    10949: @item
                   10950: An implementation in ANS Forth is available.
1.20      pazsan   10951: 
1.78      anton    10952: @end itemize
1.23      crook    10953: 
                   10954: 
1.78      anton    10955: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   10956: @subsubsection Basic @file{oof.fs} Usage
                   10957: @cindex @file{oof.fs} usage
1.23      crook    10958: 
1.78      anton    10959: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23      crook    10960: 
1.78      anton    10961: You can define a class for graphical objects like this:
1.23      crook    10962: 
1.78      anton    10963: @cindex @code{class} usage
                   10964: @cindex @code{class;} usage
                   10965: @cindex @code{method} usage
                   10966: @example
                   10967: object class graphical \ "object" is the parent class
1.139     pazsan   10968:   method draw ( x y -- )
1.78      anton    10969: class;
                   10970: @end example
1.23      crook    10971: 
1.78      anton    10972: This code defines a class @code{graphical} with an
                   10973: operation @code{draw}.  We can perform the operation
                   10974: @code{draw} on any @code{graphical} object, e.g.:
1.23      crook    10975: 
1.78      anton    10976: @example
                   10977: 100 100 t-rex draw
                   10978: @end example
1.23      crook    10979: 
1.78      anton    10980: @noindent
                   10981: where @code{t-rex} is an object or object pointer, created with e.g.
                   10982: @code{graphical : t-rex}.
1.23      crook    10983: 
1.78      anton    10984: @cindex abstract class
                   10985: How do we create a graphical object? With the present definitions,
                   10986: we cannot create a useful graphical object. The class
                   10987: @code{graphical} describes graphical objects in general, but not
                   10988: any concrete graphical object type (C++ users would call it an
                   10989: @emph{abstract class}); e.g., there is no method for the selector
                   10990: @code{draw} in the class @code{graphical}.
1.23      crook    10991: 
1.78      anton    10992: For concrete graphical objects, we define child classes of the
                   10993: class @code{graphical}, e.g.:
1.23      crook    10994: 
1.78      anton    10995: @example
                   10996: graphical class circle \ "graphical" is the parent class
                   10997:   cell var circle-radius
                   10998: how:
                   10999:   : draw ( x y -- )
                   11000:     circle-radius @@ draw-circle ;
1.23      crook    11001: 
1.139     pazsan   11002:   : init ( n-radius -- )
1.78      anton    11003:     circle-radius ! ;
                   11004: class;
                   11005: @end example
1.1       anton    11006: 
1.78      anton    11007: Here we define a class @code{circle} as a child of @code{graphical},
                   11008: with a field @code{circle-radius}; it defines new methods for the
                   11009: selectors @code{draw} and @code{init} (@code{init} is defined in
                   11010: @code{object}, the parent class of @code{graphical}).
1.1       anton    11011: 
1.78      anton    11012: Now we can create a circle in the dictionary with:
1.1       anton    11013: 
1.78      anton    11014: @example
                   11015: 50 circle : my-circle
                   11016: @end example
1.21      crook    11017: 
1.78      anton    11018: @noindent
                   11019: @code{:} invokes @code{init}, thus initializing the field
                   11020: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   11021: with:
1.1       anton    11022: 
1.78      anton    11023: @example
                   11024: 100 100 my-circle draw
                   11025: @end example
1.1       anton    11026: 
1.78      anton    11027: @cindex selector invocation, restrictions
                   11028: @cindex class definition, restrictions
                   11029: Note: You can only invoke a selector if the receiving object belongs to
                   11030: the class where the selector was defined or one of its descendents;
                   11031: e.g., you can invoke @code{draw} only for objects belonging to
                   11032: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   11033: mechanism will check if you try to invoke a selector that is not
                   11034: defined in this class hierarchy, so you'll get an error at compilation
                   11035: time.
1.1       anton    11036: 
                   11037: 
1.78      anton    11038: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   11039: @subsubsection The @file{oof.fs} base class
                   11040: @cindex @file{oof.fs} base class
1.1       anton    11041: 
1.78      anton    11042: When you define a class, you have to specify a parent class.  So how do
                   11043: you start defining classes? There is one class available from the start:
                   11044: @code{object}. You have to use it as ancestor for all classes. It is the
                   11045: only class that has no parent. Classes are also objects, except that
                   11046: they don't have instance variables; class manipulation such as
                   11047: inheritance or changing definitions of a class is handled through
                   11048: selectors of the class @code{object}.
1.1       anton    11049: 
1.78      anton    11050: @code{object} provides a number of selectors:
1.1       anton    11051: 
1.78      anton    11052: @itemize @bullet
                   11053: @item
                   11054: @code{class} for subclassing, @code{definitions} to add definitions
                   11055: later on, and @code{class?} to get type informations (is the class a
                   11056: subclass of the class passed on the stack?).
1.1       anton    11057: 
1.78      anton    11058: doc---object-class
                   11059: doc---object-definitions
                   11060: doc---object-class?
1.1       anton    11061: 
                   11062: 
1.26      crook    11063: @item
1.78      anton    11064: @code{init} and @code{dispose} as constructor and destructor of the
                   11065: object. @code{init} is invocated after the object's memory is allocated,
                   11066: while @code{dispose} also handles deallocation. Thus if you redefine
                   11067: @code{dispose}, you have to call the parent's dispose with @code{super
                   11068: dispose}, too.
                   11069: 
                   11070: doc---object-init
                   11071: doc---object-dispose
                   11072: 
1.1       anton    11073: 
1.26      crook    11074: @item
1.78      anton    11075: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   11076: @code{[]} to create named and unnamed objects and object arrays or
                   11077: object pointers.
                   11078: 
                   11079: doc---object-new
                   11080: doc---object-new[]
                   11081: doc---object-:
                   11082: doc---object-ptr
                   11083: doc---object-asptr
                   11084: doc---object-[]
                   11085: 
1.1       anton    11086: 
1.26      crook    11087: @item
1.78      anton    11088: @code{::} and @code{super} for explicit scoping. You should use explicit
                   11089: scoping only for super classes or classes with the same set of instance
                   11090: variables. Explicitly-scoped selectors use early binding.
1.21      crook    11091: 
1.78      anton    11092: doc---object-::
                   11093: doc---object-super
1.21      crook    11094: 
                   11095: 
1.26      crook    11096: @item
1.78      anton    11097: @code{self} to get the address of the object
1.21      crook    11098: 
1.78      anton    11099: doc---object-self
1.21      crook    11100: 
                   11101: 
1.78      anton    11102: @item
                   11103: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   11104: pointers and instance defers.
1.21      crook    11105: 
1.78      anton    11106: doc---object-bind
                   11107: doc---object-bound
                   11108: doc---object-link
                   11109: doc---object-is
1.21      crook    11110: 
                   11111: 
1.78      anton    11112: @item
                   11113: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   11114: form the stack, and @code{postpone} to generate selector invocation code.
1.21      crook    11115: 
1.78      anton    11116: doc---object-'
                   11117: doc---object-postpone
1.21      crook    11118: 
                   11119: 
1.78      anton    11120: @item
                   11121: @code{with} and @code{endwith} to select the active object from the
                   11122: stack, and enable its scope. Using @code{with} and @code{endwith}
                   11123: also allows you to create code using selector @code{postpone} without being
                   11124: trapped by the state-smart objects.
1.21      crook    11125: 
1.78      anton    11126: doc---object-with
                   11127: doc---object-endwith
1.21      crook    11128: 
                   11129: 
1.78      anton    11130: @end itemize
1.21      crook    11131: 
1.78      anton    11132: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   11133: @subsubsection Class Declaration
                   11134: @cindex class declaration
1.21      crook    11135: 
1.78      anton    11136: @itemize @bullet
                   11137: @item
                   11138: Instance variables
1.21      crook    11139: 
1.78      anton    11140: doc---oof-var
1.21      crook    11141: 
                   11142: 
1.78      anton    11143: @item
                   11144: Object pointers
1.21      crook    11145: 
1.78      anton    11146: doc---oof-ptr
                   11147: doc---oof-asptr
1.21      crook    11148: 
                   11149: 
1.78      anton    11150: @item
                   11151: Instance defers
1.21      crook    11152: 
1.78      anton    11153: doc---oof-defer
1.21      crook    11154: 
                   11155: 
1.78      anton    11156: @item
                   11157: Method selectors
1.21      crook    11158: 
1.78      anton    11159: doc---oof-early
                   11160: doc---oof-method
1.21      crook    11161: 
                   11162: 
1.78      anton    11163: @item
                   11164: Class-wide variables
1.21      crook    11165: 
1.78      anton    11166: doc---oof-static
1.21      crook    11167: 
                   11168: 
1.78      anton    11169: @item
                   11170: End declaration
1.1       anton    11171: 
1.78      anton    11172: doc---oof-how:
                   11173: doc---oof-class;
1.21      crook    11174: 
                   11175: 
1.78      anton    11176: @end itemize
1.21      crook    11177: 
1.78      anton    11178: @c -------------------------------------------------------------
                   11179: @node Class Implementation,  , Class Declaration, OOF
                   11180: @subsubsection Class Implementation
                   11181: @cindex class implementation
1.21      crook    11182: 
1.78      anton    11183: @c -------------------------------------------------------------
                   11184: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   11185: @subsection The @file{mini-oof.fs} model
                   11186: @cindex mini-oof
1.21      crook    11187: 
1.78      anton    11188: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79      anton    11189: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78      anton    11190: and reduces to the bare minimum of features. This is based on a posting
                   11191: of Bernd Paysan in comp.lang.forth.
1.21      crook    11192: 
1.78      anton    11193: @menu
                   11194: * Basic Mini-OOF Usage::        
                   11195: * Mini-OOF Example::            
                   11196: * Mini-OOF Implementation::     
                   11197: @end menu
1.21      crook    11198: 
1.78      anton    11199: @c -------------------------------------------------------------
                   11200: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
                   11201: @subsubsection Basic @file{mini-oof.fs} Usage
                   11202: @cindex mini-oof usage
1.21      crook    11203: 
1.78      anton    11204: There is a base class (@code{class}, which allocates one cell for the
                   11205: object pointer) plus seven other words: to define a method, a variable,
                   11206: a class; to end a class, to resolve binding, to allocate an object and
                   11207: to compile a class method.
                   11208: @comment TODO better description of the last one
1.26      crook    11209: 
1.21      crook    11210: 
1.78      anton    11211: doc-object
                   11212: doc-method
                   11213: doc-var
                   11214: doc-class
                   11215: doc-end-class
                   11216: doc-defines
                   11217: doc-new
                   11218: doc-::
1.21      crook    11219: 
                   11220: 
                   11221: 
1.78      anton    11222: @c -------------------------------------------------------------
                   11223: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   11224: @subsubsection Mini-OOF Example
                   11225: @cindex mini-oof example
1.1       anton    11226: 
1.78      anton    11227: A short example shows how to use this package. This example, in slightly
                   11228: extended form, is supplied as @file{moof-exm.fs}
                   11229: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20      pazsan   11230: 
1.26      crook    11231: @example
1.78      anton    11232: object class
                   11233:   method init
                   11234:   method draw
                   11235: end-class graphical
1.26      crook    11236: @end example
1.20      pazsan   11237: 
1.78      anton    11238: This code defines a class @code{graphical} with an
                   11239: operation @code{draw}.  We can perform the operation
                   11240: @code{draw} on any @code{graphical} object, e.g.:
1.20      pazsan   11241: 
1.26      crook    11242: @example
1.78      anton    11243: 100 100 t-rex draw
1.26      crook    11244: @end example
1.12      anton    11245: 
1.78      anton    11246: where @code{t-rex} is an object or object pointer, created with e.g.
                   11247: @code{graphical new Constant t-rex}.
1.12      anton    11248: 
1.78      anton    11249: For concrete graphical objects, we define child classes of the
                   11250: class @code{graphical}, e.g.:
1.12      anton    11251: 
1.26      crook    11252: @example
                   11253: graphical class
1.78      anton    11254:   cell var circle-radius
                   11255: end-class circle \ "graphical" is the parent class
1.12      anton    11256: 
1.78      anton    11257: :noname ( x y -- )
                   11258:   circle-radius @@ draw-circle ; circle defines draw
                   11259: :noname ( r -- )
                   11260:   circle-radius ! ; circle defines init
                   11261: @end example
1.12      anton    11262: 
1.78      anton    11263: There is no implicit init method, so we have to define one. The creation
                   11264: code of the object now has to call init explicitely.
1.21      crook    11265: 
1.78      anton    11266: @example
                   11267: circle new Constant my-circle
                   11268: 50 my-circle init
1.12      anton    11269: @end example
                   11270: 
1.78      anton    11271: It is also possible to add a function to create named objects with
                   11272: automatic call of @code{init}, given that all objects have @code{init}
                   11273: on the same place:
1.38      anton    11274: 
1.78      anton    11275: @example
                   11276: : new: ( .. o "name" -- )
                   11277:     new dup Constant init ;
                   11278: 80 circle new: large-circle
                   11279: @end example
1.12      anton    11280: 
1.78      anton    11281: We can draw this new circle at (100,100) with:
1.12      anton    11282: 
1.78      anton    11283: @example
                   11284: 100 100 my-circle draw
                   11285: @end example
1.12      anton    11286: 
1.78      anton    11287: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
                   11288: @subsubsection @file{mini-oof.fs} Implementation
1.12      anton    11289: 
1.78      anton    11290: Object-oriented systems with late binding typically use a
                   11291: ``vtable''-approach: the first variable in each object is a pointer to a
                   11292: table, which contains the methods as function pointers. The vtable
                   11293: may also contain other information.
1.12      anton    11294: 
1.79      anton    11295: So first, let's declare selectors:
1.37      anton    11296: 
                   11297: @example
1.79      anton    11298: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
1.78      anton    11299:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
                   11300: @end example
1.37      anton    11301: 
1.79      anton    11302: During selector declaration, the number of selectors and instance
                   11303: variables is on the stack (in address units). @code{method} creates one
                   11304: selector and increments the selector number. To execute a selector, it
1.78      anton    11305: takes the object, fetches the vtable pointer, adds the offset, and
1.79      anton    11306: executes the method @i{xt} stored there. Each selector takes the object
                   11307: it is invoked with as top of stack parameter; it passes the parameters
                   11308: (including the object) unchanged to the appropriate method which should
1.78      anton    11309: consume that object.
1.37      anton    11310: 
1.78      anton    11311: Now, we also have to declare instance variables
1.37      anton    11312: 
1.78      anton    11313: @example
1.79      anton    11314: : var ( m v size "name" -- m v' ) Create  over , +
1.78      anton    11315:   DOES> ( o -- addr ) @@ + ;
1.37      anton    11316: @end example
                   11317: 
1.78      anton    11318: As before, a word is created with the current offset. Instance
                   11319: variables can have different sizes (cells, floats, doubles, chars), so
                   11320: all we do is take the size and add it to the offset. If your machine
                   11321: has alignment restrictions, put the proper @code{aligned} or
                   11322: @code{faligned} before the variable, to adjust the variable
                   11323: offset. That's why it is on the top of stack.
1.37      anton    11324: 
1.78      anton    11325: We need a starting point (the base object) and some syntactic sugar:
1.37      anton    11326: 
1.78      anton    11327: @example
                   11328: Create object  1 cells , 2 cells ,
1.79      anton    11329: : class ( class -- class selectors vars ) dup 2@@ ;
1.78      anton    11330: @end example
1.12      anton    11331: 
1.78      anton    11332: For inheritance, the vtable of the parent object has to be
                   11333: copied when a new, derived class is declared. This gives all the
                   11334: methods of the parent class, which can be overridden, though.
1.12      anton    11335: 
1.78      anton    11336: @example
1.79      anton    11337: : end-class  ( class selectors vars "name" -- )
1.78      anton    11338:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   11339:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
                   11340: @end example
1.12      anton    11341: 
1.78      anton    11342: The first line creates the vtable, initialized with
                   11343: @code{noop}s. The second line is the inheritance mechanism, it
                   11344: copies the xts from the parent vtable.
1.12      anton    11345: 
1.78      anton    11346: We still have no way to define new methods, let's do that now:
1.12      anton    11347: 
1.26      crook    11348: @example
1.79      anton    11349: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78      anton    11350: @end example
1.12      anton    11351: 
1.78      anton    11352: To allocate a new object, we need a word, too:
1.12      anton    11353: 
1.78      anton    11354: @example
                   11355: : new ( class -- o )  here over @@ allot swap over ! ;
1.12      anton    11356: @end example
                   11357: 
1.78      anton    11358: Sometimes derived classes want to access the method of the
                   11359: parent object. There are two ways to achieve this with Mini-OOF:
                   11360: first, you could use named words, and second, you could look up the
                   11361: vtable of the parent object.
1.12      anton    11362: 
1.78      anton    11363: @example
                   11364: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
                   11365: @end example
1.12      anton    11366: 
                   11367: 
1.78      anton    11368: Nothing can be more confusing than a good example, so here is
                   11369: one. First let's declare a text object (called
                   11370: @code{button}), that stores text and position:
1.12      anton    11371: 
1.78      anton    11372: @example
                   11373: object class
                   11374:   cell var text
                   11375:   cell var len
                   11376:   cell var x
                   11377:   cell var y
                   11378:   method init
                   11379:   method draw
                   11380: end-class button
                   11381: @end example
1.12      anton    11382: 
1.78      anton    11383: @noindent
                   11384: Now, implement the two methods, @code{draw} and @code{init}:
1.21      crook    11385: 
1.26      crook    11386: @example
1.78      anton    11387: :noname ( o -- )
                   11388:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
                   11389:  button defines draw
                   11390: :noname ( addr u o -- )
                   11391:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
                   11392:  button defines init
1.26      crook    11393: @end example
1.12      anton    11394: 
1.78      anton    11395: @noindent
                   11396: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79      anton    11397: new data and no new selectors:
1.78      anton    11398: 
                   11399: @example
                   11400: button class
                   11401: end-class bold-button
1.12      anton    11402: 
1.78      anton    11403: : bold   27 emit ." [1m" ;
                   11404: : normal 27 emit ." [0m" ;
                   11405: @end example
1.1       anton    11406: 
1.78      anton    11407: @noindent
                   11408: The class @code{bold-button} has a different draw method to
                   11409: @code{button}, but the new method is defined in terms of the draw method
                   11410: for @code{button}:
1.20      pazsan   11411: 
1.78      anton    11412: @example
                   11413: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   11414: @end example
1.21      crook    11415: 
1.78      anton    11416: @noindent
1.79      anton    11417: Finally, create two objects and apply selectors:
1.21      crook    11418: 
1.26      crook    11419: @example
1.78      anton    11420: button new Constant foo
                   11421: s" thin foo" foo init
                   11422: page
                   11423: foo draw
                   11424: bold-button new Constant bar
                   11425: s" fat bar" bar init
                   11426: 1 bar y !
                   11427: bar draw
1.26      crook    11428: @end example
1.21      crook    11429: 
                   11430: 
1.78      anton    11431: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
                   11432: @subsection Comparison with other object models
                   11433: @cindex comparison of object models
                   11434: @cindex object models, comparison
                   11435: 
                   11436: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   11437: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   11438: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   11439: relation of the object models described here to two well-known and two
                   11440: closely-related (by the use of method maps) models.  Andras Zsoter
                   11441: helped us with this section.
                   11442: 
                   11443: @cindex Neon model
                   11444: The most popular model currently seems to be the Neon model (see
                   11445: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   11446: 1997) by Andrew McKewan) but this model has a number of limitations
                   11447: @footnote{A longer version of this critique can be
                   11448: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   11449: Dimensions, May 1997) by Anton Ertl.}:
                   11450: 
                   11451: @itemize @bullet
                   11452: @item
                   11453: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
                   11454: to pass objects on the stack.
1.21      crook    11455: 
1.78      anton    11456: @item
                   11457: It requires that the selector parses the input stream (at
1.79      anton    11458: compile time); this leads to reduced extensibility and to bugs that are
1.78      anton    11459: hard to find.
1.21      crook    11460: 
1.78      anton    11461: @item
1.79      anton    11462: It allows using every selector on every object; this eliminates the
                   11463: need for interfaces, but makes it harder to create efficient
                   11464: implementations.
1.78      anton    11465: @end itemize
1.21      crook    11466: 
1.78      anton    11467: @cindex Pountain's object-oriented model
                   11468: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   11469: Press, London, 1987) by Dick Pountain. However, it is not really about
                   11470: object-oriented programming, because it hardly deals with late
                   11471: binding. Instead, it focuses on features like information hiding and
                   11472: overloading that are characteristic of modular languages like Ada (83).
1.26      crook    11473: 
1.78      anton    11474: @cindex Zsoter's object-oriented model
1.79      anton    11475: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
                   11476: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
                   11477: describes a model that makes heavy use of an active object (like
                   11478: @code{this} in @file{objects.fs}): The active object is not only used
                   11479: for accessing all fields, but also specifies the receiving object of
                   11480: every selector invocation; you have to change the active object
                   11481: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
                   11482: changes more or less implicitly at @code{m: ... ;m}. Such a change at
                   11483: the method entry point is unnecessary with Zsoter's model, because the
                   11484: receiving object is the active object already. On the other hand, the
                   11485: explicit change is absolutely necessary in that model, because otherwise
                   11486: no one could ever change the active object. An ANS Forth implementation
                   11487: of this model is available through
                   11488: @uref{http://www.forth.org/oopf.html}.
1.21      crook    11489: 
1.78      anton    11490: @cindex @file{oof.fs}, differences to other models
                   11491: The @file{oof.fs} model combines information hiding and overloading
                   11492: resolution (by keeping names in various word lists) with object-oriented
                   11493: programming. It sets the active object implicitly on method entry, but
                   11494: also allows explicit changing (with @code{>o...o>} or with
                   11495: @code{with...endwith}). It uses parsing and state-smart objects and
                   11496: classes for resolving overloading and for early binding: the object or
                   11497: class parses the selector and determines the method from this. If the
                   11498: selector is not parsed by an object or class, it performs a call to the
                   11499: selector for the active object (late binding), like Zsoter's model.
                   11500: Fields are always accessed through the active object. The big
                   11501: disadvantage of this model is the parsing and the state-smartness, which
                   11502: reduces extensibility and increases the opportunities for subtle bugs;
                   11503: essentially, you are only safe if you never tick or @code{postpone} an
                   11504: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21      crook    11505: 
1.78      anton    11506: @cindex @file{mini-oof.fs}, differences to other models
                   11507: The @file{mini-oof.fs} model is quite similar to a very stripped-down
                   11508: version of the @file{objects.fs} model, but syntactically it is a
                   11509: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21      crook    11510: 
                   11511: 
1.78      anton    11512: @c -------------------------------------------------------------
1.150     anton    11513: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78      anton    11514: @section Programming Tools
                   11515: @cindex programming tools
1.21      crook    11516: 
1.78      anton    11517: @c !! move this and assembler down below OO stuff.
1.21      crook    11518: 
1.78      anton    11519: @menu
1.150     anton    11520: * Examining::                   Data and Code.
                   11521: * Forgetting words::            Usually before reloading.
1.78      anton    11522: * Debugging::                   Simple and quick.
                   11523: * Assertions::                  Making your programs self-checking.
                   11524: * Singlestep Debugger::         Executing your program word by word.
                   11525: @end menu
1.21      crook    11526: 
1.78      anton    11527: @node Examining, Forgetting words, Programming Tools, Programming Tools
                   11528: @subsection Examining data and code
                   11529: @cindex examining data and code
                   11530: @cindex data examination
                   11531: @cindex code examination
1.44      crook    11532: 
1.78      anton    11533: The following words inspect the stack non-destructively:
1.21      crook    11534: 
1.78      anton    11535: doc-.s
                   11536: doc-f.s
1.158     anton    11537: doc-maxdepth-.s
1.44      crook    11538: 
1.78      anton    11539: There is a word @code{.r} but it does @i{not} display the return stack!
                   11540: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21      crook    11541: 
1.78      anton    11542: doc-depth
                   11543: doc-fdepth
                   11544: doc-clearstack
1.124     anton    11545: doc-clearstacks
1.21      crook    11546: 
1.78      anton    11547: The following words inspect memory.
1.21      crook    11548: 
1.78      anton    11549: doc-?
                   11550: doc-dump
1.21      crook    11551: 
1.78      anton    11552: And finally, @code{see} allows to inspect code:
1.21      crook    11553: 
1.78      anton    11554: doc-see
                   11555: doc-xt-see
1.111     anton    11556: doc-simple-see
                   11557: doc-simple-see-range
1.21      crook    11558: 
1.78      anton    11559: @node Forgetting words, Debugging, Examining, Programming Tools
                   11560: @subsection Forgetting words
                   11561: @cindex words, forgetting
                   11562: @cindex forgeting words
1.21      crook    11563: 
1.78      anton    11564: @c  anton: other, maybe better places for this subsection: Defining Words;
                   11565: @c  Dictionary allocation.  At least a reference should be there.
1.21      crook    11566: 
1.78      anton    11567: Forth allows you to forget words (and everything that was alloted in the
                   11568: dictonary after them) in a LIFO manner.
1.21      crook    11569: 
1.78      anton    11570: doc-marker
1.21      crook    11571: 
1.78      anton    11572: The most common use of this feature is during progam development: when
                   11573: you change a source file, forget all the words it defined and load it
                   11574: again (since you also forget everything defined after the source file
                   11575: was loaded, you have to reload that, too).  Note that effects like
                   11576: storing to variables and destroyed system words are not undone when you
                   11577: forget words.  With a system like Gforth, that is fast enough at
                   11578: starting up and compiling, I find it more convenient to exit and restart
                   11579: Gforth, as this gives me a clean slate.
1.21      crook    11580: 
1.78      anton    11581: Here's an example of using @code{marker} at the start of a source file
                   11582: that you are debugging; it ensures that you only ever have one copy of
                   11583: the file's definitions compiled at any time:
1.21      crook    11584: 
1.78      anton    11585: @example
                   11586: [IFDEF] my-code
                   11587:     my-code
                   11588: [ENDIF]
1.26      crook    11589: 
1.78      anton    11590: marker my-code
                   11591: init-included-files
1.21      crook    11592: 
1.78      anton    11593: \ .. definitions start here
                   11594: \ .
                   11595: \ .
                   11596: \ end
                   11597: @end example
1.21      crook    11598: 
1.26      crook    11599: 
1.78      anton    11600: @node Debugging, Assertions, Forgetting words, Programming Tools
                   11601: @subsection Debugging
                   11602: @cindex debugging
1.21      crook    11603: 
1.78      anton    11604: Languages with a slow edit/compile/link/test development loop tend to
                   11605: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21      crook    11606: 
1.78      anton    11607: A much better (faster) way in fast-compiling languages is to add
                   11608: printing code at well-selected places, let the program run, look at
                   11609: the output, see where things went wrong, add more printing code, etc.,
                   11610: until the bug is found.
1.21      crook    11611: 
1.78      anton    11612: The simple debugging aids provided in @file{debugs.fs}
                   11613: are meant to support this style of debugging.
1.21      crook    11614: 
1.78      anton    11615: The word @code{~~} prints debugging information (by default the source
                   11616: location and the stack contents). It is easy to insert. If you use Emacs
                   11617: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   11618: query-replace them with nothing). The deferred words
1.101     anton    11619: @code{printdebugdata} and @code{.debugline} control the output of
1.78      anton    11620: @code{~~}. The default source location output format works well with
                   11621: Emacs' compilation mode, so you can step through the program at the
                   11622: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   11623: is that you can step in any direction and you know where the crash has
                   11624: happened or where the strange data has occurred).
1.21      crook    11625: 
1.78      anton    11626: doc-~~
                   11627: doc-printdebugdata
1.101     anton    11628: doc-.debugline
1.21      crook    11629: 
1.106     anton    11630: @cindex filenames in @code{~~} output
                   11631: @code{~~} (and assertions) will usually print the wrong file name if a
                   11632: marker is executed in the same file after their occurance.  They will
                   11633: print @samp{*somewhere*} as file name if a marker is executed in the
                   11634: same file before their occurance.
                   11635: 
                   11636: 
1.78      anton    11637: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   11638: @subsection Assertions
                   11639: @cindex assertions
1.21      crook    11640: 
1.78      anton    11641: It is a good idea to make your programs self-checking, especially if you
                   11642: make an assumption that may become invalid during maintenance (for
                   11643: example, that a certain field of a data structure is never zero). Gforth
                   11644: supports @dfn{assertions} for this purpose. They are used like this:
1.21      crook    11645: 
                   11646: @example
1.78      anton    11647: assert( @i{flag} )
1.26      crook    11648: @end example
                   11649: 
1.78      anton    11650: The code between @code{assert(} and @code{)} should compute a flag, that
                   11651: should be true if everything is alright and false otherwise. It should
                   11652: not change anything else on the stack. The overall stack effect of the
                   11653: assertion is @code{( -- )}. E.g.
1.21      crook    11654: 
1.26      crook    11655: @example
1.78      anton    11656: assert( 1 1 + 2 = ) \ what we learn in school
                   11657: assert( dup 0<> ) \ assert that the top of stack is not zero
                   11658: assert( false ) \ this code should not be reached
1.21      crook    11659: @end example
                   11660: 
1.78      anton    11661: The need for assertions is different at different times. During
                   11662: debugging, we want more checking, in production we sometimes care more
                   11663: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   11664: becomes a comment. Depending on the importance of an assertion and the
                   11665: time it takes to check it, you may want to turn off some assertions and
                   11666: keep others turned on. Gforth provides several levels of assertions for
                   11667: this purpose:
                   11668: 
                   11669: 
                   11670: doc-assert0(
                   11671: doc-assert1(
                   11672: doc-assert2(
                   11673: doc-assert3(
                   11674: doc-assert(
                   11675: doc-)
1.21      crook    11676: 
                   11677: 
1.78      anton    11678: The variable @code{assert-level} specifies the highest assertions that
                   11679: are turned on. I.e., at the default @code{assert-level} of one,
                   11680: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   11681: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26      crook    11682: 
1.78      anton    11683: The value of @code{assert-level} is evaluated at compile-time, not at
                   11684: run-time. Therefore you cannot turn assertions on or off at run-time;
                   11685: you have to set the @code{assert-level} appropriately before compiling a
                   11686: piece of code. You can compile different pieces of code at different
                   11687: @code{assert-level}s (e.g., a trusted library at level 1 and
                   11688: newly-written code at level 3).
1.26      crook    11689: 
                   11690: 
1.78      anton    11691: doc-assert-level
1.26      crook    11692: 
                   11693: 
1.78      anton    11694: If an assertion fails, a message compatible with Emacs' compilation mode
                   11695: is produced and the execution is aborted (currently with @code{ABORT"}.
                   11696: If there is interest, we will introduce a special throw code. But if you
                   11697: intend to @code{catch} a specific condition, using @code{throw} is
                   11698: probably more appropriate than an assertion).
1.106     anton    11699: 
                   11700: @cindex filenames in assertion output
                   11701: Assertions (and @code{~~}) will usually print the wrong file name if a
                   11702: marker is executed in the same file after their occurance.  They will
                   11703: print @samp{*somewhere*} as file name if a marker is executed in the
                   11704: same file before their occurance.
1.44      crook    11705: 
1.78      anton    11706: Definitions in ANS Forth for these assertion words are provided
                   11707: in @file{compat/assert.fs}.
1.26      crook    11708: 
1.44      crook    11709: 
1.78      anton    11710: @node Singlestep Debugger,  , Assertions, Programming Tools
                   11711: @subsection Singlestep Debugger
                   11712: @cindex singlestep Debugger
                   11713: @cindex debugging Singlestep
1.44      crook    11714: 
1.159     anton    11715: The singlestep debugger works only with the engine @code{gforth-ditc}.
1.112     anton    11716: 
1.78      anton    11717: When you create a new word there's often the need to check whether it
                   11718: behaves correctly or not. You can do this by typing @code{dbg
                   11719: badword}. A debug session might look like this:
1.26      crook    11720: 
1.78      anton    11721: @example
                   11722: : badword 0 DO i . LOOP ;  ok
                   11723: 2 dbg badword 
                   11724: : badword  
                   11725: Scanning code...
1.44      crook    11726: 
1.78      anton    11727: Nesting debugger ready!
1.44      crook    11728: 
1.78      anton    11729: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   11730: 400D4740  8049F68 DO             -> [ 0 ] 
                   11731: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   11732: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   11733: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   11734: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   11735: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   11736: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   11737: 400D4758  804B384 ;              ->  ok
                   11738: @end example
1.21      crook    11739: 
1.78      anton    11740: Each line displayed is one step. You always have to hit return to
                   11741: execute the next word that is displayed. If you don't want to execute
                   11742: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   11743: an overview what keys are available:
1.44      crook    11744: 
1.78      anton    11745: @table @i
1.44      crook    11746: 
1.78      anton    11747: @item @key{RET}
                   11748: Next; Execute the next word.
1.21      crook    11749: 
1.78      anton    11750: @item n
                   11751: Nest; Single step through next word.
1.44      crook    11752: 
1.78      anton    11753: @item u
                   11754: Unnest; Stop debugging and execute rest of word. If we got to this word
                   11755: with nest, continue debugging with the calling word.
1.44      crook    11756: 
1.78      anton    11757: @item d
                   11758: Done; Stop debugging and execute rest.
1.21      crook    11759: 
1.78      anton    11760: @item s
                   11761: Stop; Abort immediately.
1.44      crook    11762: 
1.78      anton    11763: @end table
1.44      crook    11764: 
1.78      anton    11765: Debugging large application with this mechanism is very difficult, because
                   11766: you have to nest very deeply into the program before the interesting part
                   11767: begins. This takes a lot of time. 
1.26      crook    11768: 
1.78      anton    11769: To do it more directly put a @code{BREAK:} command into your source code.
                   11770: When program execution reaches @code{BREAK:} the single step debugger is
                   11771: invoked and you have all the features described above.
1.44      crook    11772: 
1.78      anton    11773: If you have more than one part to debug it is useful to know where the
                   11774: program has stopped at the moment. You can do this by the 
                   11775: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   11776: string is typed out when the ``breakpoint'' is reached.
1.44      crook    11777: 
1.26      crook    11778: 
1.78      anton    11779: doc-dbg
                   11780: doc-break:
                   11781: doc-break"
1.44      crook    11782: 
1.150     anton    11783: @c ------------------------------------------------------------
                   11784: @node C Interface, Assembler and Code Words, Programming Tools, Words
                   11785: @section C Interface
                   11786: @cindex C interface
                   11787: @cindex foreign language interface
                   11788: @cindex interface to C functions
                   11789: 
                   11790: Note that the C interface is not yet complete; a better way of
                   11791: declaring C functions is planned, as well as a way of declaring
                   11792: structs, unions, and their fields.
                   11793: 
                   11794: @menu
                   11795: * Calling C Functions::         
                   11796: * Declaring C Functions::       
                   11797: * Callbacks::                   
1.155     anton    11798: * Low-Level C Interface Words::  
1.150     anton    11799: @end menu
                   11800: 
1.151     pazsan   11801: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150     anton    11802: @subsection Calling C functions
1.155     anton    11803: @cindex C functions, calls to
                   11804: @cindex calling C functions
1.150     anton    11805: 
1.151     pazsan   11806: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150     anton    11807: can call it as follows: You push the arguments on the stack(s), and
                   11808: then call the word for the C function.  The arguments have to be
                   11809: pushed in the same order as the arguments appear in the C
                   11810: documentation (i.e., the first argument is deepest on the stack).
                   11811: Integer and pointer arguments have to be pushed on the data stack,
                   11812: floating-point arguments on the FP stack; these arguments are consumed
1.155     anton    11813: by the called C function.
1.150     anton    11814: 
1.155     anton    11815: On returning from the C function, the return value, if any, resides on
                   11816: the appropriate stack: an integer return value is pushed on the data
                   11817: stack, an FP return value on the FP stack, and a void return value
                   11818: results in not pushing anything.  Note that most C functions have a
                   11819: return value, even if that is often not used in C; in Forth, you have
                   11820: to @code{drop} this return value explicitly if you do not use it.
1.150     anton    11821: 
                   11822: By default, an integer argument or return value corresponds to a
                   11823: single cell, and a floating-point argument or return value corresponds
                   11824: to a Forth float value; the C interface performs the appropriate
                   11825: conversions where necessary, on a best-effort basis (in some cases,
                   11826: there may be some loss).
                   11827: 
                   11828: As an example, consider the POSIX function @code{lseek()}:
                   11829: 
                   11830: @example
                   11831: off_t lseek(int fd, off_t offset, int whence);
                   11832: @end example
                   11833: 
                   11834: This function takes three integer arguments, and returns an integer
                   11835: argument, so a Forth call for setting the current file offset to the
                   11836: start of the file could look like this:
                   11837: 
                   11838: @example
                   11839: fd @@ 0 SEEK_SET lseek -1 = if
                   11840:   ... \ error handling
                   11841: then
                   11842: @end example
                   11843: 
                   11844: You might be worried that an @code{off_t} does not fit into a cell, so
                   11845: you could not pass larger offsets to lseek, and might get only a part
1.155     anton    11846: of the return values.  In that case, in your declaration of the
                   11847: function (@pxref{Declaring C Functions}) you should declare it to use
                   11848: double-cells for the off_t argument and return value, and maybe give
                   11849: the resulting Forth word a different name, like @code{dlseek}; the
                   11850: result could be called like this:
1.150     anton    11851: 
                   11852: @example
                   11853: fd @@ 0. SEEK_SET dlseek -1. d= if
                   11854:   ... \ error handling
                   11855: then
                   11856: @end example
                   11857: 
                   11858: Passing and returning structs or unions is currently not supported by
                   11859: our interface@footnote{If you know the calling convention of your C
                   11860: compiler, you usually can call such functions in some way, but that
                   11861: way is usually not portable between platforms, and sometimes not even
                   11862: between C compilers.}.
                   11863: 
                   11864: Calling functions with a variable number of arguments (e.g.,
                   11865: @code{printf()}) is currently only supported by having you declare one
                   11866: function-calling word for each argument pattern, and calling the
                   11867: appropriate word for the desired pattern.
                   11868: 
1.155     anton    11869: 
1.151     pazsan   11870: @node Declaring C Functions, Callbacks, Calling C Functions, C Interface
1.150     anton    11871: @subsection Declaring C Functions
1.155     anton    11872: @cindex C functions, declarations
                   11873: @cindex declaring C functions
1.150     anton    11874: 
                   11875: Before you can call @code{lseek} or @code{dlseek}, you have to declare
                   11876: it.  You have to look up in your system what the concrete type for the
                   11877: abstract type @code{off_t} is; let's assume it is @code{long}.  Then
                   11878: the declarations for these words are:
                   11879: 
                   11880: @example
                   11881: library libc libc.so.6
                   11882: libc lseek  int  long int  (long) lseek ( fd noffset whence -- noffset2 )
                   11883: libc dlseek int dlong int (dlong) lseek ( fd doffset whence -- doffset2 ) 
                   11884: @end example
                   11885: 
                   11886: The first line defines a Forth word @code{libc} for accessing the C
                   11887: functions in the shared library @file{libc.so.6} (the name of the
                   11888: shared library depends on the library and the OS; this example is the
                   11889: standard C library (containing most of the standard C and Unix
                   11890: functions) for GNU/Linux systems since about 1998).
                   11891: 
                   11892: The next two lines define two Forth words for the same C function
                   11893: @code{lseek()}; the middle line defines @code{lseek ( n1 n2 n3 -- n
1.155     anton    11894: )}, and the last line defines @code{dlseek ( n1 d2 n3 -- d )}.
1.150     anton    11895: 
                   11896: As you can see, the declarations are relatively platform-dependent
                   11897: (e.g., on one platform @code{off_t} may be a @code{long}, whereas on
                   11898: another platform it may be a @code{long long}; actually, in this case
                   11899: you can have this difference even on the same platform), while the
                   11900: resulting function-calling words are platform-independent, and calls
                   11901: to them are portable.
                   11902: 
                   11903: At some point in the future this interface will be superseded by a
                   11904: more convenient one with fewer portability issues.  But the resulting
1.155     anton    11905: words for calling the C function will still have the same interface,
1.156     anton    11906: so you will not need to change the calls.
1.155     anton    11907: 
                   11908: Anyway, here are the words for the current interface:
1.150     anton    11909: 
1.155     anton    11910: doc-library
                   11911: doc-int
                   11912: doc-dint
                   11913: doc-uint
                   11914: doc-udint
                   11915: doc-long
                   11916: doc-dlong
                   11917: doc-ulong
                   11918: doc-udlong
                   11919: doc-longlong
                   11920: doc-dlonglong
                   11921: doc-ulonglong
                   11922: doc-udlonglong
1.156     anton    11923: doc-ptr
1.155     anton    11924: doc-cfloat
                   11925: doc-cdouble
                   11926: doc-clongdouble
                   11927: doc-(int)
                   11928: doc-(dint)
                   11929: doc-(uint)
                   11930: doc-(udint)
                   11931: doc-(long)
                   11932: doc-(dlong)
                   11933: doc-(ulong)
                   11934: doc-(udlong)
                   11935: doc-(longlong)
                   11936: doc-(dlonglong)
                   11937: doc-(ulonglong)
                   11938: doc-(udlonglong)
1.156     anton    11939: doc-(ptr)
1.155     anton    11940: doc-(cfloat)
                   11941: doc-(cdouble)
                   11942: doc-(clongdouble)
1.150     anton    11943: 
1.155     anton    11944: 
                   11945: @node Callbacks, Low-Level C Interface Words, Declaring C Functions, C Interface
1.150     anton    11946: @subsection Callbacks
1.155     anton    11947: @cindex Callback functions written in Forth
                   11948: @cindex C function pointers to Forth words
                   11949: 
                   11950: In some cases you have to pass a function pointer to a C function,
                   11951: i.e., the library wants to call back to your application (and the
                   11952: pointed-to function is called a callback function).  You can pass the
                   11953: address of an existing C function (that you get with @code{lib-sym},
                   11954: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
                   11955: function, you probably want to define the function as a Forth word.
                   11956: 
                   11957: !!!
                   11958: @c I don't understand the existing callback interface from the example - anton
                   11959: 
                   11960: doc-callback
                   11961: doc-callback;
                   11962: doc-fptr
1.150     anton    11963: 
1.165     anton    11964: 
                   11965: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
                   11966: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
                   11967: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
                   11968: @c > > C-Funktionsadresse auf dem TOS).
                   11969: @c >
                   11970: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
                   11971: @c > gesehen habe, wozu das gut ist.
                   11972: @c 
                   11973: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch 
                   11974: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen 
                   11975: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit 
                   11976: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte 
                   11977: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit 
                   11978: @c demselben Prototyp.
                   11979: 
                   11980: 
1.155     anton    11981: @node Low-Level C Interface Words,  , Callbacks, C Interface
                   11982: @subsection Low-Level C Interface Words
1.44      crook    11983: 
1.155     anton    11984: doc-open-lib
                   11985: doc-lib-sym
1.26      crook    11986: 
1.78      anton    11987: @c -------------------------------------------------------------
1.150     anton    11988: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78      anton    11989: @section Assembler and Code Words
                   11990: @cindex assembler
                   11991: @cindex code words
1.44      crook    11992: 
1.78      anton    11993: @menu
                   11994: * Code and ;code::              
                   11995: * Common Assembler::            Assembler Syntax
                   11996: * Common Disassembler::         
                   11997: * 386 Assembler::               Deviations and special cases
                   11998: * Alpha Assembler::             Deviations and special cases
                   11999: * MIPS assembler::              Deviations and special cases
1.161     anton    12000: * PowerPC assembler::           Deviations and special cases
1.78      anton    12001: * Other assemblers::            How to write them
                   12002: @end menu
1.21      crook    12003: 
1.78      anton    12004: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
                   12005: @subsection @code{Code} and @code{;code}
1.26      crook    12006: 
1.78      anton    12007: Gforth provides some words for defining primitives (words written in
                   12008: machine code), and for defining the machine-code equivalent of
                   12009: @code{DOES>}-based defining words. However, the machine-independent
                   12010: nature of Gforth poses a few problems: First of all, Gforth runs on
                   12011: several architectures, so it can provide no standard assembler. What's
                   12012: worse is that the register allocation not only depends on the processor,
                   12013: but also on the @code{gcc} version and options used.
1.44      crook    12014: 
1.78      anton    12015: The words that Gforth offers encapsulate some system dependences (e.g.,
                   12016: the header structure), so a system-independent assembler may be used in
                   12017: Gforth. If you do not have an assembler, you can compile machine code
                   12018: directly with @code{,} and @code{c,}@footnote{This isn't portable,
                   12019: because these words emit stuff in @i{data} space; it works because
                   12020: Gforth has unified code/data spaces. Assembler isn't likely to be
                   12021: portable anyway.}.
1.21      crook    12022: 
1.44      crook    12023: 
1.78      anton    12024: doc-assembler
                   12025: doc-init-asm
                   12026: doc-code
                   12027: doc-end-code
                   12028: doc-;code
                   12029: doc-flush-icache
1.44      crook    12030: 
1.21      crook    12031: 
1.78      anton    12032: If @code{flush-icache} does not work correctly, @code{code} words
                   12033: etc. will not work (reliably), either.
1.44      crook    12034: 
1.78      anton    12035: The typical usage of these @code{code} words can be shown most easily by
                   12036: analogy to the equivalent high-level defining words:
1.44      crook    12037: 
1.78      anton    12038: @example
                   12039: : foo                              code foo
                   12040:    <high-level Forth words>              <assembler>
                   12041: ;                                  end-code
                   12042:                                 
                   12043: : bar                              : bar
                   12044:    <high-level Forth words>           <high-level Forth words>
                   12045:    CREATE                             CREATE
                   12046:       <high-level Forth words>           <high-level Forth words>
                   12047:    DOES>                              ;code
                   12048:       <high-level Forth words>           <assembler>
                   12049: ;                                  end-code
                   12050: @end example
1.21      crook    12051: 
1.78      anton    12052: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44      crook    12053: 
1.78      anton    12054: @cindex registers of the inner interpreter
                   12055: In the assembly code you will want to refer to the inner interpreter's
                   12056: registers (e.g., the data stack pointer) and you may want to use other
                   12057: registers for temporary storage. Unfortunately, the register allocation
                   12058: is installation-dependent.
1.44      crook    12059: 
1.78      anton    12060: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100     anton    12061: (return stack pointer) may be in different places in @code{gforth} and
                   12062: @code{gforth-fast}, or different installations.  This means that you
                   12063: cannot write a @code{NEXT} routine that works reliably on both versions
                   12064: or different installations; so for doing @code{NEXT}, I recommend
                   12065: jumping to @code{' noop >code-address}, which contains nothing but a
                   12066: @code{NEXT}.
1.21      crook    12067: 
1.78      anton    12068: For general accesses to the inner interpreter's registers, the easiest
                   12069: solution is to use explicit register declarations (@pxref{Explicit Reg
                   12070: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
                   12071: all of the inner interpreter's registers: You have to compile Gforth
                   12072: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
                   12073: the appropriate declarations must be present in the @code{machine.h}
                   12074: file (see @code{mips.h} for an example; you can find a full list of all
                   12075: declarable register symbols with @code{grep register engine.c}). If you
                   12076: give explicit registers to all variables that are declared at the
                   12077: beginning of @code{engine()}, you should be able to use the other
                   12078: caller-saved registers for temporary storage. Alternatively, you can use
                   12079: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
                   12080: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
                   12081: reserve a register (however, this restriction on register allocation may
                   12082: slow Gforth significantly).
1.44      crook    12083: 
1.78      anton    12084: If this solution is not viable (e.g., because @code{gcc} does not allow
                   12085: you to explicitly declare all the registers you need), you have to find
                   12086: out by looking at the code where the inner interpreter's registers
                   12087: reside and which registers can be used for temporary storage. You can
                   12088: get an assembly listing of the engine's code with @code{make engine.s}.
1.44      crook    12089: 
1.78      anton    12090: In any case, it is good practice to abstract your assembly code from the
                   12091: actual register allocation. E.g., if the data stack pointer resides in
                   12092: register @code{$17}, create an alias for this register called @code{sp},
                   12093: and use that in your assembly code.
1.21      crook    12094: 
1.78      anton    12095: @cindex code words, portable
                   12096: Another option for implementing normal and defining words efficiently
                   12097: is to add the desired functionality to the source of Gforth. For normal
                   12098: words you just have to edit @file{primitives} (@pxref{Automatic
                   12099: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
                   12100: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
                   12101: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44      crook    12102: 
1.78      anton    12103: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
                   12104: @subsection Common Assembler
1.44      crook    12105: 
1.78      anton    12106: The assemblers in Gforth generally use a postfix syntax, i.e., the
                   12107: instruction name follows the operands.
1.21      crook    12108: 
1.78      anton    12109: The operands are passed in the usual order (the same that is used in the
                   12110: manual of the architecture).  Since they all are Forth words, they have
                   12111: to be separated by spaces; you can also use Forth words to compute the
                   12112: operands.
1.44      crook    12113: 
1.78      anton    12114: The instruction names usually end with a @code{,}.  This makes it easier
                   12115: to visually separate instructions if you put several of them on one
                   12116: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21      crook    12117: 
1.78      anton    12118: Registers are usually specified by number; e.g., (decimal) @code{11}
                   12119: specifies registers R11 and F11 on the Alpha architecture (which one,
                   12120: depends on the instruction).  The usual names are also available, e.g.,
                   12121: @code{s2} for R11 on Alpha.
1.21      crook    12122: 
1.78      anton    12123: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
                   12124: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
                   12125: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
                   12126: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
                   12127: conditions are specified in a way specific to each assembler.
1.1       anton    12128: 
1.78      anton    12129: Note that the register assignments of the Gforth engine can change
                   12130: between Gforth versions, or even between different compilations of the
                   12131: same Gforth version (e.g., if you use a different GCC version).  So if
                   12132: you want to refer to Gforth's registers (e.g., the stack pointer or
                   12133: TOS), I recommend defining your own words for refering to these
                   12134: registers, and using them later on; then you can easily adapt to a
                   12135: changed register assignment.  The stability of the register assignment
                   12136: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1       anton    12137: 
1.100     anton    12138: The most common use of these registers is to dispatch to the next word
                   12139: (the @code{next} routine).  A portable way to do this is to jump to
                   12140: @code{' noop >code-address} (of course, this is less efficient than
                   12141: integrating the @code{next} code and scheduling it well).
1.1       anton    12142: 
1.96      anton    12143: Another difference between Gforth version is that the top of stack is
                   12144: kept in memory in @code{gforth} and, on most platforms, in a register in
                   12145: @code{gforth-fast}.
                   12146: 
1.78      anton    12147: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
                   12148: @subsection Common Disassembler
1.127     anton    12149: @cindex disassembler, general
                   12150: @cindex gdb disassembler
1.1       anton    12151: 
1.78      anton    12152: You can disassemble a @code{code} word with @code{see}
                   12153: (@pxref{Debugging}).  You can disassemble a section of memory with
1.1       anton    12154: 
1.127     anton    12155: doc-discode
1.44      crook    12156: 
1.127     anton    12157: There are two kinds of disassembler for Gforth: The Forth disassembler
                   12158: (available on some CPUs) and the gdb disassembler (available on
                   12159: platforms with @command{gdb} and @command{mktemp}).  If both are
                   12160: available, the Forth disassembler is used by default.  If you prefer
                   12161: the gdb disassembler, say
                   12162: 
                   12163: @example
                   12164: ' disasm-gdb is discode
                   12165: @end example
                   12166: 
                   12167: If neither is available, @code{discode} performs @code{dump}.
                   12168: 
                   12169: The Forth disassembler generally produces output that can be fed into the
1.78      anton    12170: assembler (i.e., same syntax, etc.).  It also includes additional
                   12171: information in comments.  In particular, the address of the instruction
                   12172: is given in a comment before the instruction.
1.1       anton    12173: 
1.127     anton    12174: The gdb disassembler produces output in the same format as the gdb
                   12175: @code{disassemble} command (@pxref{Machine Code,,Source and machine
                   12176: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
                   12177: the 386 and AMD64 architectures).
                   12178: 
1.78      anton    12179: @code{See} may display more or less than the actual code of the word,
                   12180: because the recognition of the end of the code is unreliable.  You can
1.127     anton    12181: use @code{discode} if it did not display enough.  It may display more, if
1.78      anton    12182: the code word is not immediately followed by a named word.  If you have
1.116     anton    12183: something else there, you can follow the word with @code{align latest ,}
1.78      anton    12184: to ensure that the end is recognized.
1.21      crook    12185: 
1.78      anton    12186: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
                   12187: @subsection 386 Assembler
1.44      crook    12188: 
1.78      anton    12189: The 386 assembler included in Gforth was written by Bernd Paysan, it's
                   12190: available under GPL, and originally part of bigFORTH.
1.21      crook    12191: 
1.78      anton    12192: The 386 disassembler included in Gforth was written by Andrew McKewan
                   12193: and is in the public domain.
1.21      crook    12194: 
1.91      anton    12195: The disassembler displays code in an Intel-like prefix syntax.
1.21      crook    12196: 
1.78      anton    12197: The assembler uses a postfix syntax with reversed parameters.
1.1       anton    12198: 
1.78      anton    12199: The assembler includes all instruction of the Athlon, i.e. 486 core
                   12200: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
                   12201: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
                   12202: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1       anton    12203: 
1.78      anton    12204: There are several prefixes to switch between different operation sizes,
                   12205: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
                   12206: double-word accesses. Addressing modes can be switched with @code{.wa}
                   12207: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
                   12208: need a prefix for byte register names (@code{AL} et al).
1.1       anton    12209: 
1.78      anton    12210: For floating point operations, the prefixes are @code{.fs} (IEEE
                   12211: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
                   12212: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21      crook    12213: 
1.78      anton    12214: The MMX opcodes don't have size prefixes, they are spelled out like in
                   12215: the Intel assembler. Instead of move from and to memory, there are
                   12216: PLDQ/PLDD and PSTQ/PSTD.
1.21      crook    12217: 
1.78      anton    12218: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
                   12219: ax.  Immediate values are indicated by postfixing them with @code{#},
1.91      anton    12220: e.g., @code{3 #}.  Here are some examples of addressing modes in various
                   12221: syntaxes:
1.21      crook    12222: 
1.26      crook    12223: @example
1.91      anton    12224: Gforth          Intel (NASM)   AT&T (gas)      Name
                   12225: .w ax           ax             %ax             register (16 bit)
                   12226: ax              eax            %eax            register (32 bit)
                   12227: 3 #             offset 3       $3              immediate
                   12228: 1000 #)         byte ptr 1000  1000            displacement
                   12229: bx )            [ebx]          (%ebx)          base
                   12230: 100 di d)       100[edi]       100(%edi)       base+displacement
                   12231: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
                   12232: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
                   12233: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
                   12234: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
                   12235: @end example
                   12236: 
                   12237: You can use @code{L)} and @code{LI)} instead of @code{D)} and
                   12238: @code{DI)} to enforce 32-bit displacement fields (useful for
                   12239: later patching).
1.21      crook    12240: 
1.78      anton    12241: Some example of instructions are:
1.1       anton    12242: 
                   12243: @example
1.78      anton    12244: ax bx mov             \ move ebx,eax
                   12245: 3 # ax mov            \ mov eax,3
1.137     pazsan   12246: 100 di d) ax mov      \ mov eax,100[edi]
1.78      anton    12247: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
                   12248: .w ax bx mov          \ mov bx,ax
1.1       anton    12249: @end example
                   12250: 
1.78      anton    12251: The following forms are supported for binary instructions:
1.1       anton    12252: 
                   12253: @example
1.78      anton    12254: <reg> <reg> <inst>
                   12255: <n> # <reg> <inst>
                   12256: <mem> <reg> <inst>
                   12257: <reg> <mem> <inst>
1.136     pazsan   12258: <n> # <mem> <inst>
1.1       anton    12259: @end example
                   12260: 
1.136     pazsan   12261: The shift/rotate syntax is:
1.1       anton    12262: 
1.26      crook    12263: @example
1.78      anton    12264: <reg/mem> 1 # shl \ shortens to shift without immediate
                   12265: <reg/mem> 4 # shl
                   12266: <reg/mem> cl shl
1.26      crook    12267: @end example
1.1       anton    12268: 
1.78      anton    12269: Precede string instructions (@code{movs} etc.) with @code{.b} to get
                   12270: the byte version.
1.1       anton    12271: 
1.78      anton    12272: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
                   12273: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
                   12274: pc < >= <= >}. (Note that most of these words shadow some Forth words
                   12275: when @code{assembler} is in front of @code{forth} in the search path,
                   12276: e.g., in @code{code} words).  Currently the control structure words use
                   12277: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
                   12278: to shuffle them (you can also use @code{swap} etc.).
1.21      crook    12279: 
1.78      anton    12280: Here is an example of a @code{code} word (assumes that the stack pointer
                   12281: is in esi and the TOS is in ebx):
1.21      crook    12282: 
1.26      crook    12283: @example
1.78      anton    12284: code my+ ( n1 n2 -- n )
                   12285:     4 si D) bx add
                   12286:     4 # si add
                   12287:     Next
                   12288: end-code
1.26      crook    12289: @end example
1.21      crook    12290: 
1.161     anton    12291: 
1.78      anton    12292: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
                   12293: @subsection Alpha Assembler
1.21      crook    12294: 
1.78      anton    12295: The Alpha assembler and disassembler were originally written by Bernd
                   12296: Thallner.
1.26      crook    12297: 
1.78      anton    12298: The register names @code{a0}--@code{a5} are not available to avoid
                   12299: shadowing hex numbers.
1.2       jwilke   12300: 
1.78      anton    12301: Immediate forms of arithmetic instructions are distinguished by a
                   12302: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
                   12303: does not count as arithmetic instruction).
1.2       jwilke   12304: 
1.78      anton    12305: You have to specify all operands to an instruction, even those that
                   12306: other assemblers consider optional, e.g., the destination register for
                   12307: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2       jwilke   12308: 
1.78      anton    12309: You can specify conditions for @code{if,} by removing the first @code{b}
                   12310: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2       jwilke   12311: 
1.26      crook    12312: @example
1.78      anton    12313: 11 fgt if, \ if F11>0e
                   12314:   ...
                   12315: endif,
1.26      crook    12316: @end example
1.2       jwilke   12317: 
1.78      anton    12318: @code{fbgt,} gives @code{fgt}.  
                   12319: 
1.161     anton    12320: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78      anton    12321: @subsection MIPS assembler
1.2       jwilke   12322: 
1.78      anton    12323: The MIPS assembler was originally written by Christian Pirker.
1.2       jwilke   12324: 
1.78      anton    12325: Currently the assembler and disassembler only cover the MIPS-I
                   12326: architecture (R3000), and don't support FP instructions.
1.2       jwilke   12327: 
1.78      anton    12328: The register names @code{$a0}--@code{$a3} are not available to avoid
                   12329: shadowing hex numbers.
1.2       jwilke   12330: 
1.78      anton    12331: Because there is no way to distinguish registers from immediate values,
                   12332: you have to explicitly use the immediate forms of instructions, i.e.,
                   12333: @code{addiu,}, not just @code{addu,} (@command{as} does this
                   12334: implicitly).
1.2       jwilke   12335: 
1.78      anton    12336: If the architecture manual specifies several formats for the instruction
                   12337: (e.g., for @code{jalr,}), you usually have to use the one with more
                   12338: arguments (i.e., two for @code{jalr,}).  When in doubt, see
                   12339: @code{arch/mips/testasm.fs} for an example of correct use.
1.2       jwilke   12340: 
1.78      anton    12341: Branches and jumps in the MIPS architecture have a delay slot.  You have
                   12342: to fill it yourself (the simplest way is to use @code{nop,}), the
                   12343: assembler does not do it for you (unlike @command{as}).  Even
                   12344: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
                   12345: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
                   12346: and @code{then,} just specify branch targets, they are not affected.
1.2       jwilke   12347: 
1.78      anton    12348: Note that you must not put branches, jumps, or @code{li,} into the delay
                   12349: slot: @code{li,} may expand to several instructions, and control flow
                   12350: instructions may not be put into the branch delay slot in any case.
1.2       jwilke   12351: 
1.78      anton    12352: For branches the argument specifying the target is a relative address;
                   12353: You have to add the address of the delay slot to get the absolute
                   12354: address.
1.1       anton    12355: 
1.78      anton    12356: The MIPS architecture also has load delay slots and restrictions on
                   12357: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
                   12358: yourself to satisfy these restrictions, the assembler does not do it for
                   12359: you.
1.1       anton    12360: 
1.78      anton    12361: You can specify the conditions for @code{if,} etc. by taking a
                   12362: conditional branch and leaving away the @code{b} at the start and the
                   12363: @code{,} at the end.  E.g.,
1.1       anton    12364: 
1.26      crook    12365: @example
1.78      anton    12366: 4 5 eq if,
                   12367:   ... \ do something if $4 equals $5
                   12368: then,
1.26      crook    12369: @end example
1.1       anton    12370: 
1.161     anton    12371: 
                   12372: @node PowerPC assembler, Other assemblers, MIPS assembler, Assembler and Code Words
                   12373: @subsection PowerPC assembler
                   12374: 
1.162     anton    12375: The PowerPC assembler and disassembler were contributed by Michal
1.161     anton    12376: Revucky.
                   12377: 
1.162     anton    12378: This assembler does not follow the convention of ending mnemonic names
                   12379: with a ``,'', so some mnemonic names shadow regular Forth words (in
                   12380: particular: @code{and or xor fabs}); so if you want to use the Forth
                   12381: words, you have to make them visible first, e.g., with @code{also
                   12382: forth}.
                   12383: 
1.161     anton    12384: Registers are referred to by their number, e.g., @code{9} means the
                   12385: integer register 9 or the FP register 9 (depending on the
                   12386: instruction).
                   12387: 
                   12388: Because there is no way to distinguish registers from immediate values,
                   12389: you have to explicitly use the immediate forms of instructions, i.e.,
1.162     anton    12390: @code{addi,}, not just @code{add,}.
1.161     anton    12391: 
1.162     anton    12392: The assembler and disassembler usually support the most general form
1.161     anton    12393: of an instruction, but usually not the shorter forms (especially for
                   12394: branches).
                   12395: 
                   12396: 
                   12397: 
                   12398: @node Other assemblers,  , PowerPC assembler, Assembler and Code Words
1.78      anton    12399: @subsection Other assemblers
                   12400: 
                   12401: If you want to contribute another assembler/disassembler, please contact
1.103     anton    12402: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
                   12403: an assembler already.  If you are writing them from scratch, please use
                   12404: a similar syntax style as the one we use (i.e., postfix, commas at the
                   12405: end of the instruction names, @pxref{Common Assembler}); make the output
                   12406: of the disassembler be valid input for the assembler, and keep the style
1.78      anton    12407: similar to the style we used.
                   12408: 
                   12409: Hints on implementation: The most important part is to have a good test
                   12410: suite that contains all instructions.  Once you have that, the rest is
                   12411: easy.  For actual coding you can take a look at
                   12412: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
                   12413: the assembler and disassembler, avoiding redundancy and some potential
                   12414: bugs.  You can also look at that file (and @pxref{Advanced does> usage
                   12415: example}) to get ideas how to factor a disassembler.
                   12416: 
                   12417: Start with the disassembler, because it's easier to reuse data from the
                   12418: disassembler for the assembler than the other way round.
1.1       anton    12419: 
1.78      anton    12420: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
                   12421: how simple it can be.
1.1       anton    12422: 
1.161     anton    12423: 
                   12424: 
                   12425: 
1.78      anton    12426: @c -------------------------------------------------------------
                   12427: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
                   12428: @section Threading Words
                   12429: @cindex threading words
1.1       anton    12430: 
1.78      anton    12431: @cindex code address
                   12432: These words provide access to code addresses and other threading stuff
                   12433: in Gforth (and, possibly, other interpretive Forths). It more or less
                   12434: abstracts away the differences between direct and indirect threading
                   12435: (and, for direct threading, the machine dependences). However, at
                   12436: present this wordset is still incomplete. It is also pretty low-level;
                   12437: some day it will hopefully be made unnecessary by an internals wordset
                   12438: that abstracts implementation details away completely.
1.1       anton    12439: 
1.78      anton    12440: The terminology used here stems from indirect threaded Forth systems; in
                   12441: such a system, the XT of a word is represented by the CFA (code field
                   12442: address) of a word; the CFA points to a cell that contains the code
                   12443: address.  The code address is the address of some machine code that
                   12444: performs the run-time action of invoking the word (e.g., the
                   12445: @code{dovar:} routine pushes the address of the body of the word (a
                   12446: variable) on the stack
                   12447: ).
1.1       anton    12448: 
1.78      anton    12449: @cindex code address
                   12450: @cindex code field address
                   12451: In an indirect threaded Forth, you can get the code address of @i{name}
                   12452: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
                   12453: >code-address}, independent of the threading method.
1.1       anton    12454: 
1.78      anton    12455: doc-threading-method
                   12456: doc->code-address
                   12457: doc-code-address!
1.1       anton    12458: 
1.78      anton    12459: @cindex @code{does>}-handler
                   12460: @cindex @code{does>}-code
                   12461: For a word defined with @code{DOES>}, the code address usually points to
                   12462: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
                   12463: routine (in Gforth on some platforms, it can also point to the dodoes
                   12464: routine itself).  What you are typically interested in, though, is
                   12465: whether a word is a @code{DOES>}-defined word, and what Forth code it
                   12466: executes; @code{>does-code} tells you that.
1.1       anton    12467: 
1.78      anton    12468: doc->does-code
1.1       anton    12469: 
1.78      anton    12470: To create a @code{DOES>}-defined word with the following basic words,
                   12471: you have to set up a @code{DOES>}-handler with @code{does-handler!};
                   12472: @code{/does-handler} aus behind you have to place your executable Forth
                   12473: code.  Finally you have to create a word and modify its behaviour with
                   12474: @code{does-handler!}.
1.1       anton    12475: 
1.78      anton    12476: doc-does-code!
                   12477: doc-does-handler!
                   12478: doc-/does-handler
1.1       anton    12479: 
1.78      anton    12480: The code addresses produced by various defining words are produced by
                   12481: the following words:
1.1       anton    12482: 
1.78      anton    12483: doc-docol:
                   12484: doc-docon:
                   12485: doc-dovar:
                   12486: doc-douser:
                   12487: doc-dodefer:
                   12488: doc-dofield:
1.1       anton    12489: 
1.99      anton    12490: @cindex definer
                   12491: The following two words generalize @code{>code-address},
                   12492: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
                   12493: 
                   12494: doc->definer
                   12495: doc-definer!
                   12496: 
1.26      crook    12497: @c -------------------------------------------------------------
1.78      anton    12498: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21      crook    12499: @section Passing Commands to the Operating System
                   12500: @cindex operating system - passing commands
                   12501: @cindex shell commands
                   12502: 
                   12503: Gforth allows you to pass an arbitrary string to the host operating
                   12504: system shell (if such a thing exists) for execution.
                   12505: 
                   12506: doc-sh
                   12507: doc-system
                   12508: doc-$?
1.23      crook    12509: doc-getenv
1.44      crook    12510: 
1.26      crook    12511: @c -------------------------------------------------------------
1.47      crook    12512: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
                   12513: @section Keeping track of Time
                   12514: @cindex time-related words
                   12515: 
                   12516: doc-ms
                   12517: doc-time&date
1.79      anton    12518: doc-utime
                   12519: doc-cputime
1.47      crook    12520: 
                   12521: 
                   12522: @c -------------------------------------------------------------
                   12523: @node Miscellaneous Words,  , Keeping track of Time, Words
1.21      crook    12524: @section Miscellaneous Words
                   12525: @cindex miscellaneous words
                   12526: 
1.29      crook    12527: @comment TODO find homes for these
                   12528: 
1.26      crook    12529: These section lists the ANS Forth words that are not documented
1.21      crook    12530: elsewhere in this manual. Ultimately, they all need proper homes.
                   12531: 
1.68      anton    12532: doc-quit
1.44      crook    12533: 
1.26      crook    12534: The following ANS Forth words are not currently supported by Gforth 
1.27      crook    12535: (@pxref{ANS conformance}):
1.21      crook    12536: 
                   12537: @code{EDITOR} 
                   12538: @code{EMIT?} 
                   12539: @code{FORGET} 
                   12540: 
1.24      anton    12541: @c ******************************************************************
                   12542: @node Error messages, Tools, Words, Top
                   12543: @chapter Error messages
                   12544: @cindex error messages
                   12545: @cindex backtrace
                   12546: 
                   12547: A typical Gforth error message looks like this:
                   12548: 
                   12549: @example
1.86      anton    12550: in file included from \evaluated string/:-1
1.24      anton    12551: in file included from ./yyy.fs:1
                   12552: ./xxx.fs:4: Invalid memory address
1.134     anton    12553: >>>bar<<<
1.79      anton    12554: Backtrace:
1.25      anton    12555: $400E664C @@
                   12556: $400E6664 foo
1.24      anton    12557: @end example
                   12558: 
                   12559: The message identifying the error is @code{Invalid memory address}.  The
                   12560: error happened when text-interpreting line 4 of the file
                   12561: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
                   12562: word on the line where the error happened, is pointed out (with
1.134     anton    12563: @code{>>>} and @code{<<<}).
1.24      anton    12564: 
                   12565: The file containing the error was included in line 1 of @file{./yyy.fs},
                   12566: and @file{yyy.fs} was included from a non-file (in this case, by giving
                   12567: @file{yyy.fs} as command-line parameter to Gforth).
                   12568: 
                   12569: At the end of the error message you find a return stack dump that can be
                   12570: interpreted as a backtrace (possibly empty). On top you find the top of
                   12571: the return stack when the @code{throw} happened, and at the bottom you
                   12572: find the return stack entry just above the return stack of the topmost
                   12573: text interpreter.
                   12574: 
                   12575: To the right of most return stack entries you see a guess for the word
                   12576: that pushed that return stack entry as its return address. This gives a
                   12577: backtrace. In our case we see that @code{bar} called @code{foo}, and
                   12578: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
                   12579: address} exception).
                   12580: 
                   12581: Note that the backtrace is not perfect: We don't know which return stack
                   12582: entries are return addresses (so we may get false positives); and in
                   12583: some cases (e.g., for @code{abort"}) we cannot determine from the return
                   12584: address the word that pushed the return address, so for some return
                   12585: addresses you see no names in the return stack dump.
1.25      anton    12586: 
                   12587: @cindex @code{catch} and backtraces
                   12588: The return stack dump represents the return stack at the time when a
                   12589: specific @code{throw} was executed.  In programs that make use of
                   12590: @code{catch}, it is not necessarily clear which @code{throw} should be
                   12591: used for the return stack dump (e.g., consider one @code{throw} that
                   12592: indicates an error, which is caught, and during recovery another error
1.160     anton    12593: happens; which @code{throw} should be used for the stack dump?).
                   12594: Gforth presents the return stack dump for the first @code{throw} after
                   12595: the last executed (not returned-to) @code{catch} or @code{nothrow};
                   12596: this works well in the usual case. To get the right backtrace, you
                   12597: usually want to insert @code{nothrow} or @code{['] false catch drop}
                   12598: after a @code{catch} if the error is not rethrown.
1.25      anton    12599: 
                   12600: @cindex @code{gforth-fast} and backtraces
                   12601: @cindex @code{gforth-fast}, difference from @code{gforth}
                   12602: @cindex backtraces with @code{gforth-fast}
                   12603: @cindex return stack dump with @code{gforth-fast}
1.79      anton    12604: @code{Gforth} is able to do a return stack dump for throws generated
1.25      anton    12605: from primitives (e.g., invalid memory address, stack empty etc.);
                   12606: @code{gforth-fast} is only able to do a return stack dump from a
1.96      anton    12607: directly called @code{throw} (including @code{abort} etc.).  Given an
1.30      anton    12608: exception caused by a primitive in @code{gforth-fast}, you will
                   12609: typically see no return stack dump at all; however, if the exception is
                   12610: caught by @code{catch} (e.g., for restoring some state), and then
                   12611: @code{throw}n again, the return stack dump will be for the first such
                   12612: @code{throw}.
1.2       jwilke   12613: 
1.5       anton    12614: @c ******************************************************************
1.24      anton    12615: @node Tools, ANS conformance, Error messages, Top
1.1       anton    12616: @chapter Tools
                   12617: 
                   12618: @menu
                   12619: * ANS Report::                  Report the words used, sorted by wordset.
1.127     anton    12620: * Stack depth changes::         Where does this stack item come from?
1.1       anton    12621: @end menu
                   12622: 
                   12623: See also @ref{Emacs and Gforth}.
                   12624: 
1.126     pazsan   12625: @node ANS Report, Stack depth changes, Tools, Tools
1.1       anton    12626: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   12627: @cindex @file{ans-report.fs}
                   12628: @cindex report the words used in your program
                   12629: @cindex words used in your program
                   12630: 
                   12631: If you want to label a Forth program as ANS Forth Program, you must
                   12632: document which wordsets the program uses; for extension wordsets, it is
                   12633: helpful to list the words the program requires from these wordsets
                   12634: (because Forth systems are allowed to provide only some words of them).
                   12635: 
                   12636: The @file{ans-report.fs} tool makes it easy for you to determine which
                   12637: words from which wordset and which non-ANS words your application
                   12638: uses. You simply have to include @file{ans-report.fs} before loading the
                   12639: program you want to check. After loading your program, you can get the
                   12640: report with @code{print-ans-report}. A typical use is to run this as
                   12641: batch job like this:
                   12642: @example
                   12643: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   12644: @end example
                   12645: 
                   12646: The output looks like this (for @file{compat/control.fs}):
                   12647: @example
                   12648: The program uses the following words
                   12649: from CORE :
                   12650: : POSTPONE THEN ; immediate ?dup IF 0= 
                   12651: from BLOCK-EXT :
                   12652: \ 
                   12653: from FILE :
                   12654: ( 
                   12655: @end example
                   12656: 
                   12657: @subsection Caveats
                   12658: 
                   12659: Note that @file{ans-report.fs} just checks which words are used, not whether
                   12660: they are used in an ANS Forth conforming way!
                   12661: 
                   12662: Some words are defined in several wordsets in the
                   12663: standard. @file{ans-report.fs} reports them for only one of the
                   12664: wordsets, and not necessarily the one you expect. It depends on usage
                   12665: which wordset is the right one to specify. E.g., if you only use the
                   12666: compilation semantics of @code{S"}, it is a Core word; if you also use
                   12667: its interpretation semantics, it is a File word.
1.124     anton    12668: 
                   12669: 
1.127     anton    12670: @node Stack depth changes,  , ANS Report, Tools
1.124     anton    12671: @section Stack depth changes during interpretation
                   12672: @cindex @file{depth-changes.fs}
                   12673: @cindex depth changes during interpretation
                   12674: @cindex stack depth changes during interpretation
                   12675: @cindex items on the stack after interpretation
                   12676: 
                   12677: Sometimes you notice that, after loading a file, there are items left
                   12678: on the stack.  The tool @file{depth-changes.fs} helps you find out
                   12679: quickly where in the file these stack items are coming from.
                   12680: 
                   12681: The simplest way of using @file{depth-changes.fs} is to include it
                   12682: before the file(s) you want to check, e.g.:
                   12683: 
                   12684: @example
                   12685: gforth depth-changes.fs my-file.fs
                   12686: @end example
                   12687: 
                   12688: This will compare the stack depths of the data and FP stack at every
                   12689: empty line (in interpretation state) against these depths at the last
                   12690: empty line (in interpretation state).  If the depths are not equal,
                   12691: the position in the file and the stack contents are printed with
                   12692: @code{~~} (@pxref{Debugging}).  This indicates that a stack depth
                   12693: change has occured in the paragraph of non-empty lines before the
                   12694: indicated line.  It is a good idea to leave an empty line at the end
                   12695: of the file, so the last paragraph is checked, too.
                   12696: 
                   12697: Checking only at empty lines usually works well, but sometimes you
                   12698: have big blocks of non-empty lines (e.g., when building a big table),
                   12699: and you want to know where in this block the stack depth changed.  You
                   12700: can check all interpreted lines with
                   12701: 
                   12702: @example
                   12703: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
                   12704: @end example
                   12705: 
                   12706: This checks the stack depth at every end-of-line.  So the depth change
                   12707: occured in the line reported by the @code{~~} (not in the line
                   12708: before).
                   12709: 
                   12710: Note that, while this offers better accuracy in indicating where the
                   12711: stack depth changes, it will often report many intentional stack depth
                   12712: changes (e.g., when an interpreted computation stretches across
                   12713: several lines).  You can suppress the checking of some lines by
                   12714: putting backslashes at the end of these lines (not followed by white
                   12715: space), and using
                   12716: 
                   12717: @example
                   12718: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
                   12719: @end example
1.1       anton    12720: 
                   12721: @c ******************************************************************
1.65      anton    12722: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1       anton    12723: @chapter ANS conformance
                   12724: @cindex ANS conformance of Gforth
                   12725: 
                   12726: To the best of our knowledge, Gforth is an
                   12727: 
                   12728: ANS Forth System
                   12729: @itemize @bullet
                   12730: @item providing the Core Extensions word set
                   12731: @item providing the Block word set
                   12732: @item providing the Block Extensions word set
                   12733: @item providing the Double-Number word set
                   12734: @item providing the Double-Number Extensions word set
                   12735: @item providing the Exception word set
                   12736: @item providing the Exception Extensions word set
                   12737: @item providing the Facility word set
1.40      anton    12738: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1       anton    12739: @item providing the File Access word set
                   12740: @item providing the File Access Extensions word set
                   12741: @item providing the Floating-Point word set
                   12742: @item providing the Floating-Point Extensions word set
                   12743: @item providing the Locals word set
                   12744: @item providing the Locals Extensions word set
                   12745: @item providing the Memory-Allocation word set
                   12746: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   12747: @item providing the Programming-Tools word set
                   12748: @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
                   12749: @item providing the Search-Order word set
                   12750: @item providing the Search-Order Extensions word set
                   12751: @item providing the String word set
                   12752: @item providing the String Extensions word set (another easy one)
                   12753: @end itemize
                   12754: 
1.118     anton    12755: Gforth has the following environmental restrictions:
                   12756: 
                   12757: @cindex environmental restrictions
                   12758: @itemize @bullet
                   12759: @item
                   12760: While processing the OS command line, if an exception is not caught,
                   12761: Gforth exits with a non-zero exit code instyead of performing QUIT.
                   12762: 
                   12763: @item
                   12764: When an @code{throw} is performed after a @code{query}, Gforth does not
                   12765: allways restore the input source specification in effect at the
                   12766: corresponding catch.
                   12767: 
                   12768: @end itemize
                   12769: 
                   12770: 
1.1       anton    12771: @cindex system documentation
                   12772: In addition, ANS Forth systems are required to document certain
                   12773: implementation choices. This chapter tries to meet these
                   12774: requirements. In many cases it gives a way to ask the system for the
                   12775: information instead of providing the information directly, in
                   12776: particular, if the information depends on the processor, the operating
                   12777: system or the installation options chosen, or if they are likely to
                   12778: change during the maintenance of Gforth.
                   12779: 
                   12780: @comment The framework for the rest has been taken from pfe.
                   12781: 
                   12782: @menu
                   12783: * The Core Words::              
                   12784: * The optional Block word set::  
                   12785: * The optional Double Number word set::  
                   12786: * The optional Exception word set::  
                   12787: * The optional Facility word set::  
                   12788: * The optional File-Access word set::  
                   12789: * The optional Floating-Point word set::  
                   12790: * The optional Locals word set::  
                   12791: * The optional Memory-Allocation word set::  
                   12792: * The optional Programming-Tools word set::  
                   12793: * The optional Search-Order word set::  
                   12794: @end menu
                   12795: 
                   12796: 
                   12797: @c =====================================================================
                   12798: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   12799: @comment  node-name,  next,  previous,  up
                   12800: @section The Core Words
                   12801: @c =====================================================================
                   12802: @cindex core words, system documentation
                   12803: @cindex system documentation, core words
                   12804: 
                   12805: @menu
                   12806: * core-idef::                   Implementation Defined Options                   
                   12807: * core-ambcond::                Ambiguous Conditions                
                   12808: * core-other::                  Other System Documentation                  
                   12809: @end menu
                   12810: 
                   12811: @c ---------------------------------------------------------------------
                   12812: @node core-idef, core-ambcond, The Core Words, The Core Words
                   12813: @subsection Implementation Defined Options
                   12814: @c ---------------------------------------------------------------------
                   12815: @cindex core words, implementation-defined options
                   12816: @cindex implementation-defined options, core words
                   12817: 
                   12818: 
                   12819: @table @i
                   12820: @item (Cell) aligned addresses:
                   12821: @cindex cell-aligned addresses
                   12822: @cindex aligned addresses
                   12823: processor-dependent. Gforth's alignment words perform natural alignment
                   12824: (e.g., an address aligned for a datum of size 8 is divisible by
                   12825: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   12826: 
                   12827: @item @code{EMIT} and non-graphic characters:
                   12828: @cindex @code{EMIT} and non-graphic characters
                   12829: @cindex non-graphic characters and @code{EMIT}
                   12830: The character is output using the C library function (actually, macro)
                   12831: @code{putc}.
                   12832: 
                   12833: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   12834: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   12835: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   12836: @cindex @code{ACCEPT}, editing
                   12837: @cindex @code{EXPECT}, editing
                   12838: This is modeled on the GNU readline library (@pxref{Readline
                   12839: Interaction, , Command Line Editing, readline, The GNU Readline
                   12840: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   12841: producing a full word completion every time you type it (instead of
1.28      crook    12842: producing the common prefix of all completions). @xref{Command-line editing}.
1.1       anton    12843: 
                   12844: @item character set:
                   12845: @cindex character set
                   12846: The character set of your computer and display device. Gforth is
                   12847: 8-bit-clean (but some other component in your system may make trouble).
                   12848: 
                   12849: @item Character-aligned address requirements:
                   12850: @cindex character-aligned address requirements
                   12851: installation-dependent. Currently a character is represented by a C
                   12852: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   12853: (Comments on that requested).
                   12854: 
                   12855: @item character-set extensions and matching of names:
                   12856: @cindex character-set extensions and matching of names
1.26      crook    12857: @cindex case-sensitivity for name lookup
                   12858: @cindex name lookup, case-sensitivity
                   12859: @cindex locale and case-sensitivity
1.21      crook    12860: Any character except the ASCII NUL character can be used in a
1.1       anton    12861: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47      crook    12862: matching is performed using the C library function @code{strncasecmp}, whose
1.1       anton    12863: function is probably influenced by the locale. E.g., the @code{C} locale
                   12864: does not know about accents and umlauts, so they are matched
                   12865: case-sensitively in that locale. For portability reasons it is best to
                   12866: write programs such that they work in the @code{C} locale. Then one can
                   12867: use libraries written by a Polish programmer (who might use words
                   12868: containing ISO Latin-2 encoded characters) and by a French programmer
                   12869: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   12870: funny results for some of the words (which ones, depends on the font you
                   12871: are using)). Also, the locale you prefer may not be available in other
                   12872: operating systems. Hopefully, Unicode will solve these problems one day.
                   12873: 
                   12874: @item conditions under which control characters match a space delimiter:
                   12875: @cindex space delimiters
                   12876: @cindex control characters as delimiters
1.117     anton    12877: If @code{word} is called with the space character as a delimiter, all
1.1       anton    12878: white-space characters (as identified by the C macro @code{isspace()})
1.117     anton    12879: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138     anton    12880: delimiters.  @code{Parse-name}, which is used by the outer
1.1       anton    12881: interpreter (aka text interpreter) by default, treats all white-space
                   12882: characters as delimiters.
                   12883: 
1.26      crook    12884: @item format of the control-flow stack:
                   12885: @cindex control-flow stack, format
                   12886: The data stack is used as control-flow stack. The size of a control-flow
1.1       anton    12887: stack item in cells is given by the constant @code{cs-item-size}. At the
                   12888: time of this writing, an item consists of a (pointer to a) locals list
                   12889: (third), an address in the code (second), and a tag for identifying the
                   12890: item (TOS). The following tags are used: @code{defstart},
                   12891: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   12892: @code{scopestart}.
                   12893: 
                   12894: @item conversion of digits > 35
                   12895: @cindex digits > 35
                   12896: The characters @code{[\]^_'} are the digits with the decimal value
                   12897: 36@minus{}41. There is no way to input many of the larger digits.
                   12898: 
                   12899: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   12900: @cindex @code{EXPECT}, display after end of input
                   12901: @cindex @code{ACCEPT}, display after end of input
                   12902: The cursor is moved to the end of the entered string. If the input is
                   12903: terminated using the @kbd{Return} key, a space is typed.
                   12904: 
                   12905: @item exception abort sequence of @code{ABORT"}:
                   12906: @cindex exception abort sequence of @code{ABORT"}
                   12907: @cindex @code{ABORT"}, exception abort sequence
                   12908: The error string is stored into the variable @code{"error} and a
                   12909: @code{-2 throw} is performed.
                   12910: 
                   12911: @item input line terminator:
                   12912: @cindex input line terminator
                   12913: @cindex line terminator on input
1.26      crook    12914: @cindex newline character on input
1.1       anton    12915: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   12916: lines. One of these characters is typically produced when you type the
                   12917: @kbd{Enter} or @kbd{Return} key.
                   12918: 
                   12919: @item maximum size of a counted string:
                   12920: @cindex maximum size of a counted string
                   12921: @cindex counted string, maximum size
                   12922: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79      anton    12923: on all platforms, but this may change.
1.1       anton    12924: 
                   12925: @item maximum size of a parsed string:
                   12926: @cindex maximum size of a parsed string
                   12927: @cindex parsed string, maximum size
                   12928: Given by the constant @code{/line}. Currently 255 characters.
                   12929: 
                   12930: @item maximum size of a definition name, in characters:
                   12931: @cindex maximum size of a definition name, in characters
                   12932: @cindex name, maximum length
1.113     anton    12933: MAXU/8
1.1       anton    12934: 
                   12935: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   12936: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   12937: @cindex @code{ENVIRONMENT?} string length, maximum
1.113     anton    12938: MAXU/8
1.1       anton    12939: 
                   12940: @item method of selecting the user input device:
                   12941: @cindex user input device, method of selecting
                   12942: The user input device is the standard input. There is currently no way to
                   12943: change it from within Gforth. However, the input can typically be
                   12944: redirected in the command line that starts Gforth.
                   12945: 
                   12946: @item method of selecting the user output device:
                   12947: @cindex user output device, method of selecting
                   12948: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    12949: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   12950: output when the user output device is a terminal, otherwise the output
                   12951: is buffered.
1.1       anton    12952: 
                   12953: @item methods of dictionary compilation:
                   12954: What are we expected to document here?
                   12955: 
                   12956: @item number of bits in one address unit:
                   12957: @cindex number of bits in one address unit
                   12958: @cindex address unit, size in bits
                   12959: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79      anton    12960: platforms.
1.1       anton    12961: 
                   12962: @item number representation and arithmetic:
                   12963: @cindex number representation and arithmetic
1.79      anton    12964: Processor-dependent. Binary two's complement on all current platforms.
1.1       anton    12965: 
                   12966: @item ranges for integer types:
                   12967: @cindex ranges for integer types
                   12968: @cindex integer types, ranges
                   12969: Installation-dependent. Make environmental queries for @code{MAX-N},
                   12970: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   12971: unsigned (and positive) types is 0. The lower bound for signed types on
                   12972: two's complement and one's complement machines machines can be computed
                   12973: by adding 1 to the upper bound.
                   12974: 
                   12975: @item read-only data space regions:
                   12976: @cindex read-only data space regions
                   12977: @cindex data-space, read-only regions
                   12978: The whole Forth data space is writable.
                   12979: 
                   12980: @item size of buffer at @code{WORD}:
                   12981: @cindex size of buffer at @code{WORD}
                   12982: @cindex @code{WORD} buffer size
                   12983: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   12984: shared with the pictured numeric output string. If overwriting
                   12985: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   12986: space, although only as much can be sensibly used as fits in a counted
                   12987: string.
                   12988: 
                   12989: @item size of one cell in address units:
                   12990: @cindex cell size
                   12991: @code{1 cells .}.
                   12992: 
                   12993: @item size of one character in address units:
                   12994: @cindex char size
1.79      anton    12995: @code{1 chars .}. 1 on all current platforms.
1.1       anton    12996: 
                   12997: @item size of the keyboard terminal buffer:
                   12998: @cindex size of the keyboard terminal buffer
                   12999: @cindex terminal buffer, size
                   13000: Varies. You can determine the size at a specific time using @code{lp@@
                   13001: tib - .}. It is shared with the locals stack and TIBs of files that
                   13002: include the current file. You can change the amount of space for TIBs
                   13003: and locals stack at Gforth startup with the command line option
                   13004: @code{-l}.
                   13005: 
                   13006: @item size of the pictured numeric output buffer:
                   13007: @cindex size of the pictured numeric output buffer
                   13008: @cindex pictured numeric output buffer, size
                   13009: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   13010: shared with @code{WORD}.
                   13011: 
                   13012: @item size of the scratch area returned by @code{PAD}:
                   13013: @cindex size of the scratch area returned by @code{PAD}
                   13014: @cindex @code{PAD} size
                   13015: The remainder of dictionary space. @code{unused pad here - - .}.
                   13016: 
                   13017: @item system case-sensitivity characteristics:
                   13018: @cindex case-sensitivity characteristics
1.26      crook    13019: Dictionary searches are case-insensitive (except in
1.1       anton    13020: @code{TABLE}s). However, as explained above under @i{character-set
                   13021: extensions}, the matching for non-ASCII characters is determined by the
                   13022: locale you are using. In the default @code{C} locale all non-ASCII
                   13023: characters are matched case-sensitively.
                   13024: 
                   13025: @item system prompt:
                   13026: @cindex system prompt
                   13027: @cindex prompt
                   13028: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   13029: 
                   13030: @item division rounding:
                   13031: @cindex division rounding
1.166     anton    13032: The ordinary division words @code{/ mod /mod */ */mod} perform floored
                   13033: division (with the default installation of Gforth).  You can check
                   13034: this with @code{s" floored" environment? drop .}.  If you write
                   13035: programs that need a specific division rounding, best use
                   13036: @code{fm/mod} or @code{sm/rem} for portability.
1.1       anton    13037: 
                   13038: @item values of @code{STATE} when true:
                   13039: @cindex @code{STATE} values
                   13040: -1.
                   13041: 
                   13042: @item values returned after arithmetic overflow:
                   13043: On two's complement machines, arithmetic is performed modulo
                   13044: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.164     anton    13045: arithmetic (with appropriate mapping for signed types). Division by
                   13046: zero typically results in a @code{-55 throw} (Floating-point
                   13047: unidentified fault) or @code{-10 throw} (divide by zero).  Integer
1.166     anton    13048: division overflow can result in these throws, or in @code{-11 throw};
                   13049: in @code{gforth-fast} division overflow and divide by zero may also
                   13050: result in returning bogus results without producing an exception.
1.1       anton    13051: 
                   13052: @item whether the current definition can be found after @t{DOES>}:
                   13053: @cindex @t{DOES>}, visibility of current definition
                   13054: No.
                   13055: 
                   13056: @end table
                   13057: 
                   13058: @c ---------------------------------------------------------------------
                   13059: @node core-ambcond, core-other, core-idef, The Core Words
                   13060: @subsection Ambiguous conditions
                   13061: @c ---------------------------------------------------------------------
                   13062: @cindex core words, ambiguous conditions
                   13063: @cindex ambiguous conditions, core words
                   13064: 
                   13065: @table @i
                   13066: 
                   13067: @item a name is neither a word nor a number:
                   13068: @cindex name not found
1.26      crook    13069: @cindex undefined word
1.80      anton    13070: @code{-13 throw} (Undefined word).
1.1       anton    13071: 
                   13072: @item a definition name exceeds the maximum length allowed:
1.26      crook    13073: @cindex word name too long
1.1       anton    13074: @code{-19 throw} (Word name too long)
                   13075: 
                   13076: @item addressing a region not inside the various data spaces of the forth system:
                   13077: @cindex Invalid memory address
1.32      anton    13078: The stacks, code space and header space are accessible. Machine code space is
1.1       anton    13079: typically readable. Accessing other addresses gives results dependent on
                   13080: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   13081: address).
                   13082: 
                   13083: @item argument type incompatible with parameter:
1.26      crook    13084: @cindex argument type mismatch
1.1       anton    13085: This is usually not caught. Some words perform checks, e.g., the control
                   13086: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   13087: mismatch).
                   13088: 
                   13089: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   13090: @cindex Interpreting a compile-only word, for @code{'} etc.
                   13091: @cindex execution token of words with undefined execution semantics
                   13092: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   13093: get an execution token for @code{compile-only-error} (which performs a
                   13094: @code{-14 throw} when executed).
                   13095: 
                   13096: @item dividing by zero:
                   13097: @cindex dividing by zero
                   13098: @cindex floating point unidentified fault, integer division
1.80      anton    13099: On some platforms, this produces a @code{-10 throw} (Division by
1.24      anton    13100: zero); on other systems, this typically results in a @code{-55 throw}
                   13101: (Floating-point unidentified fault).
1.1       anton    13102: 
                   13103: @item insufficient data stack or return stack space:
                   13104: @cindex insufficient data stack or return stack space
                   13105: @cindex stack overflow
1.26      crook    13106: @cindex address alignment exception, stack overflow
1.1       anton    13107: @cindex Invalid memory address, stack overflow
                   13108: Depending on the operating system, the installation, and the invocation
                   13109: of Gforth, this is either checked by the memory management hardware, or
1.24      anton    13110: it is not checked. If it is checked, you typically get a @code{-3 throw}
                   13111: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
                   13112: throw} (Invalid memory address) (depending on the platform and how you
                   13113: achieved the overflow) as soon as the overflow happens. If it is not
                   13114: checked, overflows typically result in mysterious illegal memory
                   13115: accesses, producing @code{-9 throw} (Invalid memory address) or
                   13116: @code{-23 throw} (Address alignment exception); they might also destroy
                   13117: the internal data structure of @code{ALLOCATE} and friends, resulting in
                   13118: various errors in these words.
1.1       anton    13119: 
                   13120: @item insufficient space for loop control parameters:
                   13121: @cindex insufficient space for loop control parameters
1.80      anton    13122: Like other return stack overflows.
1.1       anton    13123: 
                   13124: @item insufficient space in the dictionary:
                   13125: @cindex insufficient space in the dictionary
                   13126: @cindex dictionary overflow
1.12      anton    13127: If you try to allot (either directly with @code{allot}, or indirectly
                   13128: with @code{,}, @code{create} etc.) more memory than available in the
                   13129: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   13130: to access memory beyond the end of the dictionary, the results are
                   13131: similar to stack overflows.
1.1       anton    13132: 
                   13133: @item interpreting a word with undefined interpretation semantics:
                   13134: @cindex interpreting a word with undefined interpretation semantics
                   13135: @cindex Interpreting a compile-only word
                   13136: For some words, we have defined interpretation semantics. For the
                   13137: others: @code{-14 throw} (Interpreting a compile-only word).
                   13138: 
                   13139: @item modifying the contents of the input buffer or a string literal:
                   13140: @cindex modifying the contents of the input buffer or a string literal
                   13141: These are located in writable memory and can be modified.
                   13142: 
                   13143: @item overflow of the pictured numeric output string:
                   13144: @cindex overflow of the pictured numeric output string
                   13145: @cindex pictured numeric output string, overflow
1.24      anton    13146: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1       anton    13147: 
                   13148: @item parsed string overflow:
                   13149: @cindex parsed string overflow
                   13150: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   13151: 
                   13152: @item producing a result out of range:
                   13153: @cindex result out of range
                   13154: On two's complement machines, arithmetic is performed modulo
                   13155: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.166     anton    13156: arithmetic (with appropriate mapping for signed types). Division by
                   13157: zero typically results in a @code{-10 throw} (divide by zero) or
                   13158: @code{-55 throw} (floating point unidentified fault). Overflow on
                   13159: division may result in these errors or in @code{-11 throw} (result out
                   13160: of range).  @code{Gforth-fast} may silently produce bogus results on
                   13161: division overflow or division by zero.  @code{Convert} and
1.24      anton    13162: @code{>number} currently overflow silently.
1.1       anton    13163: 
                   13164: @item reading from an empty data or return stack:
                   13165: @cindex stack empty
                   13166: @cindex stack underflow
1.24      anton    13167: @cindex return stack underflow
1.1       anton    13168: The data stack is checked by the outer (aka text) interpreter after
                   13169: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   13170: underflow) is performed. Apart from that, stacks may be checked or not,
1.24      anton    13171: depending on operating system, installation, and invocation. If they are
                   13172: caught by a check, they typically result in @code{-4 throw} (Stack
                   13173: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
                   13174: (Invalid memory address), depending on the platform and which stack
                   13175: underflows and by how much. Note that even if the system uses checking
                   13176: (through the MMU), your program may have to underflow by a significant
                   13177: number of stack items to trigger the reaction (the reason for this is
                   13178: that the MMU, and therefore the checking, works with a page-size
                   13179: granularity).  If there is no checking, the symptoms resulting from an
                   13180: underflow are similar to those from an overflow.  Unbalanced return
1.80      anton    13181: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24      anton    13182: (Invalid memory address) and Illegal Instruction (typically @code{-260
                   13183: throw}).
1.1       anton    13184: 
                   13185: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   13186: @cindex unexpected end of the input buffer
                   13187: @cindex zero-length string as a name
                   13188: @cindex Attempt to use zero-length string as a name
                   13189: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   13190: use zero-length string as a name). Words like @code{'} probably will not
                   13191: find what they search. Note that it is possible to create zero-length
                   13192: names with @code{nextname} (should it not?).
                   13193: 
                   13194: @item @code{>IN} greater than input buffer:
                   13195: @cindex @code{>IN} greater than input buffer
                   13196: The next invocation of a parsing word returns a string with length 0.
                   13197: 
                   13198: @item @code{RECURSE} appears after @code{DOES>}:
                   13199: @cindex @code{RECURSE} appears after @code{DOES>}
                   13200: Compiles a recursive call to the defining word, not to the defined word.
                   13201: 
                   13202: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   13203: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26      crook    13204: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1       anton    13205: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   13206: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   13207: the end of the file was reached), its source-id may be
                   13208: reused. Therefore, restoring an input source specification referencing a
                   13209: closed file may lead to unpredictable results instead of a @code{-12
                   13210: THROW}.
                   13211: 
                   13212: In the future, Gforth may be able to restore input source specifications
                   13213: from other than the current input source.
                   13214: 
                   13215: @item data space containing definitions gets de-allocated:
                   13216: @cindex data space containing definitions gets de-allocated
                   13217: Deallocation with @code{allot} is not checked. This typically results in
                   13218: memory access faults or execution of illegal instructions.
                   13219: 
                   13220: @item data space read/write with incorrect alignment:
                   13221: @cindex data space read/write with incorrect alignment
                   13222: @cindex alignment faults
1.26      crook    13223: @cindex address alignment exception
1.1       anton    13224: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    13225: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    13226: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   13227: (Invalid memory address). There are reportedly some processors with
1.12      anton    13228: alignment restrictions that do not report violations.
1.1       anton    13229: 
                   13230: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   13231: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   13232: Like other alignment errors.
                   13233: 
                   13234: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   13235: Like other stack underflows.
                   13236: 
                   13237: @item loop control parameters not available:
                   13238: @cindex loop control parameters not available
                   13239: Not checked. The counted loop words simply assume that the top of return
                   13240: stack items are loop control parameters and behave accordingly.
                   13241: 
                   13242: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   13243: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   13244: @cindex last word was headerless
                   13245: @code{abort" last word was headerless"}.
                   13246: 
                   13247: @item name not defined by @code{VALUE} used by @code{TO}:
                   13248: @cindex name not defined by @code{VALUE} used by @code{TO}
                   13249: @cindex @code{TO} on non-@code{VALUE}s
                   13250: @cindex Invalid name argument, @code{TO}
                   13251: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   13252: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   13253: 
                   13254: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   13255: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26      crook    13256: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1       anton    13257: @code{-13 throw} (Undefined word)
                   13258: 
                   13259: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   13260: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   13261: Gforth behaves as if they were of the same type. I.e., you can predict
                   13262: the behaviour by interpreting all parameters as, e.g., signed.
                   13263: 
                   13264: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   13265: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   13266: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   13267: compilation semantics of @code{TO}.
                   13268: 
                   13269: @item String longer than a counted string returned by @code{WORD}:
1.26      crook    13270: @cindex string longer than a counted string returned by @code{WORD}
1.1       anton    13271: @cindex @code{WORD}, string overflow
                   13272: Not checked. The string will be ok, but the count will, of course,
                   13273: contain only the least significant bits of the length.
                   13274: 
                   13275: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   13276: @cindex @code{LSHIFT}, large shift counts
                   13277: @cindex @code{RSHIFT}, large shift counts
                   13278: Processor-dependent. Typical behaviours are returning 0 and using only
                   13279: the low bits of the shift count.
                   13280: 
                   13281: @item word not defined via @code{CREATE}:
                   13282: @cindex @code{>BODY} of non-@code{CREATE}d words
                   13283: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   13284: 
                   13285: @cindex @code{DOES>} of non-@code{CREATE}d words
                   13286: @code{DOES>} changes the execution semantics of the last defined word no
                   13287: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   13288: @code{CREATE , DOES>}.
                   13289: 
                   13290: @item words improperly used outside @code{<#} and @code{#>}:
                   13291: Not checked. As usual, you can expect memory faults.
                   13292: 
                   13293: @end table
                   13294: 
                   13295: 
                   13296: @c ---------------------------------------------------------------------
                   13297: @node core-other,  , core-ambcond, The Core Words
                   13298: @subsection Other system documentation
                   13299: @c ---------------------------------------------------------------------
                   13300: @cindex other system documentation, core words
                   13301: @cindex core words, other system documentation
                   13302: 
                   13303: @table @i
                   13304: @item nonstandard words using @code{PAD}:
                   13305: @cindex @code{PAD} use by nonstandard words
                   13306: None.
                   13307: 
                   13308: @item operator's terminal facilities available:
                   13309: @cindex operator's terminal facilities available
1.80      anton    13310: After processing the OS's command line, Gforth goes into interactive mode,
1.1       anton    13311: and you can give commands to Gforth interactively. The actual facilities
                   13312: available depend on how you invoke Gforth.
                   13313: 
                   13314: @item program data space available:
                   13315: @cindex program data space available
                   13316: @cindex data space available
                   13317: @code{UNUSED .} gives the remaining dictionary space. The total
                   13318: dictionary space can be specified with the @code{-m} switch
                   13319: (@pxref{Invoking Gforth}) when Gforth starts up.
                   13320: 
                   13321: @item return stack space available:
                   13322: @cindex return stack space available
                   13323: You can compute the total return stack space in cells with
                   13324: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   13325: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   13326: 
                   13327: @item stack space available:
                   13328: @cindex stack space available
                   13329: You can compute the total data stack space in cells with
                   13330: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   13331: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   13332: 
                   13333: @item system dictionary space required, in address units:
                   13334: @cindex system dictionary space required, in address units
                   13335: Type @code{here forthstart - .} after startup. At the time of this
                   13336: writing, this gives 80080 (bytes) on a 32-bit system.
                   13337: @end table
                   13338: 
                   13339: 
                   13340: @c =====================================================================
                   13341: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   13342: @section The optional Block word set
                   13343: @c =====================================================================
                   13344: @cindex system documentation, block words
                   13345: @cindex block words, system documentation
                   13346: 
                   13347: @menu
                   13348: * block-idef::                  Implementation Defined Options
                   13349: * block-ambcond::               Ambiguous Conditions               
                   13350: * block-other::                 Other System Documentation                 
                   13351: @end menu
                   13352: 
                   13353: 
                   13354: @c ---------------------------------------------------------------------
                   13355: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   13356: @subsection Implementation Defined Options
                   13357: @c ---------------------------------------------------------------------
                   13358: @cindex implementation-defined options, block words
                   13359: @cindex block words, implementation-defined options
                   13360: 
                   13361: @table @i
                   13362: @item the format for display by @code{LIST}:
                   13363: @cindex @code{LIST} display format
                   13364: First the screen number is displayed, then 16 lines of 64 characters,
                   13365: each line preceded by the line number.
                   13366: 
                   13367: @item the length of a line affected by @code{\}:
                   13368: @cindex length of a line affected by @code{\}
                   13369: @cindex @code{\}, line length in blocks
                   13370: 64 characters.
                   13371: @end table
                   13372: 
                   13373: 
                   13374: @c ---------------------------------------------------------------------
                   13375: @node block-ambcond, block-other, block-idef, The optional Block word set
                   13376: @subsection Ambiguous conditions
                   13377: @c ---------------------------------------------------------------------
                   13378: @cindex block words, ambiguous conditions
                   13379: @cindex ambiguous conditions, block words
                   13380: 
                   13381: @table @i
                   13382: @item correct block read was not possible:
                   13383: @cindex block read not possible
                   13384: Typically results in a @code{throw} of some OS-derived value (between
                   13385: -512 and -2048). If the blocks file was just not long enough, blanks are
                   13386: supplied for the missing portion.
                   13387: 
                   13388: @item I/O exception in block transfer:
                   13389: @cindex I/O exception in block transfer
                   13390: @cindex block transfer, I/O exception
                   13391: Typically results in a @code{throw} of some OS-derived value (between
                   13392: -512 and -2048).
                   13393: 
                   13394: @item invalid block number:
                   13395: @cindex invalid block number
                   13396: @cindex block number invalid
                   13397: @code{-35 throw} (Invalid block number)
                   13398: 
                   13399: @item a program directly alters the contents of @code{BLK}:
                   13400: @cindex @code{BLK}, altering @code{BLK}
                   13401: The input stream is switched to that other block, at the same
                   13402: position. If the storing to @code{BLK} happens when interpreting
                   13403: non-block input, the system will get quite confused when the block ends.
                   13404: 
                   13405: @item no current block buffer for @code{UPDATE}:
                   13406: @cindex @code{UPDATE}, no current block buffer
                   13407: @code{UPDATE} has no effect.
                   13408: 
                   13409: @end table
                   13410: 
                   13411: @c ---------------------------------------------------------------------
                   13412: @node block-other,  , block-ambcond, The optional Block word set
                   13413: @subsection Other system documentation
                   13414: @c ---------------------------------------------------------------------
                   13415: @cindex other system documentation, block words
                   13416: @cindex block words, other system documentation
                   13417: 
                   13418: @table @i
                   13419: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   13420: No restrictions (yet).
                   13421: 
                   13422: @item the number of blocks available for source and data:
                   13423: depends on your disk space.
                   13424: 
                   13425: @end table
                   13426: 
                   13427: 
                   13428: @c =====================================================================
                   13429: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   13430: @section The optional Double Number word set
                   13431: @c =====================================================================
                   13432: @cindex system documentation, double words
                   13433: @cindex double words, system documentation
                   13434: 
                   13435: @menu
                   13436: * double-ambcond::              Ambiguous Conditions              
                   13437: @end menu
                   13438: 
                   13439: 
                   13440: @c ---------------------------------------------------------------------
                   13441: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   13442: @subsection Ambiguous conditions
                   13443: @c ---------------------------------------------------------------------
                   13444: @cindex double words, ambiguous conditions
                   13445: @cindex ambiguous conditions, double words
                   13446: 
                   13447: @table @i
1.29      crook    13448: @item @i{d} outside of range of @i{n} in @code{D>S}:
                   13449: @cindex @code{D>S}, @i{d} out of range of @i{n} 
                   13450: The least significant cell of @i{d} is produced.
1.1       anton    13451: 
                   13452: @end table
                   13453: 
                   13454: 
                   13455: @c =====================================================================
                   13456: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   13457: @section The optional Exception word set
                   13458: @c =====================================================================
                   13459: @cindex system documentation, exception words
                   13460: @cindex exception words, system documentation
                   13461: 
                   13462: @menu
                   13463: * exception-idef::              Implementation Defined Options              
                   13464: @end menu
                   13465: 
                   13466: 
                   13467: @c ---------------------------------------------------------------------
                   13468: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   13469: @subsection Implementation Defined Options
                   13470: @c ---------------------------------------------------------------------
                   13471: @cindex implementation-defined options, exception words
                   13472: @cindex exception words, implementation-defined options
                   13473: 
                   13474: @table @i
                   13475: @item @code{THROW}-codes used in the system:
                   13476: @cindex @code{THROW}-codes used in the system
                   13477: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29      crook    13478: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1       anton    13479: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   13480: allocation operations). The mapping from OS error numbers to throw codes
                   13481: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   13482: undefined OS errors produce a message with a strange number; e.g.,
                   13483: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   13484: @end table
                   13485: 
                   13486: @c =====================================================================
                   13487: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   13488: @section The optional Facility word set
                   13489: @c =====================================================================
                   13490: @cindex system documentation, facility words
                   13491: @cindex facility words, system documentation
                   13492: 
                   13493: @menu
                   13494: * facility-idef::               Implementation Defined Options               
                   13495: * facility-ambcond::            Ambiguous Conditions            
                   13496: @end menu
                   13497: 
                   13498: 
                   13499: @c ---------------------------------------------------------------------
                   13500: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   13501: @subsection Implementation Defined Options
                   13502: @c ---------------------------------------------------------------------
                   13503: @cindex implementation-defined options, facility words
                   13504: @cindex facility words, implementation-defined options
                   13505: 
                   13506: @table @i
                   13507: @item encoding of keyboard events (@code{EKEY}):
                   13508: @cindex keyboard events, encoding in @code{EKEY}
                   13509: @cindex @code{EKEY}, encoding of keyboard events
1.40      anton    13510: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41      anton    13511: Other keys are encoded with the constants @code{k-left}, @code{k-right},
                   13512: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
                   13513: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
                   13514: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40      anton    13515: 
1.1       anton    13516: 
                   13517: @item duration of a system clock tick:
                   13518: @cindex duration of a system clock tick
                   13519: @cindex clock tick duration
                   13520: System dependent. With respect to @code{MS}, the time is specified in
                   13521: microseconds. How well the OS and the hardware implement this, is
                   13522: another question.
                   13523: 
                   13524: @item repeatability to be expected from the execution of @code{MS}:
                   13525: @cindex repeatability to be expected from the execution of @code{MS}
                   13526: @cindex @code{MS}, repeatability to be expected
                   13527: System dependent. On Unix, a lot depends on load. If the system is
                   13528: lightly loaded, and the delay is short enough that Gforth does not get
                   13529: swapped out, the performance should be acceptable. Under MS-DOS and
                   13530: other single-tasking systems, it should be good.
                   13531: 
                   13532: @end table
                   13533: 
                   13534: 
                   13535: @c ---------------------------------------------------------------------
                   13536: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   13537: @subsection Ambiguous conditions
                   13538: @c ---------------------------------------------------------------------
                   13539: @cindex facility words, ambiguous conditions
                   13540: @cindex ambiguous conditions, facility words
                   13541: 
                   13542: @table @i
                   13543: @item @code{AT-XY} can't be performed on user output device:
                   13544: @cindex @code{AT-XY} can't be performed on user output device
                   13545: Largely terminal dependent. No range checks are done on the arguments.
                   13546: No errors are reported. You may see some garbage appearing, you may see
                   13547: simply nothing happen.
                   13548: 
                   13549: @end table
                   13550: 
                   13551: 
                   13552: @c =====================================================================
                   13553: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   13554: @section The optional File-Access word set
                   13555: @c =====================================================================
                   13556: @cindex system documentation, file words
                   13557: @cindex file words, system documentation
                   13558: 
                   13559: @menu
                   13560: * file-idef::                   Implementation Defined Options
                   13561: * file-ambcond::                Ambiguous Conditions                
                   13562: @end menu
                   13563: 
                   13564: @c ---------------------------------------------------------------------
                   13565: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   13566: @subsection Implementation Defined Options
                   13567: @c ---------------------------------------------------------------------
                   13568: @cindex implementation-defined options, file words
                   13569: @cindex file words, implementation-defined options
                   13570: 
                   13571: @table @i
                   13572: @item file access methods used:
                   13573: @cindex file access methods used
                   13574: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   13575: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   13576: @code{wb}): The file is cleared, if it exists, and created, if it does
                   13577: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   13578: @code{create-file} creates a file with 666 permissions modified by your
                   13579: umask.
                   13580: 
                   13581: @item file exceptions:
                   13582: @cindex file exceptions
                   13583: The file words do not raise exceptions (except, perhaps, memory access
                   13584: faults when you pass illegal addresses or file-ids).
                   13585: 
                   13586: @item file line terminator:
                   13587: @cindex file line terminator
                   13588: System-dependent. Gforth uses C's newline character as line
                   13589: terminator. What the actual character code(s) of this are is
                   13590: system-dependent.
                   13591: 
                   13592: @item file name format:
                   13593: @cindex file name format
                   13594: System dependent. Gforth just uses the file name format of your OS.
                   13595: 
                   13596: @item information returned by @code{FILE-STATUS}:
                   13597: @cindex @code{FILE-STATUS}, returned information
                   13598: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   13599: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   13600: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   13601: along with the returned mode.
                   13602: 
                   13603: @item input file state after an exception when including source:
                   13604: @cindex exception when including source
                   13605: All files that are left via the exception are closed.
                   13606: 
1.29      crook    13607: @item @i{ior} values and meaning:
                   13608: @cindex @i{ior} values and meaning
1.68      anton    13609: @cindex @i{wior} values and meaning
1.29      crook    13610: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    13611: intended as throw codes. They typically are in the range
                   13612: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    13613: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    13614: 
                   13615: @item maximum depth of file input nesting:
                   13616: @cindex maximum depth of file input nesting
                   13617: @cindex file input nesting, maximum depth
                   13618: limited by the amount of return stack, locals/TIB stack, and the number
                   13619: of open files available. This should not give you troubles.
                   13620: 
                   13621: @item maximum size of input line:
                   13622: @cindex maximum size of input line
                   13623: @cindex input line size, maximum
                   13624: @code{/line}. Currently 255.
                   13625: 
                   13626: @item methods of mapping block ranges to files:
                   13627: @cindex mapping block ranges to files
                   13628: @cindex files containing blocks
                   13629: @cindex blocks in files
                   13630: By default, blocks are accessed in the file @file{blocks.fb} in the
                   13631: current working directory. The file can be switched with @code{USE}.
                   13632: 
                   13633: @item number of string buffers provided by @code{S"}:
                   13634: @cindex @code{S"}, number of string buffers
                   13635: 1
                   13636: 
                   13637: @item size of string buffer used by @code{S"}:
                   13638: @cindex @code{S"}, size of string buffer
                   13639: @code{/line}. currently 255.
                   13640: 
                   13641: @end table
                   13642: 
                   13643: @c ---------------------------------------------------------------------
                   13644: @node file-ambcond,  , file-idef, The optional File-Access word set
                   13645: @subsection Ambiguous conditions
                   13646: @c ---------------------------------------------------------------------
                   13647: @cindex file words, ambiguous conditions
                   13648: @cindex ambiguous conditions, file words
                   13649: 
                   13650: @table @i
                   13651: @item attempting to position a file outside its boundaries:
                   13652: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   13653: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   13654: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   13655: 
                   13656: @item attempting to read from file positions not yet written:
                   13657: @cindex reading from file positions not yet written
                   13658: End-of-file, i.e., zero characters are read and no error is reported.
                   13659: 
1.29      crook    13660: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
                   13661: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
1.1       anton    13662: An appropriate exception may be thrown, but a memory fault or other
                   13663: problem is more probable.
                   13664: 
1.29      crook    13665: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
                   13666: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
                   13667: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
                   13668: The @i{ior} produced by the operation, that discovered the problem, is
1.1       anton    13669: thrown.
                   13670: 
                   13671: @item named file cannot be opened (@code{INCLUDED}):
                   13672: @cindex @code{INCLUDED}, named file cannot be opened
1.29      crook    13673: The @i{ior} produced by @code{open-file} is thrown.
1.1       anton    13674: 
                   13675: @item requesting an unmapped block number:
                   13676: @cindex unmapped block numbers
                   13677: There are no unmapped legal block numbers. On some operating systems,
                   13678: writing a block with a large number may overflow the file system and
                   13679: have an error message as consequence.
                   13680: 
                   13681: @item using @code{source-id} when @code{blk} is non-zero:
                   13682: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   13683: @code{source-id} performs its function. Typically it will give the id of
                   13684: the source which loaded the block. (Better ideas?)
                   13685: 
                   13686: @end table
                   13687: 
                   13688: 
                   13689: @c =====================================================================
                   13690: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   13691: @section The optional Floating-Point word set
                   13692: @c =====================================================================
                   13693: @cindex system documentation, floating-point words
                   13694: @cindex floating-point words, system documentation
                   13695: 
                   13696: @menu
                   13697: * floating-idef::               Implementation Defined Options
                   13698: * floating-ambcond::            Ambiguous Conditions            
                   13699: @end menu
                   13700: 
                   13701: 
                   13702: @c ---------------------------------------------------------------------
                   13703: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   13704: @subsection Implementation Defined Options
                   13705: @c ---------------------------------------------------------------------
                   13706: @cindex implementation-defined options, floating-point words
                   13707: @cindex floating-point words, implementation-defined options
                   13708: 
                   13709: @table @i
                   13710: @item format and range of floating point numbers:
                   13711: @cindex format and range of floating point numbers
                   13712: @cindex floating point numbers, format and range
                   13713: System-dependent; the @code{double} type of C.
                   13714: 
1.29      crook    13715: @item results of @code{REPRESENT} when @i{float} is out of range:
                   13716: @cindex  @code{REPRESENT}, results when @i{float} is out of range
1.1       anton    13717: System dependent; @code{REPRESENT} is implemented using the C library
                   13718: function @code{ecvt()} and inherits its behaviour in this respect.
                   13719: 
                   13720: @item rounding or truncation of floating-point numbers:
                   13721: @cindex rounding of floating-point numbers
                   13722: @cindex truncation of floating-point numbers
                   13723: @cindex floating-point numbers, rounding or truncation
                   13724: System dependent; the rounding behaviour is inherited from the hosting C
                   13725: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   13726: nearest, and break ties by rounding to even (i.e., such that the last
                   13727: bit of the mantissa is 0).
                   13728: 
                   13729: @item size of floating-point stack:
                   13730: @cindex floating-point stack size
                   13731: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   13732: the floating-point stack (in floats). You can specify this on startup
                   13733: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   13734: 
                   13735: @item width of floating-point stack:
                   13736: @cindex floating-point stack width 
                   13737: @code{1 floats}.
                   13738: 
                   13739: @end table
                   13740: 
                   13741: 
                   13742: @c ---------------------------------------------------------------------
                   13743: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   13744: @subsection Ambiguous conditions
                   13745: @c ---------------------------------------------------------------------
                   13746: @cindex floating-point words, ambiguous conditions
                   13747: @cindex ambiguous conditions, floating-point words
                   13748: 
                   13749: @table @i
                   13750: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   13751: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   13752: System-dependent. Typically results in a @code{-23 THROW} like other
                   13753: alignment violations.
                   13754: 
                   13755: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   13756: @cindex @code{f@@} used with an address that is not float aligned
                   13757: @cindex @code{f!} used with an address that is not float aligned
                   13758: System-dependent. Typically results in a @code{-23 THROW} like other
                   13759: alignment violations.
                   13760: 
                   13761: @item floating-point result out of range:
                   13762: @cindex floating-point result out of range
1.80      anton    13763: System-dependent. Can result in a @code{-43 throw} (floating point
                   13764: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
                   13765: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1       anton    13766: unidentified fault), or can produce a special value representing, e.g.,
                   13767: Infinity.
                   13768: 
                   13769: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   13770: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   13771: System-dependent. Typically results in an alignment fault like other
                   13772: alignment violations.
                   13773: 
1.35      anton    13774: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   13775: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1       anton    13776: The floating-point number is converted into decimal nonetheless.
                   13777: 
                   13778: @item Both arguments are equal to zero (@code{FATAN2}):
                   13779: @cindex @code{FATAN2}, both arguments are equal to zero
                   13780: System-dependent. @code{FATAN2} is implemented using the C library
                   13781: function @code{atan2()}.
                   13782: 
1.29      crook    13783: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
                   13784: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
                   13785: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1       anton    13786: because of small errors and the tan will be a very large (or very small)
                   13787: but finite number.
                   13788: 
1.29      crook    13789: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
                   13790: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1       anton    13791: The result is rounded to the nearest float.
                   13792: 
                   13793: @item dividing by zero:
                   13794: @cindex dividing by zero, floating-point
                   13795: @cindex floating-point dividing by zero
                   13796: @cindex floating-point unidentified fault, FP divide-by-zero
1.80      anton    13797: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
                   13798: (floating point divide by zero) or @code{-55 throw} (Floating-point
                   13799: unidentified fault).
1.1       anton    13800: 
                   13801: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   13802: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   13803: System dependent. On IEEE-FP based systems the number is converted into
                   13804: an infinity.
                   13805: 
1.29      crook    13806: @item @i{float}<1 (@code{FACOSH}):
                   13807: @cindex @code{FACOSH}, @i{float}<1
1.1       anton    13808: @cindex floating-point unidentified fault, @code{FACOSH}
1.80      anton    13809: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1       anton    13810: 
1.29      crook    13811: @item @i{float}=<-1 (@code{FLNP1}):
                   13812: @cindex @code{FLNP1}, @i{float}=<-1
1.1       anton    13813: @cindex floating-point unidentified fault, @code{FLNP1}
1.80      anton    13814: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
                   13815: negative infinity for @i{float}=-1).
1.1       anton    13816: 
1.29      crook    13817: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
                   13818: @cindex @code{FLN}, @i{float}=<0
                   13819: @cindex @code{FLOG}, @i{float}=<0
1.1       anton    13820: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80      anton    13821: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
                   13822: negative infinity for @i{float}=0).
1.1       anton    13823: 
1.29      crook    13824: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
                   13825: @cindex @code{FASINH}, @i{float}<0
                   13826: @cindex @code{FSQRT}, @i{float}<0
1.1       anton    13827: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80      anton    13828: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
                   13829: @code{fasinh} some platforms produce a NaN, others a number (bug in the
                   13830: C library?).
1.1       anton    13831: 
1.29      crook    13832: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
                   13833: @cindex @code{FACOS}, |@i{float}|>1
                   13834: @cindex @code{FASIN}, |@i{float}|>1
                   13835: @cindex @code{FATANH}, |@i{float}|>1
1.1       anton    13836: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80      anton    13837: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1       anton    13838: 
1.29      crook    13839: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
                   13840: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1       anton    13841: @cindex floating-point unidentified fault, @code{F>D}
1.80      anton    13842: Platform-dependent; typically, some double number is produced and no
                   13843: error is reported.
1.1       anton    13844: 
                   13845: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   13846: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80      anton    13847: @code{Precision} characters of the numeric output area are used.  If
                   13848: @code{precision} is too high, these words will smash the data or code
                   13849: close to @code{here}.
1.1       anton    13850: @end table
                   13851: 
                   13852: @c =====================================================================
                   13853: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   13854: @section The optional Locals word set
                   13855: @c =====================================================================
                   13856: @cindex system documentation, locals words
                   13857: @cindex locals words, system documentation
                   13858: 
                   13859: @menu
                   13860: * locals-idef::                 Implementation Defined Options                 
                   13861: * locals-ambcond::              Ambiguous Conditions              
                   13862: @end menu
                   13863: 
                   13864: 
                   13865: @c ---------------------------------------------------------------------
                   13866: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   13867: @subsection Implementation Defined Options
                   13868: @c ---------------------------------------------------------------------
                   13869: @cindex implementation-defined options, locals words
                   13870: @cindex locals words, implementation-defined options
                   13871: 
                   13872: @table @i
                   13873: @item maximum number of locals in a definition:
                   13874: @cindex maximum number of locals in a definition
                   13875: @cindex locals, maximum number in a definition
                   13876: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   13877: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   13878: characters. The number of locals in a definition is bounded by the size
                   13879: of locals-buffer, which contains the names of the locals.
                   13880: 
                   13881: @end table
                   13882: 
                   13883: 
                   13884: @c ---------------------------------------------------------------------
                   13885: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   13886: @subsection Ambiguous conditions
                   13887: @c ---------------------------------------------------------------------
                   13888: @cindex locals words, ambiguous conditions
                   13889: @cindex ambiguous conditions, locals words
                   13890: 
                   13891: @table @i
                   13892: @item executing a named local in interpretation state:
                   13893: @cindex local in interpretation state
                   13894: @cindex Interpreting a compile-only word, for a local
                   13895: Locals have no interpretation semantics. If you try to perform the
                   13896: interpretation semantics, you will get a @code{-14 throw} somewhere
                   13897: (Interpreting a compile-only word). If you perform the compilation
                   13898: semantics, the locals access will be compiled (irrespective of state).
                   13899: 
1.29      crook    13900: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1       anton    13901: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   13902: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   13903: @cindex Invalid name argument, @code{TO}
                   13904: @code{-32 throw} (Invalid name argument)
                   13905: 
                   13906: @end table
                   13907: 
                   13908: 
                   13909: @c =====================================================================
                   13910: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   13911: @section The optional Memory-Allocation word set
                   13912: @c =====================================================================
                   13913: @cindex system documentation, memory-allocation words
                   13914: @cindex memory-allocation words, system documentation
                   13915: 
                   13916: @menu
                   13917: * memory-idef::                 Implementation Defined Options                 
                   13918: @end menu
                   13919: 
                   13920: 
                   13921: @c ---------------------------------------------------------------------
                   13922: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   13923: @subsection Implementation Defined Options
                   13924: @c ---------------------------------------------------------------------
                   13925: @cindex implementation-defined options, memory-allocation words
                   13926: @cindex memory-allocation words, implementation-defined options
                   13927: 
                   13928: @table @i
1.29      crook    13929: @item values and meaning of @i{ior}:
                   13930: @cindex  @i{ior} values and meaning
                   13931: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    13932: intended as throw codes. They typically are in the range
                   13933: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    13934: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    13935: 
                   13936: @end table
                   13937: 
                   13938: @c =====================================================================
                   13939: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   13940: @section The optional Programming-Tools word set
                   13941: @c =====================================================================
                   13942: @cindex system documentation, programming-tools words
                   13943: @cindex programming-tools words, system documentation
                   13944: 
                   13945: @menu
                   13946: * programming-idef::            Implementation Defined Options            
                   13947: * programming-ambcond::         Ambiguous Conditions         
                   13948: @end menu
                   13949: 
                   13950: 
                   13951: @c ---------------------------------------------------------------------
                   13952: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   13953: @subsection Implementation Defined Options
                   13954: @c ---------------------------------------------------------------------
                   13955: @cindex implementation-defined options, programming-tools words
                   13956: @cindex programming-tools words, implementation-defined options
                   13957: 
                   13958: @table @i
                   13959: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   13960: @cindex @code{;CODE} ending sequence
                   13961: @cindex @code{CODE} ending sequence
                   13962: @code{END-CODE}
                   13963: 
                   13964: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   13965: @cindex @code{;CODE}, processing input
                   13966: @cindex @code{CODE}, processing input
                   13967: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   13968: the input is processed by the text interpreter, (starting) in interpret
                   13969: state.
                   13970: 
                   13971: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   13972: @cindex @code{ASSEMBLER}, search order capability
                   13973: The ANS Forth search order word set.
                   13974: 
                   13975: @item source and format of display by @code{SEE}:
                   13976: @cindex @code{SEE}, source and format of output
1.80      anton    13977: The source for @code{see} is the executable code used by the inner
1.1       anton    13978: interpreter.  The current @code{see} tries to output Forth source code
1.80      anton    13979: (and on some platforms, assembly code for primitives) as well as
                   13980: possible.
1.1       anton    13981: 
                   13982: @end table
                   13983: 
                   13984: @c ---------------------------------------------------------------------
                   13985: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   13986: @subsection Ambiguous conditions
                   13987: @c ---------------------------------------------------------------------
                   13988: @cindex programming-tools words, ambiguous conditions
                   13989: @cindex ambiguous conditions, programming-tools words
                   13990: 
                   13991: @table @i
                   13992: 
1.21      crook    13993: @item deleting the compilation word list (@code{FORGET}):
                   13994: @cindex @code{FORGET}, deleting the compilation word list
1.1       anton    13995: Not implemented (yet).
                   13996: 
1.29      crook    13997: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
                   13998: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
                   13999: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1       anton    14000: @cindex control-flow stack underflow
                   14001: This typically results in an @code{abort"} with a descriptive error
                   14002: message (may change into a @code{-22 throw} (Control structure mismatch)
                   14003: in the future). You may also get a memory access error. If you are
                   14004: unlucky, this ambiguous condition is not caught.
                   14005: 
1.29      crook    14006: @item @i{name} can't be found (@code{FORGET}):
                   14007: @cindex @code{FORGET}, @i{name} can't be found
1.1       anton    14008: Not implemented (yet).
                   14009: 
1.29      crook    14010: @item @i{name} not defined via @code{CREATE}:
                   14011: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1       anton    14012: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   14013: the execution semantics of the last defined word no matter how it was
                   14014: defined.
                   14015: 
                   14016: @item @code{POSTPONE} applied to @code{[IF]}:
                   14017: @cindex @code{POSTPONE} applied to @code{[IF]}
                   14018: @cindex @code{[IF]} and @code{POSTPONE}
                   14019: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   14020: equivalent to @code{[IF]}.
                   14021: 
                   14022: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   14023: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   14024: Continue in the same state of conditional compilation in the next outer
                   14025: input source. Currently there is no warning to the user about this.
                   14026: 
                   14027: @item removing a needed definition (@code{FORGET}):
                   14028: @cindex @code{FORGET}, removing a needed definition
                   14029: Not implemented (yet).
                   14030: 
                   14031: @end table
                   14032: 
                   14033: 
                   14034: @c =====================================================================
                   14035: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   14036: @section The optional Search-Order word set
                   14037: @c =====================================================================
                   14038: @cindex system documentation, search-order words
                   14039: @cindex search-order words, system documentation
                   14040: 
                   14041: @menu
                   14042: * search-idef::                 Implementation Defined Options                 
                   14043: * search-ambcond::              Ambiguous Conditions              
                   14044: @end menu
                   14045: 
                   14046: 
                   14047: @c ---------------------------------------------------------------------
                   14048: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   14049: @subsection Implementation Defined Options
                   14050: @c ---------------------------------------------------------------------
                   14051: @cindex implementation-defined options, search-order words
                   14052: @cindex search-order words, implementation-defined options
                   14053: 
                   14054: @table @i
                   14055: @item maximum number of word lists in search order:
                   14056: @cindex maximum number of word lists in search order
                   14057: @cindex search order, maximum depth
                   14058: @code{s" wordlists" environment? drop .}. Currently 16.
                   14059: 
                   14060: @item minimum search order:
                   14061: @cindex minimum search order
                   14062: @cindex search order, minimum
                   14063: @code{root root}.
                   14064: 
                   14065: @end table
                   14066: 
                   14067: @c ---------------------------------------------------------------------
                   14068: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   14069: @subsection Ambiguous conditions
                   14070: @c ---------------------------------------------------------------------
                   14071: @cindex search-order words, ambiguous conditions
                   14072: @cindex ambiguous conditions, search-order words
                   14073: 
                   14074: @table @i
1.21      crook    14075: @item changing the compilation word list (during compilation):
                   14076: @cindex changing the compilation word list (during compilation)
                   14077: @cindex compilation word list, change before definition ends
                   14078: The word is entered into the word list that was the compilation word list
1.1       anton    14079: at the start of the definition. Any changes to the name field (e.g.,
                   14080: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116     anton    14081: are applied to the latest defined word (as reported by @code{latest} or
                   14082: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1       anton    14083: 
                   14084: @item search order empty (@code{previous}):
                   14085: @cindex @code{previous}, search order empty
1.26      crook    14086: @cindex vocstack empty, @code{previous}
1.1       anton    14087: @code{abort" Vocstack empty"}.
                   14088: 
                   14089: @item too many word lists in search order (@code{also}):
                   14090: @cindex @code{also}, too many word lists in search order
1.26      crook    14091: @cindex vocstack full, @code{also}
1.1       anton    14092: @code{abort" Vocstack full"}.
                   14093: 
                   14094: @end table
                   14095: 
                   14096: @c ***************************************************************
1.65      anton    14097: @node Standard vs Extensions, Model, ANS conformance, Top
                   14098: @chapter Should I use Gforth extensions?
                   14099: @cindex Gforth extensions
                   14100: 
                   14101: As you read through the rest of this manual, you will see documentation
                   14102: for @i{Standard} words, and documentation for some appealing Gforth
                   14103: @i{extensions}. You might ask yourself the question: @i{``Should I
                   14104: restrict myself to the standard, or should I use the extensions?''}
                   14105: 
                   14106: The answer depends on the goals you have for the program you are working
                   14107: on:
                   14108: 
                   14109: @itemize @bullet
                   14110: 
                   14111: @item Is it just for yourself or do you want to share it with others?
                   14112: 
                   14113: @item
                   14114: If you want to share it, do the others all use Gforth?
                   14115: 
                   14116: @item
                   14117: If it is just for yourself, do you want to restrict yourself to Gforth?
                   14118: 
                   14119: @end itemize
                   14120: 
                   14121: If restricting the program to Gforth is ok, then there is no reason not
                   14122: to use extensions.  It is still a good idea to keep to the standard
                   14123: where it is easy, in case you want to reuse these parts in another
                   14124: program that you want to be portable.
                   14125: 
                   14126: If you want to be able to port the program to other Forth systems, there
                   14127: are the following points to consider:
                   14128: 
                   14129: @itemize @bullet
                   14130: 
                   14131: @item
                   14132: Most Forth systems that are being maintained support the ANS Forth
                   14133: standard.  So if your program complies with the standard, it will be
                   14134: portable among many systems.
                   14135: 
                   14136: @item
                   14137: A number of the Gforth extensions can be implemented in ANS Forth using
                   14138: public-domain files provided in the @file{compat/} directory. These are
                   14139: mentioned in the text in passing.  There is no reason not to use these
                   14140: extensions, your program will still be ANS Forth compliant; just include
                   14141: the appropriate compat files with your program.
                   14142: 
                   14143: @item
                   14144: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
                   14145: analyse your program and determine what non-Standard words it relies
                   14146: upon.  However, it does not check whether you use standard words in a
                   14147: non-standard way.
                   14148: 
                   14149: @item
                   14150: Some techniques are not standardized by ANS Forth, and are hard or
                   14151: impossible to implement in a standard way, but can be implemented in
                   14152: most Forth systems easily, and usually in similar ways (e.g., accessing
                   14153: word headers).  Forth has a rich historical precedent for programmers
                   14154: taking advantage of implementation-dependent features of their tools
                   14155: (for example, relying on a knowledge of the dictionary
                   14156: structure). Sometimes these techniques are necessary to extract every
                   14157: last bit of performance from the hardware, sometimes they are just a
                   14158: programming shorthand.
                   14159: 
                   14160: @item
                   14161: Does using a Gforth extension save more work than the porting this part
                   14162: to other Forth systems (if any) will cost?
                   14163: 
                   14164: @item
                   14165: Is the additional functionality worth the reduction in portability and
                   14166: the additional porting problems?
                   14167: 
                   14168: @end itemize
                   14169: 
                   14170: In order to perform these consideratios, you need to know what's
                   14171: standard and what's not.  This manual generally states if something is
1.81      anton    14172: non-standard, but the authoritative source is the
                   14173: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65      anton    14174: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
                   14175: into the thought processes of the technical committee.
                   14176: 
                   14177: Note also that portability between Forth systems is not the only
                   14178: portability issue; there is also the issue of portability between
                   14179: different platforms (processor/OS combinations).
                   14180: 
                   14181: @c ***************************************************************
                   14182: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1       anton    14183: @chapter Model
                   14184: 
                   14185: This chapter has yet to be written. It will contain information, on
                   14186: which internal structures you can rely.
                   14187: 
                   14188: @c ***************************************************************
                   14189: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   14190: @chapter Integrating Gforth into C programs
                   14191: 
                   14192: This is not yet implemented.
                   14193: 
                   14194: Several people like to use Forth as scripting language for applications
                   14195: that are otherwise written in C, C++, or some other language.
                   14196: 
                   14197: The Forth system ATLAST provides facilities for embedding it into
                   14198: applications; unfortunately it has several disadvantages: most
                   14199: importantly, it is not based on ANS Forth, and it is apparently dead
                   14200: (i.e., not developed further and not supported). The facilities
1.21      crook    14201: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1       anton    14202: making the switch should not be hard.
                   14203: 
                   14204: We also tried to design the interface such that it can easily be
                   14205: implemented by other Forth systems, so that we may one day arrive at a
                   14206: standardized interface. Such a standard interface would allow you to
                   14207: replace the Forth system without having to rewrite C code.
                   14208: 
                   14209: You embed the Gforth interpreter by linking with the library
                   14210: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   14211: global symbols in this library that belong to the interface, have the
                   14212: prefix @code{forth_}. (Global symbols that are used internally have the
                   14213: prefix @code{gforth_}).
                   14214: 
                   14215: You can include the declarations of Forth types and the functions and
                   14216: variables of the interface with @code{#include <forth.h>}.
                   14217: 
                   14218: Types.
                   14219: 
                   14220: Variables.
                   14221: 
                   14222: Data and FP Stack pointer. Area sizes.
                   14223: 
                   14224: functions.
                   14225: 
                   14226: forth_init(imagefile)
                   14227: forth_evaluate(string) exceptions?
                   14228: forth_goto(address) (or forth_execute(xt)?)
                   14229: forth_continue() (a corountining mechanism)
                   14230: 
                   14231: Adding primitives.
                   14232: 
                   14233: No checking.
                   14234: 
                   14235: Signals?
                   14236: 
                   14237: Accessing the Stacks
                   14238: 
1.26      crook    14239: @c ******************************************************************
1.1       anton    14240: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   14241: @chapter Emacs and Gforth
                   14242: @cindex Emacs and Gforth
                   14243: 
                   14244: @cindex @file{gforth.el}
                   14245: @cindex @file{forth.el}
                   14246: @cindex Rydqvist, Goran
1.107     dvdkhlng 14247: @cindex Kuehling, David
1.1       anton    14248: @cindex comment editing commands
                   14249: @cindex @code{\}, editing with Emacs
                   14250: @cindex debug tracer editing commands
                   14251: @cindex @code{~~}, removal with Emacs
                   14252: @cindex Forth mode in Emacs
1.107     dvdkhlng 14253: 
1.1       anton    14254: Gforth comes with @file{gforth.el}, an improved version of
                   14255: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26      crook    14256: improvements are:
                   14257: 
                   14258: @itemize @bullet
                   14259: @item
1.107     dvdkhlng 14260: A better handling of indentation.
                   14261: @item
                   14262: A custom hilighting engine for Forth-code.
1.26      crook    14263: @item
                   14264: Comment paragraph filling (@kbd{M-q})
                   14265: @item
                   14266: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
                   14267: @item
                   14268: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41      anton    14269: @item
                   14270: Support of the @code{info-lookup} feature for looking up the
                   14271: documentation of a word.
1.107     dvdkhlng 14272: @item
                   14273: Support for reading and writing blocks files.
1.26      crook    14274: @end itemize
                   14275: 
1.107     dvdkhlng 14276: To get a basic description of these features, enter Forth mode and
                   14277: type @kbd{C-h m}.
1.1       anton    14278: 
                   14279: @cindex source location of error or debugging output in Emacs
                   14280: @cindex error output, finding the source location in Emacs
                   14281: @cindex debugging output, finding the source location in Emacs
                   14282: In addition, Gforth supports Emacs quite well: The source code locations
                   14283: given in error messages, debugging output (from @code{~~}) and failed
                   14284: assertion messages are in the right format for Emacs' compilation mode
                   14285: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   14286: Manual}) so the source location corresponding to an error or other
                   14287: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   14288: @kbd{C-c C-c} for the error under the cursor).
                   14289: 
1.107     dvdkhlng 14290: @cindex viewing the documentation of a word in Emacs
                   14291: @cindex context-sensitive help
                   14292: Moreover, for words documented in this manual, you can look up the
                   14293: glossary entry quickly by using @kbd{C-h TAB}
                   14294: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
                   14295: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
                   14296: later and does not work for words containing @code{:}.
                   14297: 
                   14298: @menu
                   14299: * Installing gforth.el::        Making Emacs aware of Forth.
                   14300: * Emacs Tags::                  Viewing the source of a word in Emacs.
                   14301: * Hilighting::                  Making Forth code look prettier.
                   14302: * Auto-Indentation::            Customizing auto-indentation.
                   14303: * Blocks Files::                Reading and writing blocks files.
                   14304: @end menu
                   14305: 
                   14306: @c ----------------------------------
1.109     anton    14307: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107     dvdkhlng 14308: @section Installing gforth.el
                   14309: @cindex @file{.emacs}
                   14310: @cindex @file{gforth.el}, installation
                   14311: To make the features from @file{gforth.el} available in Emacs, add
                   14312: the following lines to your @file{.emacs} file:
                   14313: 
                   14314: @example
                   14315: (autoload 'forth-mode "gforth.el")
                   14316: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) 
                   14317:                            auto-mode-alist))
                   14318: (autoload 'forth-block-mode "gforth.el")
                   14319: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode) 
                   14320:                            auto-mode-alist))
                   14321: (add-hook 'forth-mode-hook (function (lambda ()
                   14322:    ;; customize variables here:
                   14323:    (setq forth-indent-level 4)
                   14324:    (setq forth-minor-indent-level 2)
                   14325:    (setq forth-hilight-level 3)
                   14326:    ;;; ...
                   14327: )))
                   14328: @end example
                   14329: 
                   14330: @c ----------------------------------
                   14331: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
                   14332: @section Emacs Tags
1.1       anton    14333: @cindex @file{TAGS} file
                   14334: @cindex @file{etags.fs}
                   14335: @cindex viewing the source of a word in Emacs
1.43      anton    14336: @cindex @code{require}, placement in files
                   14337: @cindex @code{include}, placement in files
1.107     dvdkhlng 14338: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
                   14339: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1       anton    14340: contains the definitions of all words defined afterwards. You can then
1.107     dvdkhlng 14341: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1       anton    14342: several tags files at the same time (e.g., one for the Gforth sources
                   14343: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   14344: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   14345: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43      anton    14346: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
                   14347: with @file{etags.fs}, you should avoid putting definitions both before
                   14348: and after @code{require} etc., otherwise you will see the same file
                   14349: visited several times by commands like @code{tags-search}.
1.1       anton    14350: 
1.107     dvdkhlng 14351: @c ----------------------------------
                   14352: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
                   14353: @section Hilighting
                   14354: @cindex hilighting Forth code in Emacs
                   14355: @cindex highlighting Forth code in Emacs
                   14356: @file{gforth.el} comes with a custom source hilighting engine.  When
                   14357: you open a file in @code{forth-mode}, it will be completely parsed,
                   14358: assigning faces to keywords, comments, strings etc.  While you edit
                   14359: the file, modified regions get parsed and updated on-the-fly. 
                   14360: 
                   14361: Use the variable `forth-hilight-level' to change the level of
                   14362: decoration from 0 (no hilighting at all) to 3 (the default).  Even if
                   14363: you set the hilighting level to 0, the parser will still work in the
                   14364: background, collecting information about whether regions of text are
                   14365: ``compiled'' or ``interpreted''.  Those information are required for
                   14366: auto-indentation to work properly.  Set `forth-disable-parser' to
                   14367: non-nil if your computer is too slow to handle parsing.  This will
                   14368: have an impact on the smartness of the auto-indentation engine,
                   14369: though.
                   14370: 
                   14371: Sometimes Forth sources define new features that should be hilighted,
                   14372: new control structures, defining-words etc.  You can use the variable
                   14373: `forth-custom-words' to make @code{forth-mode} hilight additional
                   14374: words and constructs.  See the docstring of `forth-words' for details
                   14375: (in Emacs, type @kbd{C-h v forth-words}).
                   14376: 
                   14377: `forth-custom-words' is meant to be customized in your
                   14378: @file{.emacs} file.  To customize hilighing in a file-specific manner,
                   14379: set `forth-local-words' in a local-variables section at the end of
                   14380: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
                   14381: 
                   14382: Example:
                   14383: @example
                   14384: 0 [IF]
                   14385:    Local Variables:
                   14386:    forth-local-words:
                   14387:       ((("t:") definition-starter (font-lock-keyword-face . 1)
                   14388:         "[ \t\n]" t name (font-lock-function-name-face . 3))
                   14389:        ((";t") definition-ender (font-lock-keyword-face . 1)))
                   14390:    End:
                   14391: [THEN]
                   14392: @end example
                   14393: 
                   14394: @c ----------------------------------
                   14395: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
                   14396: @section Auto-Indentation
                   14397: @cindex auto-indentation of Forth code in Emacs
                   14398: @cindex indentation of Forth code in Emacs
                   14399: @code{forth-mode} automatically tries to indent lines in a smart way,
                   14400: whenever you type @key{TAB} or break a line with @kbd{C-m}.
                   14401: 
                   14402: Simple customization can be achieved by setting
                   14403: `forth-indent-level' and `forth-minor-indent-level' in your
                   14404: @file{.emacs} file. For historical reasons @file{gforth.el} indents
                   14405: per default by multiples of 4 columns.  To use the more traditional
                   14406: 3-column indentation, add the following lines to your @file{.emacs}:
                   14407: 
                   14408: @example
                   14409: (add-hook 'forth-mode-hook (function (lambda ()
                   14410:    ;; customize variables here:
                   14411:    (setq forth-indent-level 3)
                   14412:    (setq forth-minor-indent-level 1)
                   14413: )))
                   14414: @end example
                   14415: 
                   14416: If you want indentation to recognize non-default words, customize it
                   14417: by setting `forth-custom-indent-words' in your @file{.emacs}.  See the
                   14418: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
                   14419: v forth-indent-words}).
                   14420: 
                   14421: To customize indentation in a file-specific manner, set
                   14422: `forth-local-indent-words' in a local-variables section at the end of
                   14423: your source file (@pxref{Local Variables in Files, Variables,,emacs,
                   14424: Emacs Manual}).
                   14425: 
                   14426: Example:
                   14427: @example
                   14428: 0 [IF]
                   14429:    Local Variables:
                   14430:    forth-local-indent-words:
                   14431:       ((("t:") (0 . 2) (0 . 2))
                   14432:        ((";t") (-2 . 0) (0 . -2)))
                   14433:    End:
                   14434: [THEN]
                   14435: @end example
                   14436: 
                   14437: @c ----------------------------------
1.109     anton    14438: @node Blocks Files,  , Auto-Indentation, Emacs and Gforth
1.107     dvdkhlng 14439: @section Blocks Files
                   14440: @cindex blocks files, use with Emacs
                   14441: @code{forth-mode} Autodetects blocks files by checking whether the
                   14442: length of the first line exceeds 1023 characters.  It then tries to
                   14443: convert the file into normal text format.  When you save the file, it
                   14444: will be written to disk as normal stream-source file.
                   14445: 
                   14446: If you want to write blocks files, use @code{forth-blocks-mode}.  It
                   14447: inherits all the features from @code{forth-mode}, plus some additions:
1.41      anton    14448: 
1.107     dvdkhlng 14449: @itemize @bullet
                   14450: @item
                   14451: Files are written to disk in blocks file format.
                   14452: @item
                   14453: Screen numbers are displayed in the mode line (enumerated beginning
                   14454: with the value of `forth-block-base')
                   14455: @item
                   14456: Warnings are displayed when lines exceed 64 characters.
                   14457: @item
                   14458: The beginning of the currently edited block is marked with an
                   14459: overlay-arrow. 
                   14460: @end itemize
1.41      anton    14461: 
1.107     dvdkhlng 14462: There are some restrictions you should be aware of.  When you open a
                   14463: blocks file that contains tabulator or newline characters, these
                   14464: characters will be translated into spaces when the file is written
                   14465: back to disk.  If tabs or newlines are encountered during blocks file
                   14466: reading, an error is output to the echo area. So have a look at the
                   14467: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1       anton    14468: 
1.107     dvdkhlng 14469: Please consult the docstring of @code{forth-blocks-mode} for more
                   14470: information by typing @kbd{C-h v forth-blocks-mode}).
1.1       anton    14471: 
1.26      crook    14472: @c ******************************************************************
1.1       anton    14473: @node Image Files, Engine, Emacs and Gforth, Top
                   14474: @chapter Image Files
1.26      crook    14475: @cindex image file
                   14476: @cindex @file{.fi} files
1.1       anton    14477: @cindex precompiled Forth code
                   14478: @cindex dictionary in persistent form
                   14479: @cindex persistent form of dictionary
                   14480: 
                   14481: An image file is a file containing an image of the Forth dictionary,
                   14482: i.e., compiled Forth code and data residing in the dictionary.  By
                   14483: convention, we use the extension @code{.fi} for image files.
                   14484: 
                   14485: @menu
1.18      anton    14486: * Image Licensing Issues::      Distribution terms for images.
                   14487: * Image File Background::       Why have image files?
1.67      anton    14488: * Non-Relocatable Image Files::  don't always work.
1.18      anton    14489: * Data-Relocatable Image Files::  are better.
1.67      anton    14490: * Fully Relocatable Image Files::  better yet.
1.18      anton    14491: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.29      crook    14492: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.18      anton    14493: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    14494: @end menu
                   14495: 
1.18      anton    14496: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   14497: @section Image Licensing Issues
                   14498: @cindex license for images
                   14499: @cindex image license
                   14500: 
                   14501: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   14502: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   14503: original image; i.e., according to copyright law it is a derived work of
                   14504: the original image.
                   14505: 
                   14506: Since Gforth is distributed under the GNU GPL, the newly created image
                   14507: falls under the GNU GPL, too. In particular, this means that if you
                   14508: distribute the image, you have to make all of the sources for the image
1.113     anton    14509: available, including those you wrote.  For details see @ref{Copying, ,
1.18      anton    14510: GNU General Public License (Section 3)}.
                   14511: 
                   14512: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   14513: contains only code compiled from the sources you gave it; if none of
                   14514: these sources is under the GPL, the terms discussed above do not apply
                   14515: to the image. However, if your image needs an engine (a gforth binary)
                   14516: that is under the GPL, you should make sure that you distribute both in
                   14517: a way that is at most a @emph{mere aggregation}, if you don't want the
                   14518: terms of the GPL to apply to the image.
                   14519: 
                   14520: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    14521: @section Image File Background
                   14522: @cindex image file background
                   14523: 
1.80      anton    14524: Gforth consists not only of primitives (in the engine), but also of
1.1       anton    14525: definitions written in Forth. Since the Forth compiler itself belongs to
                   14526: those definitions, it is not possible to start the system with the
1.80      anton    14527: engine and the Forth source alone. Therefore we provide the Forth
1.26      crook    14528: code as an image file in nearly executable form. When Gforth starts up,
                   14529: a C routine loads the image file into memory, optionally relocates the
                   14530: addresses, then sets up the memory (stacks etc.) according to
                   14531: information in the image file, and (finally) starts executing Forth
                   14532: code.
1.1       anton    14533: 
                   14534: The image file variants represent different compromises between the
                   14535: goals of making it easy to generate image files and making them
                   14536: portable.
                   14537: 
                   14538: @cindex relocation at run-time
1.26      crook    14539: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1       anton    14540: run-time. This avoids many of the complications discussed below (image
                   14541: files are data relocatable without further ado), but costs performance
                   14542: (one addition per memory access).
                   14543: 
                   14544: @cindex relocation at load-time
1.26      crook    14545: By contrast, the Gforth loader performs relocation at image load time. The
                   14546: loader also has to replace tokens that represent primitive calls with the
1.1       anton    14547: appropriate code-field addresses (or code addresses in the case of
                   14548: direct threading).
                   14549: 
                   14550: There are three kinds of image files, with different degrees of
                   14551: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   14552: image files.
                   14553: 
                   14554: @cindex image file loader
                   14555: @cindex relocating loader
                   14556: @cindex loader for image files
                   14557: These image file variants have several restrictions in common; they are
                   14558: caused by the design of the image file loader:
                   14559: 
                   14560: @itemize @bullet
                   14561: @item
                   14562: There is only one segment; in particular, this means, that an image file
                   14563: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26      crook    14564: them). The contents of the stacks are not represented, either.
1.1       anton    14565: 
                   14566: @item
                   14567: The only kinds of relocation supported are: adding the same offset to
                   14568: all cells that represent data addresses; and replacing special tokens
                   14569: with code addresses or with pieces of machine code.
                   14570: 
                   14571: If any complex computations involving addresses are performed, the
                   14572: results cannot be represented in the image file. Several applications that
                   14573: use such computations come to mind:
                   14574: @itemize @minus
                   14575: @item
                   14576: Hashing addresses (or data structures which contain addresses) for table
                   14577: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   14578: purpose, you will have no problem, because the hash tables are
                   14579: recomputed automatically when the system is started. If you use your own
                   14580: hash tables, you will have to do something similar.
                   14581: 
                   14582: @item
                   14583: There's a cute implementation of doubly-linked lists that uses
                   14584: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   14585: in the image file, and restore the doubly-linked representation on
                   14586: startup.@footnote{In my opinion, though, you should think thrice before
                   14587: using a doubly-linked list (whatever implementation).}
                   14588: 
                   14589: @item
                   14590: The code addresses of run-time routines like @code{docol:} cannot be
                   14591: represented in the image file (because their tokens would be replaced by
                   14592: machine code in direct threaded implementations). As a workaround,
                   14593: compute these addresses at run-time with @code{>code-address} from the
                   14594: executions tokens of appropriate words (see the definitions of
1.80      anton    14595: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1       anton    14596: 
                   14597: @item
                   14598: On many architectures addresses are represented in machine code in some
                   14599: shifted or mangled form. You cannot put @code{CODE} words that contain
                   14600: absolute addresses in this form in a relocatable image file. Workarounds
                   14601: are representing the address in some relative form (e.g., relative to
                   14602: the CFA, which is present in some register), or loading the address from
                   14603: a place where it is stored in a non-mangled form.
                   14604: @end itemize
                   14605: @end itemize
                   14606: 
                   14607: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   14608: @section Non-Relocatable Image Files
                   14609: @cindex non-relocatable image files
1.26      crook    14610: @cindex image file, non-relocatable
1.1       anton    14611: 
                   14612: These files are simple memory dumps of the dictionary. They are specific
                   14613: to the executable (i.e., @file{gforth} file) they were created
                   14614: with. What's worse, they are specific to the place on which the
                   14615: dictionary resided when the image was created. Now, there is no
                   14616: guarantee that the dictionary will reside at the same place the next
                   14617: time you start Gforth, so there's no guarantee that a non-relocatable
                   14618: image will work the next time (Gforth will complain instead of crashing,
                   14619: though).
                   14620: 
                   14621: You can create a non-relocatable image file with
                   14622: 
1.44      crook    14623: 
1.1       anton    14624: doc-savesystem
                   14625: 
1.44      crook    14626: 
1.1       anton    14627: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   14628: @section Data-Relocatable Image Files
                   14629: @cindex data-relocatable image files
1.26      crook    14630: @cindex image file, data-relocatable
1.1       anton    14631: 
                   14632: These files contain relocatable data addresses, but fixed code addresses
                   14633: (instead of tokens). They are specific to the executable (i.e.,
                   14634: @file{gforth} file) they were created with. For direct threading on some
                   14635: architectures (e.g., the i386), data-relocatable images do not work. You
                   14636: get a data-relocatable image, if you use @file{gforthmi} with a
                   14637: Gforth binary that is not doubly indirect threaded (@pxref{Fully
                   14638: Relocatable Image Files}).
                   14639: 
                   14640: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   14641: @section Fully Relocatable Image Files
                   14642: @cindex fully relocatable image files
1.26      crook    14643: @cindex image file, fully relocatable
1.1       anton    14644: 
                   14645: @cindex @file{kern*.fi}, relocatability
                   14646: @cindex @file{gforth.fi}, relocatability
                   14647: These image files have relocatable data addresses, and tokens for code
                   14648: addresses. They can be used with different binaries (e.g., with and
                   14649: without debugging) on the same machine, and even across machines with
                   14650: the same data formats (byte order, cell size, floating point
                   14651: format). However, they are usually specific to the version of Gforth
                   14652: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
                   14653: are fully relocatable.
                   14654: 
                   14655: There are two ways to create a fully relocatable image file:
                   14656: 
                   14657: @menu
1.29      crook    14658: * gforthmi::                    The normal way
1.1       anton    14659: * cross.fs::                    The hard way
                   14660: @end menu
                   14661: 
                   14662: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   14663: @subsection @file{gforthmi}
                   14664: @cindex @file{comp-i.fs}
                   14665: @cindex @file{gforthmi}
                   14666: 
                   14667: You will usually use @file{gforthmi}. If you want to create an
1.29      crook    14668: image @i{file} that contains everything you would load by invoking
                   14669: Gforth with @code{gforth @i{options}}, you simply say:
1.1       anton    14670: @example
1.29      crook    14671: gforthmi @i{file} @i{options}
1.1       anton    14672: @end example
                   14673: 
                   14674: E.g., if you want to create an image @file{asm.fi} that has the file
                   14675: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   14676: like this:
                   14677: 
                   14678: @example
                   14679: gforthmi asm.fi asm.fs
                   14680: @end example
                   14681: 
1.27      crook    14682: @file{gforthmi} is implemented as a sh script and works like this: It
                   14683: produces two non-relocatable images for different addresses and then
                   14684: compares them. Its output reflects this: first you see the output (if
1.62      crook    14685: any) of the two Gforth invocations that produce the non-relocatable image
1.27      crook    14686: files, then you see the output of the comparing program: It displays the
                   14687: offset used for data addresses and the offset used for code addresses;
1.1       anton    14688: moreover, for each cell that cannot be represented correctly in the
1.44      crook    14689: image files, it displays a line like this:
1.1       anton    14690: 
                   14691: @example
                   14692:      78DC         BFFFFA50         BFFFFA40
                   14693: @end example
                   14694: 
                   14695: This means that at offset $78dc from @code{forthstart}, one input image
                   14696: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   14697: cannot be represented correctly in the output image, you should examine
                   14698: these places in the dictionary and verify that these cells are dead
                   14699: (i.e., not read before they are written).
1.39      anton    14700: 
                   14701: @cindex --application, @code{gforthmi} option
                   14702: If you insert the option @code{--application} in front of the image file
                   14703: name, you will get an image that uses the @code{--appl-image} option
                   14704: instead of the @code{--image-file} option (@pxref{Invoking
                   14705: Gforth}). When you execute such an image on Unix (by typing the image
                   14706: name as command), the Gforth engine will pass all options to the image
                   14707: instead of trying to interpret them as engine options.
1.1       anton    14708: 
1.27      crook    14709: If you type @file{gforthmi} with no arguments, it prints some usage
                   14710: instructions.
                   14711: 
1.1       anton    14712: @cindex @code{savesystem} during @file{gforthmi}
                   14713: @cindex @code{bye} during @file{gforthmi}
                   14714: @cindex doubly indirect threaded code
1.44      crook    14715: @cindex environment variables
                   14716: @cindex @code{GFORTHD} -- environment variable
                   14717: @cindex @code{GFORTH} -- environment variable
1.1       anton    14718: @cindex @code{gforth-ditc}
1.29      crook    14719: There are a few wrinkles: After processing the passed @i{options}, the
1.1       anton    14720: words @code{savesystem} and @code{bye} must be visible. A special doubly
                   14721: indirect threaded version of the @file{gforth} executable is used for
1.62      crook    14722: creating the non-relocatable images; you can pass the exact filename of
1.1       anton    14723: this executable through the environment variable @code{GFORTHD}
                   14724: (default: @file{gforth-ditc}); if you pass a version that is not doubly
                   14725: indirect threaded, you will not get a fully relocatable image, but a
1.27      crook    14726: data-relocatable image (because there is no code address offset). The
                   14727: normal @file{gforth} executable is used for creating the relocatable
                   14728: image; you can pass the exact filename of this executable through the
                   14729: environment variable @code{GFORTH}.
1.1       anton    14730: 
                   14731: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   14732: @subsection @file{cross.fs}
                   14733: @cindex @file{cross.fs}
                   14734: @cindex cross-compiler
                   14735: @cindex metacompiler
1.47      crook    14736: @cindex target compiler
1.1       anton    14737: 
                   14738: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47      crook    14739: programming language (@pxref{Cross Compiler}).
1.1       anton    14740: 
1.47      crook    14741: @code{cross} allows you to create image files for machines with
1.1       anton    14742: different data sizes and data formats than the one used for generating
                   14743: the image file. You can also use it to create an application image that
                   14744: does not contain a Forth compiler. These features are bought with
                   14745: restrictions and inconveniences in programming. E.g., addresses have to
                   14746: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   14747: order to make the code relocatable.
                   14748: 
                   14749: 
                   14750: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   14751: @section Stack and Dictionary Sizes
                   14752: @cindex image file, stack and dictionary sizes
                   14753: @cindex dictionary size default
                   14754: @cindex stack size default
                   14755: 
                   14756: If you invoke Gforth with a command line flag for the size
                   14757: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   14758: dictionary. If you save the dictionary with @code{savesystem} or create
                   14759: an image with @file{gforthmi}, this size will become the default
                   14760: for the resulting image file. E.g., the following will create a
1.21      crook    14761: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1       anton    14762: 
                   14763: @example
                   14764: gforthmi gforth.fi -m 1M
                   14765: @end example
                   14766: 
                   14767: In other words, if you want to set the default size for the dictionary
                   14768: and the stacks of an image, just invoke @file{gforthmi} with the
                   14769: appropriate options when creating the image.
                   14770: 
                   14771: @cindex stack size, cache-friendly
                   14772: Note: For cache-friendly behaviour (i.e., good performance), you should
                   14773: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   14774: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   14775: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   14776: 
                   14777: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   14778: @section Running Image Files
                   14779: @cindex running image files
                   14780: @cindex invoking image files
                   14781: @cindex image file invocation
                   14782: 
                   14783: @cindex -i, invoke image file
                   14784: @cindex --image file, invoke image file
1.29      crook    14785: You can invoke Gforth with an image file @i{image} instead of the
1.1       anton    14786: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   14787: @example
1.29      crook    14788: gforth -i @i{image}
1.1       anton    14789: @end example
                   14790: 
                   14791: @cindex executable image file
1.26      crook    14792: @cindex image file, executable
1.1       anton    14793: If your operating system supports starting scripts with a line of the
                   14794: form @code{#! ...}, you just have to type the image file name to start
                   14795: Gforth with this image file (note that the file extension @code{.fi} is
1.29      crook    14796: just a convention). I.e., to run Gforth with the image file @i{image},
                   14797: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27      crook    14798: This works because every @code{.fi} file starts with a line of this
                   14799: format:
                   14800: 
                   14801: @example
                   14802: #! /usr/local/bin/gforth-0.4.0 -i
                   14803: @end example
                   14804: 
                   14805: The file and pathname for the Gforth engine specified on this line is
                   14806: the specific Gforth executable that it was built against; i.e. the value
                   14807: of the environment variable @code{GFORTH} at the time that
                   14808: @file{gforthmi} was executed.
1.1       anton    14809: 
1.27      crook    14810: You can make use of the same shell capability to make a Forth source
                   14811: file into an executable. For example, if you place this text in a file:
1.26      crook    14812: 
                   14813: @example
                   14814: #! /usr/local/bin/gforth
                   14815: 
                   14816: ." Hello, world" CR
                   14817: bye
                   14818: @end example
                   14819: 
                   14820: @noindent
1.27      crook    14821: and then make the file executable (chmod +x in Unix), you can run it
1.26      crook    14822: directly from the command line. The sequence @code{#!} is used in two
                   14823: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29      crook    14824: system@footnote{The Unix kernel actually recognises two types of files:
                   14825: executable files and files of data, where the data is processed by an
                   14826: interpreter that is specified on the ``interpreter line'' -- the first
                   14827: line of the file, starting with the sequence #!. There may be a small
                   14828: limit (e.g., 32) on the number of characters that may be specified on
                   14829: the interpreter line.} secondly it is treated as a comment character by
                   14830: Gforth. Because of the second usage, a space is required between
1.80      anton    14831: @code{#!} and the path to the executable (moreover, some Unixes
                   14832: require the sequence @code{#! /}).
1.27      crook    14833: 
                   14834: The disadvantage of this latter technique, compared with using
1.80      anton    14835: @file{gforthmi}, is that it is slightly slower; the Forth source code is
                   14836: compiled on-the-fly, each time the program is invoked.
1.26      crook    14837: 
1.1       anton    14838: doc-#!
                   14839: 
1.44      crook    14840: 
1.1       anton    14841: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   14842: @section Modifying the Startup Sequence
                   14843: @cindex startup sequence for image file
                   14844: @cindex image file initialization sequence
                   14845: @cindex initialization sequence of image file
                   14846: 
1.120     anton    14847: You can add your own initialization to the startup sequence of an image
                   14848: through the deferred word @code{'cold}. @code{'cold} is invoked just
                   14849: before the image-specific command line processing (i.e., loading files
                   14850: and evaluating (@code{-e}) strings) starts.
1.1       anton    14851: 
                   14852: A sequence for adding your initialization usually looks like this:
                   14853: 
                   14854: @example
                   14855: :noname
                   14856:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   14857:     ... \ your stuff
                   14858: ; IS 'cold
                   14859: @end example
                   14860: 
1.157     anton    14861: After @code{'cold}, Gforth processes the image options
                   14862: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
                   14863: another deferred word.  This normally prints Gforth's startup message
                   14864: and does nothing else.
                   14865: 
1.1       anton    14866: @cindex turnkey image files
1.26      crook    14867: @cindex image file, turnkey applications
1.157     anton    14868: So, if you want to make a turnkey image (i.e., an image for an
                   14869: application instead of an extended Forth system), you can do this in
                   14870: two ways:
                   14871: 
                   14872: @itemize @bullet
                   14873: 
                   14874: @item
                   14875: If you want to do your interpretation of the OS command-line
                   14876: arguments, hook into @code{'cold}.  In that case you probably also
                   14877: want to build the image with @code{gforthmi --application}
                   14878: (@pxref{gforthmi}) to keep the engine from processing OS command line
                   14879: options.  You can then do your own command-line processing with
                   14880: @code{next-arg} 
                   14881: 
                   14882: @item
                   14883: If you want to have the normal Gforth processing of OS command-line
                   14884: arguments, hook into @code{bootmessage}.
                   14885: 
                   14886: @end itemize
                   14887: 
                   14888: In either case, you probably do not want the word that you execute in
                   14889: these hooks to exit normally, but use @code{bye} or @code{throw}.
                   14890: Otherwise the Gforth startup process would continue and eventually
                   14891: present the Forth command line to the user.
1.26      crook    14892: 
                   14893: doc-'cold
1.157     anton    14894: doc-bootmessage
1.44      crook    14895: 
1.1       anton    14896: @c ******************************************************************
1.113     anton    14897: @node Engine, Cross Compiler, Image Files, Top
1.1       anton    14898: @chapter Engine
                   14899: @cindex engine
                   14900: @cindex virtual machine
                   14901: 
1.26      crook    14902: Reading this chapter is not necessary for programming with Gforth. It
1.1       anton    14903: may be helpful for finding your way in the Gforth sources.
                   14904: 
1.109     anton    14905: The ideas in this section have also been published in the following
                   14906: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
                   14907: Forth-Tagung '93; M. Anton Ertl,
                   14908: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
                   14909: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
                   14910: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
                   14911: Threaded code variations and optimizations (extended version)}},
                   14912: Forth-Tagung '02.
1.1       anton    14913: 
                   14914: @menu
                   14915: * Portability::                 
                   14916: * Threading::                   
                   14917: * Primitives::                  
                   14918: * Performance::                 
                   14919: @end menu
                   14920: 
                   14921: @node Portability, Threading, Engine, Engine
                   14922: @section Portability
                   14923: @cindex engine portability
                   14924: 
1.26      crook    14925: An important goal of the Gforth Project is availability across a wide
                   14926: range of personal machines. fig-Forth, and, to a lesser extent, F83,
                   14927: achieved this goal by manually coding the engine in assembly language
                   14928: for several then-popular processors. This approach is very
                   14929: labor-intensive and the results are short-lived due to progress in
                   14930: computer architecture.
1.1       anton    14931: 
                   14932: @cindex C, using C for the engine
                   14933: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   14934: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   14935: particularly popular for UNIX-based Forths due to the large variety of
                   14936: architectures of UNIX machines. Unfortunately an implementation in C
                   14937: does not mix well with the goals of efficiency and with using
                   14938: traditional techniques: Indirect or direct threading cannot be expressed
                   14939: in C, and switch threading, the fastest technique available in C, is
                   14940: significantly slower. Another problem with C is that it is very
                   14941: cumbersome to express double integer arithmetic.
                   14942: 
                   14943: @cindex GNU C for the engine
                   14944: @cindex long long
                   14945: Fortunately, there is a portable language that does not have these
                   14946: limitations: GNU C, the version of C processed by the GNU C compiler
                   14947: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   14948: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   14949: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   14950: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   14951: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109     anton    14952: double numbers on many systems.  GNU C is freely available on all
1.1       anton    14953: important (and many unimportant) UNIX machines, VMS, 80386s running
                   14954: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   14955: on all these machines.
                   14956: 
                   14957: Writing in a portable language has the reputation of producing code that
                   14958: is slower than assembly. For our Forth engine we repeatedly looked at
                   14959: the code produced by the compiler and eliminated most compiler-induced
                   14960: inefficiencies by appropriate changes in the source code.
                   14961: 
                   14962: @cindex explicit register declarations
                   14963: @cindex --enable-force-reg, configuration flag
                   14964: @cindex -DFORCE_REG
                   14965: However, register allocation cannot be portably influenced by the
                   14966: programmer, leading to some inefficiencies on register-starved
                   14967: machines. We use explicit register declarations (@pxref{Explicit Reg
                   14968: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   14969: improve the speed on some machines. They are turned on by using the
                   14970: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   14971: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   14972: machine, but also on the compiler version: On some machines some
                   14973: compiler versions produce incorrect code when certain explicit register
                   14974: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   14975: 
                   14976: @node Threading, Primitives, Portability, Engine
                   14977: @section Threading
                   14978: @cindex inner interpreter implementation
                   14979: @cindex threaded code implementation
                   14980: 
                   14981: @cindex labels as values
                   14982: GNU C's labels as values extension (available since @code{gcc-2.0},
                   14983: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29      crook    14984: makes it possible to take the address of @i{label} by writing
                   14985: @code{&&@i{label}}.  This address can then be used in a statement like
                   14986: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1       anton    14987: @code{goto x}.
                   14988: 
1.26      crook    14989: @cindex @code{NEXT}, indirect threaded
1.1       anton    14990: @cindex indirect threaded inner interpreter
                   14991: @cindex inner interpreter, indirect threaded
1.26      crook    14992: With this feature an indirect threaded @code{NEXT} looks like:
1.1       anton    14993: @example
                   14994: cfa = *ip++;
                   14995: ca = *cfa;
                   14996: goto *ca;
                   14997: @end example
                   14998: @cindex instruction pointer
                   14999: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   15000: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   15001: execution token and points to the code field of the next word to be
                   15002: executed; The @code{ca} (code address) fetched from there points to some
                   15003: executable code, e.g., a primitive or the colon definition handler
                   15004: @code{docol}.
                   15005: 
1.26      crook    15006: @cindex @code{NEXT}, direct threaded
1.1       anton    15007: @cindex direct threaded inner interpreter
                   15008: @cindex inner interpreter, direct threaded
                   15009: Direct threading is even simpler:
                   15010: @example
                   15011: ca = *ip++;
                   15012: goto *ca;
                   15013: @end example
                   15014: 
                   15015: Of course we have packaged the whole thing neatly in macros called
1.26      crook    15016: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1       anton    15017: 
                   15018: @menu
                   15019: * Scheduling::                  
                   15020: * Direct or Indirect Threaded?::  
1.109     anton    15021: * Dynamic Superinstructions::   
1.1       anton    15022: * DOES>::                       
                   15023: @end menu
                   15024: 
                   15025: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   15026: @subsection Scheduling
                   15027: @cindex inner interpreter optimization
                   15028: 
                   15029: There is a little complication: Pipelined and superscalar processors,
                   15030: i.e., RISC and some modern CISC machines can process independent
                   15031: instructions while waiting for the results of an instruction. The
                   15032: compiler usually reorders (schedules) the instructions in a way that
                   15033: achieves good usage of these delay slots. However, on our first tries
                   15034: the compiler did not do well on scheduling primitives. E.g., for
                   15035: @code{+} implemented as
                   15036: @example
                   15037: n=sp[0]+sp[1];
                   15038: sp++;
                   15039: sp[0]=n;
                   15040: NEXT;
                   15041: @end example
1.81      anton    15042: the @code{NEXT} comes strictly after the other code, i.e., there is
                   15043: nearly no scheduling. After a little thought the problem becomes clear:
                   15044: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21      crook    15045: addresses (and the version of @code{gcc} we used would not know it even
                   15046: if it was possible), so it could not move the load of the cfa above the
                   15047: store to the TOS. Indeed the pointers could be the same, if code on or
                   15048: very near the top of stack were executed. In the interest of speed we
                   15049: chose to forbid this probably unused ``feature'' and helped the compiler
1.81      anton    15050: in scheduling: @code{NEXT} is divided into several parts:
                   15051: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
                   15052: like:
1.1       anton    15053: @example
1.81      anton    15054: NEXT_P0;
1.1       anton    15055: n=sp[0]+sp[1];
                   15056: sp++;
                   15057: NEXT_P1;
                   15058: sp[0]=n;
                   15059: NEXT_P2;
                   15060: @end example
                   15061: 
1.81      anton    15062: There are various schemes that distribute the different operations of
                   15063: NEXT between these parts in several ways; in general, different schemes
                   15064: perform best on different processors.  We use a scheme for most
                   15065: architectures that performs well for most processors of this
1.109     anton    15066: architecture; in the future we may switch to benchmarking and chosing
1.81      anton    15067: the scheme on installation time.
                   15068: 
1.1       anton    15069: 
1.109     anton    15070: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1       anton    15071: @subsection Direct or Indirect Threaded?
                   15072: @cindex threading, direct or indirect?
                   15073: 
1.109     anton    15074: Threaded forth code consists of references to primitives (simple machine
                   15075: code routines like @code{+}) and to non-primitives (e.g., colon
                   15076: definitions, variables, constants); for a specific class of
                   15077: non-primitives (e.g., variables) there is one code routine (e.g.,
                   15078: @code{dovar}), but each variable needs a separate reference to its data.
                   15079: 
                   15080: Traditionally Forth has been implemented as indirect threaded code,
                   15081: because this allows to use only one cell to reference a non-primitive
                   15082: (basically you point to the data, and find the code address there).
                   15083: 
                   15084: @cindex primitive-centric threaded code
                   15085: However, threaded code in Gforth (since 0.6.0) uses two cells for
                   15086: non-primitives, one for the code address, and one for the data address;
                   15087: the data pointer is an immediate argument for the virtual machine
                   15088: instruction represented by the code address.  We call this
                   15089: @emph{primitive-centric} threaded code, because all code addresses point
                   15090: to simple primitives.  E.g., for a variable, the code address is for
                   15091: @code{lit} (also used for integer literals like @code{99}).
                   15092: 
                   15093: Primitive-centric threaded code allows us to use (faster) direct
                   15094: threading as dispatch method, completely portably (direct threaded code
                   15095: in Gforth before 0.6.0 required architecture-specific code).  It also
                   15096: eliminates the performance problems related to I-cache consistency that
                   15097: 386 implementations have with direct threaded code, and allows
                   15098: additional optimizations.
                   15099: 
                   15100: @cindex hybrid direct/indirect threaded code
                   15101: There is a catch, however: the @var{xt} parameter of @code{execute} can
                   15102: occupy only one cell, so how do we pass non-primitives with their code
                   15103: @emph{and} data addresses to them?  Our answer is to use indirect
                   15104: threaded dispatch for @code{execute} and other words that use a
                   15105: single-cell xt.  So, normal threaded code in colon definitions uses
                   15106: direct threading, and @code{execute} and similar words, which dispatch
                   15107: to xts on the data stack, use indirect threaded code.  We call this
                   15108: @emph{hybrid direct/indirect} threaded code.
                   15109: 
                   15110: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
                   15111: @cindex gforth engine
                   15112: @cindex gforth-fast engine
                   15113: The engines @command{gforth} and @command{gforth-fast} use hybrid
                   15114: direct/indirect threaded code.  This means that with these engines you
                   15115: cannot use @code{,} to compile an xt.  Instead, you have to use
                   15116: @code{compile,}.
                   15117: 
                   15118: @cindex gforth-itc engine
1.115     anton    15119: If you want to compile xts with @code{,}, use @command{gforth-itc}.
                   15120: This engine uses plain old indirect threaded code.  It still compiles in
                   15121: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109     anton    15122: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115     anton    15123: ... [}).  If you want to do that, you have to use @command{gforth-itc}
1.109     anton    15124: and execute @code{' , is compile,}.  Your program can check if it is
                   15125: running on a hybrid direct/indirect threaded engine or a pure indirect
                   15126: threaded engine with @code{threading-method} (@pxref{Threading Words}).
                   15127: 
                   15128: 
                   15129: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
                   15130: @subsection Dynamic Superinstructions
                   15131: @cindex Dynamic superinstructions with replication
                   15132: @cindex Superinstructions
                   15133: @cindex Replication
                   15134: 
                   15135: The engines @command{gforth} and @command{gforth-fast} use another
                   15136: optimization: Dynamic superinstructions with replication.  As an
                   15137: example, consider the following colon definition:
                   15138: 
                   15139: @example
                   15140: : squared ( n1 -- n2 )
                   15141:   dup * ;
                   15142: @end example
                   15143: 
                   15144: Gforth compiles this into the threaded code sequence
                   15145: 
                   15146: @example
                   15147: dup
                   15148: *
                   15149: ;s
                   15150: @end example
                   15151: 
                   15152: In normal direct threaded code there is a code address occupying one
                   15153: cell for each of these primitives.  Each code address points to a
                   15154: machine code routine, and the interpreter jumps to this machine code in
                   15155: order to execute the primitive.  The routines for these three
                   15156: primitives are (in @command{gforth-fast} on the 386):
                   15157: 
                   15158: @example
                   15159: Code dup  
                   15160: ( $804B950 )  add     esi , # -4  \ $83 $C6 $FC 
                   15161: ( $804B953 )  add     ebx , # 4  \ $83 $C3 $4 
                   15162: ( $804B956 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
                   15163: ( $804B959 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   15164: end-code
                   15165: Code *  
                   15166: ( $804ACC4 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
                   15167: ( $804ACC7 )  add     esi , # 4  \ $83 $C6 $4 
                   15168: ( $804ACCA )  add     ebx , # 4  \ $83 $C3 $4 
                   15169: ( $804ACCD )  imul    ecx , eax  \ $F $AF $C8 
                   15170: ( $804ACD0 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   15171: end-code
                   15172: Code ;s  
                   15173: ( $804A693 )  mov     eax , dword ptr [edi]  \ $8B $7 
                   15174: ( $804A695 )  add     edi , # 4  \ $83 $C7 $4 
                   15175: ( $804A698 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
                   15176: ( $804A69B )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   15177: end-code
                   15178: @end example
                   15179: 
                   15180: With dynamic superinstructions and replication the compiler does not
                   15181: just lay down the threaded code, but also copies the machine code
                   15182: fragments, usually without the jump at the end.
                   15183: 
                   15184: @example
                   15185: ( $4057D27D )  add     esi , # -4  \ $83 $C6 $FC 
                   15186: ( $4057D280 )  add     ebx , # 4  \ $83 $C3 $4 
                   15187: ( $4057D283 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
                   15188: ( $4057D286 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
                   15189: ( $4057D289 )  add     esi , # 4  \ $83 $C6 $4 
                   15190: ( $4057D28C )  add     ebx , # 4  \ $83 $C3 $4 
                   15191: ( $4057D28F )  imul    ecx , eax  \ $F $AF $C8 
                   15192: ( $4057D292 )  mov     eax , dword ptr [edi]  \ $8B $7 
                   15193: ( $4057D294 )  add     edi , # 4  \ $83 $C7 $4 
                   15194: ( $4057D297 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
                   15195: ( $4057D29A )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   15196: @end example
                   15197: 
                   15198: Only when a threaded-code control-flow change happens (e.g., in
                   15199: @code{;s}), the jump is appended.  This optimization eliminates many of
                   15200: these jumps and makes the rest much more predictable.  The speedup
                   15201: depends on the processor and the application; on the Athlon and Pentium
                   15202: III this optimization typically produces a speedup by a factor of 2.
                   15203: 
                   15204: The code addresses in the direct-threaded code are set to point to the
                   15205: appropriate points in the copied machine code, in this example like
                   15206: this:
1.1       anton    15207: 
1.109     anton    15208: @example
                   15209: primitive  code address
                   15210:    dup       $4057D27D
                   15211:    *         $4057D286
                   15212:    ;s        $4057D292
                   15213: @end example
                   15214: 
                   15215: Thus there can be threaded-code jumps to any place in this piece of
                   15216: code.  This also simplifies decompilation quite a bit.
                   15217: 
                   15218: @cindex --no-dynamic command-line option
                   15219: @cindex --no-super command-line option
                   15220: You can disable this optimization with @option{--no-dynamic}.  You can
                   15221: use the copying without eliminating the jumps (i.e., dynamic
                   15222: replication, but without superinstructions) with @option{--no-super};
                   15223: this gives the branch prediction benefit alone; the effect on
1.110     anton    15224: performance depends on the CPU; on the Athlon and Pentium III the
                   15225: speedup is a little less than for dynamic superinstructions with
                   15226: replication.
                   15227: 
                   15228: @cindex patching threaded code
                   15229: One use of these options is if you want to patch the threaded code.
                   15230: With superinstructions, many of the dispatch jumps are eliminated, so
                   15231: patching often has no effect.  These options preserve all the dispatch
                   15232: jumps.
1.109     anton    15233: 
                   15234: @cindex --dynamic command-line option
1.110     anton    15235: On some machines dynamic superinstructions are disabled by default,
                   15236: because it is unsafe on these machines.  However, if you feel
                   15237: adventurous, you can enable it with @option{--dynamic}.
1.109     anton    15238: 
                   15239: @node DOES>,  , Dynamic Superinstructions, Threading
1.1       anton    15240: @subsection DOES>
                   15241: @cindex @code{DOES>} implementation
                   15242: 
1.26      crook    15243: @cindex @code{dodoes} routine
                   15244: @cindex @code{DOES>}-code
1.1       anton    15245: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   15246: the chunk of code executed by every word defined by a
1.109     anton    15247: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
                   15248: this is only needed if the xt of the word is @code{execute}d. The main
                   15249: problem here is: How to find the Forth code to be executed, i.e. the
                   15250: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
                   15251: solutions:
1.1       anton    15252: 
1.21      crook    15253: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109     anton    15254: @code{DOES>}-code address is stored in the cell after the code address
                   15255: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
                   15256: illegal in the Forth-79 and all later standards, because in fig-Forth
                   15257: this address lies in the body (which is illegal in these
                   15258: standards). However, by making the code field larger for all words this
                   15259: solution becomes legal again.  We use this approach.  Leaving a cell
                   15260: unused in most words is a bit wasteful, but on the machines we are
                   15261: targeting this is hardly a problem.
                   15262: 
1.1       anton    15263: 
                   15264: @node Primitives, Performance, Threading, Engine
                   15265: @section Primitives
                   15266: @cindex primitives, implementation
                   15267: @cindex virtual machine instructions, implementation
                   15268: 
                   15269: @menu
                   15270: * Automatic Generation::        
                   15271: * TOS Optimization::            
                   15272: * Produced code::               
                   15273: @end menu
                   15274: 
                   15275: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   15276: @subsection Automatic Generation
                   15277: @cindex primitives, automatic generation
                   15278: 
                   15279: @cindex @file{prims2x.fs}
1.109     anton    15280: 
1.1       anton    15281: Since the primitives are implemented in a portable language, there is no
                   15282: longer any need to minimize the number of primitives. On the contrary,
                   15283: having many primitives has an advantage: speed. In order to reduce the
                   15284: number of errors in primitives and to make programming them easier, we
1.109     anton    15285: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
                   15286: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
                   15287: generates most (and sometimes all) of the C code for a primitive from
                   15288: the stack effect notation.  The source for a primitive has the following
                   15289: form:
1.1       anton    15290: 
                   15291: @cindex primitive source format
                   15292: @format
1.58      anton    15293: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
1.29      crook    15294: [@code{""}@i{glossary entry}@code{""}]
                   15295: @i{C code}
1.1       anton    15296: [@code{:}
1.29      crook    15297: @i{Forth code}]
1.1       anton    15298: @end format
                   15299: 
                   15300: The items in brackets are optional. The category and glossary fields
                   15301: are there for generating the documentation, the Forth code is there
                   15302: for manual implementations on machines without GNU C. E.g., the source
                   15303: for the primitive @code{+} is:
                   15304: @example
1.58      anton    15305: +    ( n1 n2 -- n )   core    plus
1.1       anton    15306: n = n1+n2;
                   15307: @end example
                   15308: 
                   15309: This looks like a specification, but in fact @code{n = n1+n2} is C
                   15310: code. Our primitive generation tool extracts a lot of information from
                   15311: the stack effect notations@footnote{We use a one-stack notation, even
                   15312: though we have separate data and floating-point stacks; The separate
                   15313: notation can be generated easily from the unified notation.}: The number
                   15314: of items popped from and pushed on the stack, their type, and by what
                   15315: name they are referred to in the C code. It then generates a C code
                   15316: prelude and postlude for each primitive. The final C code for @code{+}
                   15317: looks like this:
                   15318: 
                   15319: @example
1.46      pazsan   15320: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
1.1       anton    15321: /*  */                          /* documentation */
1.81      anton    15322: NAME("+")                       /* debugging output (with -DDEBUG) */
1.1       anton    15323: @{
                   15324: DEF_CA                          /* definition of variable ca (indirect threading) */
                   15325: Cell n1;                        /* definitions of variables */
                   15326: Cell n2;
                   15327: Cell n;
1.81      anton    15328: NEXT_P0;                        /* NEXT part 0 */
1.1       anton    15329: n1 = (Cell) sp[1];              /* input */
                   15330: n2 = (Cell) TOS;
                   15331: sp += 1;                        /* stack adjustment */
                   15332: @{
                   15333: n = n1+n2;                      /* C code taken from the source */
                   15334: @}
                   15335: NEXT_P1;                        /* NEXT part 1 */
                   15336: TOS = (Cell)n;                  /* output */
                   15337: NEXT_P2;                        /* NEXT part 2 */
                   15338: @}
                   15339: @end example
                   15340: 
                   15341: This looks long and inefficient, but the GNU C compiler optimizes quite
                   15342: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   15343: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   15344: using them as intermediate storage also adds no cost.
                   15345: 
1.26      crook    15346: There are also other optimizations that are not illustrated by this
                   15347: example: assignments between simple variables are usually for free (copy
1.1       anton    15348: propagation). If one of the stack items is not used by the primitive
                   15349: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   15350: (dead code elimination). On the other hand, there are some things that
                   15351: the compiler does not do, therefore they are performed by
                   15352: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   15353: a stack item to the place where it just came from (e.g., @code{over}).
                   15354: 
                   15355: While programming a primitive is usually easy, there are a few cases
                   15356: where the programmer has to take the actions of the generator into
                   15357: account, most notably @code{?dup}, but also words that do not (always)
1.26      crook    15358: fall through to @code{NEXT}.
1.109     anton    15359: 
                   15360: For more information
1.1       anton    15361: 
                   15362: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   15363: @subsection TOS Optimization
                   15364: @cindex TOS optimization for primitives
                   15365: @cindex primitives, keeping the TOS in a register
                   15366: 
                   15367: An important optimization for stack machine emulators, e.g., Forth
                   15368: engines, is keeping  one or more of the top stack items in
1.29      crook    15369: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
                   15370: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1       anton    15371: @itemize @bullet
                   15372: @item
1.29      crook    15373: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1       anton    15374: due to fewer loads from and stores to the stack.
1.29      crook    15375: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
                   15376: @i{y<n}, due to additional moves between registers.
1.1       anton    15377: @end itemize
                   15378: 
                   15379: @cindex -DUSE_TOS
                   15380: @cindex -DUSE_NO_TOS
                   15381: In particular, keeping one item in a register is never a disadvantage,
                   15382: if there are enough registers. Keeping two items in registers is a
                   15383: disadvantage for frequent words like @code{?branch}, constants,
                   15384: variables, literals and @code{i}. Therefore our generator only produces
                   15385: code that keeps zero or one items in registers. The generated C code
                   15386: covers both cases; the selection between these alternatives is made at
                   15387: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   15388: code for @code{+} is just a simple variable name in the one-item case,
                   15389: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   15390: GNU C compiler tries to keep simple variables like @code{TOS} in
                   15391: registers, and it usually succeeds, if there are enough registers.
                   15392: 
                   15393: @cindex -DUSE_FTOS
                   15394: @cindex -DUSE_NO_FTOS
                   15395: The primitive generator performs the TOS optimization for the
                   15396: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   15397: operations the benefit of this optimization is even larger:
                   15398: floating-point operations take quite long on most processors, but can be
                   15399: performed in parallel with other operations as long as their results are
                   15400: not used. If the FP-TOS is kept in a register, this works. If
                   15401: it is kept on the stack, i.e., in memory, the store into memory has to
                   15402: wait for the result of the floating-point operation, lengthening the
                   15403: execution time of the primitive considerably.
                   15404: 
                   15405: The TOS optimization makes the automatic generation of primitives a
                   15406: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   15407: @code{TOS} is not sufficient. There are some special cases to
                   15408: consider:
                   15409: @itemize @bullet
                   15410: @item In the case of @code{dup ( w -- w w )} the generator must not
                   15411: eliminate the store to the original location of the item on the stack,
                   15412: if the TOS optimization is turned on.
                   15413: @item Primitives with stack effects of the form @code{--}
1.29      crook    15414: @i{out1}...@i{outy} must store the TOS to the stack at the start.
                   15415: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1       anton    15416: must load the TOS from the stack at the end. But for the null stack
                   15417: effect @code{--} no stores or loads should be generated.
                   15418: @end itemize
                   15419: 
                   15420: @node Produced code,  , TOS Optimization, Primitives
                   15421: @subsection Produced code
                   15422: @cindex primitives, assembly code listing
                   15423: 
                   15424: @cindex @file{engine.s}
                   15425: To see what assembly code is produced for the primitives on your machine
                   15426: with your compiler and your flag settings, type @code{make engine.s} and
1.81      anton    15427: look at the resulting file @file{engine.s}.  Alternatively, you can also
                   15428: disassemble the code of primitives with @code{see} on some architectures.
1.1       anton    15429: 
                   15430: @node  Performance,  , Primitives, Engine
                   15431: @section Performance
                   15432: @cindex performance of some Forth interpreters
                   15433: @cindex engine performance
                   15434: @cindex benchmarking Forth systems
                   15435: @cindex Gforth performance
                   15436: 
                   15437: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112     anton    15438: impossible to write a significantly faster threaded-code engine.
1.1       anton    15439: 
                   15440: On register-starved machines like the 386 architecture processors
                   15441: improvements are possible, because @code{gcc} does not utilize the
                   15442: registers as well as a human, even with explicit register declarations;
                   15443: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   15444: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   15445: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40      anton    15446: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
                   15447: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
                   15448: registers fit in real registers (and we can even afford to use the TOS
                   15449: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112     anton    15450: earlier results.  And dynamic superinstructions provide another speedup
                   15451: (but only around a factor 1.2 on the 486).
1.1       anton    15452: 
                   15453: @cindex Win32Forth performance
                   15454: @cindex NT Forth performance
                   15455: @cindex eforth performance
                   15456: @cindex ThisForth performance
                   15457: @cindex PFE performance
                   15458: @cindex TILE performance
1.81      anton    15459: The potential advantage of assembly language implementations is not
1.112     anton    15460: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81      anton    15461: (direct threaded, compiled with @code{gcc-2.95.1} and
                   15462: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
                   15463: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
                   15464: (with and without peephole (aka pinhole) optimization of the threaded
                   15465: code); all these systems were written in assembly language. We also
                   15466: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
                   15467: with @code{gcc-2.6.3} with the default configuration for Linux:
                   15468: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
                   15469: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
                   15470: employs peephole optimization of the threaded code) and TILE (compiled
                   15471: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
                   15472: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
                   15473: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
                   15474: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
                   15475: then extended it to run the benchmarks, added the peephole optimizer,
                   15476: ran the benchmarks and reported the results.
1.40      anton    15477: 
1.1       anton    15478: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   15479: matrix multiplication come from the Stanford integer benchmarks and have
                   15480: been translated into Forth by Martin Fraeman; we used the versions
                   15481: included in the TILE Forth package, but with bigger data set sizes; and
                   15482: a recursive Fibonacci number computation for benchmarking calling
                   15483: performance. The following table shows the time taken for the benchmarks
                   15484: scaled by the time taken by Gforth (in other words, it shows the speedup
                   15485: factor that Gforth achieved over the other systems).
                   15486: 
                   15487: @example
1.112     anton    15488: relative       Win32-    NT       eforth       This-      
                   15489: time     Gforth Forth Forth eforth  +opt   PFE Forth  TILE
                   15490: sieve      1.00  2.16  1.78   2.16  1.32  2.46  4.96 13.37
                   15491: bubble     1.00  1.93  2.07   2.18  1.29  2.21        5.70
                   15492: matmul     1.00  1.92  1.76   1.90  0.96  2.06        5.32
                   15493: fib        1.00  2.32  2.03   1.86  1.31  2.64  4.55  6.54
1.1       anton    15494: @end example
                   15495: 
1.26      crook    15496: You may be quite surprised by the good performance of Gforth when
                   15497: compared with systems written in assembly language. One important reason
                   15498: for the disappointing performance of these other systems is probably
                   15499: that they are not written optimally for the 486 (e.g., they use the
                   15500: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
                   15501: but costly method for relocating the Forth image: like @code{cforth}, it
                   15502: computes the actual addresses at run time, resulting in two address
                   15503: computations per @code{NEXT} (@pxref{Image File Background}).
                   15504: 
1.1       anton    15505: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   15506: explained with the self-imposed restriction of the latter systems to
                   15507: standard C, which makes efficient threading impossible (however, the
1.4       anton    15508: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    15509: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   15510: Moreover, current C compilers have a hard time optimizing other aspects
                   15511: of the ThisForth and the TILE source.
                   15512: 
1.26      crook    15513: The performance of Gforth on 386 architecture processors varies widely
                   15514: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
                   15515: allocate any of the virtual machine registers into real machine
                   15516: registers by itself and would not work correctly with explicit register
1.112     anton    15517: declarations, giving a significantly slower engine (on a 486DX2/66
                   15518: running the Sieve) than the one measured above.
1.1       anton    15519: 
1.26      crook    15520: Note that there have been several releases of Win32Forth since the
                   15521: release presented here, so the results presented above may have little
1.40      anton    15522: predictive value for the performance of Win32Forth today (results for
                   15523: the current release on an i486DX2/66 are welcome).
1.1       anton    15524: 
                   15525: @cindex @file{Benchres}
1.66      anton    15526: In
                   15527: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
                   15528: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1       anton    15529: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66      anton    15530: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
                   15531: several native code systems; that version of Gforth is slower on a 486
1.112     anton    15532: than the version used here. You can find a newer version of these
                   15533: measurements at
1.47      crook    15534: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1       anton    15535: find numbers for Gforth on various machines in @file{Benchres}.
                   15536: 
1.26      crook    15537: @c ******************************************************************
1.113     anton    15538: @c @node Binding to System Library, Cross Compiler, Engine, Top
                   15539: @c @chapter Binding to System Library
1.13      pazsan   15540: 
1.113     anton    15541: @c ****************************************************************
                   15542: @node Cross Compiler, Bugs, Engine, Top
1.14      pazsan   15543: @chapter Cross Compiler
1.47      crook    15544: @cindex @file{cross.fs}
                   15545: @cindex cross-compiler
                   15546: @cindex metacompiler
                   15547: @cindex target compiler
1.13      pazsan   15548: 
1.46      pazsan   15549: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
                   15550: mostly written in Forth, including crucial parts like the outer
                   15551: interpreter and compiler, it needs compiled Forth code to get
                   15552: started. The cross compiler allows to create new images for other
                   15553: architectures, even running under another Forth system.
1.13      pazsan   15554: 
                   15555: @menu
1.67      anton    15556: * Using the Cross Compiler::    
                   15557: * How the Cross Compiler Works::  
1.13      pazsan   15558: @end menu
                   15559: 
1.21      crook    15560: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14      pazsan   15561: @section Using the Cross Compiler
1.46      pazsan   15562: 
                   15563: The cross compiler uses a language that resembles Forth, but isn't. The
                   15564: main difference is that you can execute Forth code after definition,
                   15565: while you usually can't execute the code compiled by cross, because the
                   15566: code you are compiling is typically for a different computer than the
                   15567: one you are compiling on.
                   15568: 
1.81      anton    15569: @c anton: This chapter is somewhat different from waht I would expect: I
                   15570: @c would expect an explanation of the cross language and how to create an
                   15571: @c application image with it.  The section explains some aspects of
                   15572: @c creating a Gforth kernel.
                   15573: 
1.46      pazsan   15574: The Makefile is already set up to allow you to create kernels for new
                   15575: architectures with a simple make command. The generic kernels using the
                   15576: GCC compiled virtual machine are created in the normal build process
                   15577: with @code{make}. To create a embedded Gforth executable for e.g. the
                   15578: 8086 processor (running on a DOS machine), type
                   15579: 
                   15580: @example
                   15581: make kernl-8086.fi
                   15582: @end example
                   15583: 
                   15584: This will use the machine description from the @file{arch/8086}
                   15585: directory to create a new kernel. A machine file may look like that:
                   15586: 
                   15587: @example
                   15588: \ Parameter for target systems                         06oct92py
                   15589: 
                   15590:     4 Constant cell             \ cell size in bytes
                   15591:     2 Constant cell<<           \ cell shift to bytes
                   15592:     5 Constant cell>bit         \ cell shift to bits
                   15593:     8 Constant bits/char        \ bits per character
                   15594:     8 Constant bits/byte        \ bits per byte [default: 8]
                   15595:     8 Constant float            \ bytes per float
                   15596:     8 Constant /maxalign        \ maximum alignment in bytes
                   15597: false Constant bigendian        \ byte order
                   15598: ( true=big, false=little )
                   15599: 
                   15600: include machpc.fs               \ feature list
                   15601: @end example
                   15602: 
                   15603: This part is obligatory for the cross compiler itself, the feature list
                   15604: is used by the kernel to conditionally compile some features in and out,
                   15605: depending on whether the target supports these features.
                   15606: 
                   15607: There are some optional features, if you define your own primitives,
                   15608: have an assembler, or need special, nonstandard preparation to make the
1.81      anton    15609: boot process work. @code{asm-include} includes an assembler,
1.46      pazsan   15610: @code{prims-include} includes primitives, and @code{>boot} prepares for
                   15611: booting.
                   15612: 
                   15613: @example
                   15614: : asm-include    ." Include assembler" cr
                   15615:   s" arch/8086/asm.fs" included ;
                   15616: 
                   15617: : prims-include  ." Include primitives" cr
                   15618:   s" arch/8086/prim.fs" included ;
                   15619: 
                   15620: : >boot          ." Prepare booting" cr
                   15621:   s" ' boot >body into-forth 1+ !" evaluate ;
                   15622: @end example
                   15623: 
                   15624: These words are used as sort of macro during the cross compilation in
1.81      anton    15625: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46      pazsan   15626: be possible --- but more complicated --- to write a new kernel project
                   15627: file, too.
                   15628: 
                   15629: @file{kernel/main.fs} expects the machine description file name on the
                   15630: stack; the cross compiler itself (@file{cross.fs}) assumes that either
                   15631: @code{mach-file} leaves a counted string on the stack, or
                   15632: @code{machine-file} leaves an address, count pair of the filename on the
                   15633: stack.
                   15634: 
                   15635: The feature list is typically controlled using @code{SetValue}, generic
                   15636: files that are used by several projects can use @code{DefaultValue}
                   15637: instead. Both functions work like @code{Value}, when the value isn't
                   15638: defined, but @code{SetValue} works like @code{to} if the value is
                   15639: defined, and @code{DefaultValue} doesn't set anything, if the value is
                   15640: defined.
                   15641: 
                   15642: @example
                   15643: \ generic mach file for pc gforth                       03sep97jaw
                   15644: 
                   15645: true DefaultValue NIL  \ relocating
                   15646: 
                   15647: >ENVIRON
                   15648: 
                   15649: true DefaultValue file          \ controls the presence of the
                   15650:                                 \ file access wordset
                   15651: true DefaultValue OS            \ flag to indicate a operating system
                   15652: 
                   15653: true DefaultValue prims         \ true: primitives are c-code
                   15654: 
                   15655: true DefaultValue floating      \ floating point wordset is present
                   15656: 
                   15657: true DefaultValue glocals       \ gforth locals are present
                   15658:                                 \ will be loaded
                   15659: true DefaultValue dcomps        \ double number comparisons
                   15660: 
                   15661: true DefaultValue hash          \ hashing primitives are loaded/present
                   15662: 
                   15663: true DefaultValue xconds        \ used together with glocals,
                   15664:                                 \ special conditionals supporting gforths'
                   15665:                                 \ local variables
                   15666: true DefaultValue header        \ save a header information
                   15667: 
                   15668: true DefaultValue backtrace     \ enables backtrace code
                   15669: 
                   15670: false DefaultValue ec
                   15671: false DefaultValue crlf
                   15672: 
                   15673: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
                   15674: 
                   15675: &16 KB          DefaultValue stack-size
                   15676: &15 KB &512 +   DefaultValue fstack-size
                   15677: &15 KB          DefaultValue rstack-size
                   15678: &14 KB &512 +   DefaultValue lstack-size
                   15679: @end example
1.13      pazsan   15680: 
1.48      anton    15681: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
1.14      pazsan   15682: @section How the Cross Compiler Works
1.13      pazsan   15683: 
                   15684: @node Bugs, Origin, Cross Compiler, Top
1.21      crook    15685: @appendix Bugs
1.1       anton    15686: @cindex bug reporting
                   15687: 
1.21      crook    15688: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1       anton    15689: 
1.103     anton    15690: If you find a bug, please submit a bug report through
                   15691: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21      crook    15692: 
                   15693: @itemize @bullet
                   15694: @item
1.81      anton    15695: A program (or a sequence of keyboard commands) that reproduces the bug.
                   15696: @item
                   15697: A description of what you think constitutes the buggy behaviour.
                   15698: @item
1.21      crook    15699: The Gforth version used (it is announced at the start of an
                   15700: interactive Gforth session).
                   15701: @item
                   15702: The machine and operating system (on Unix
                   15703: systems @code{uname -a} will report this information).
                   15704: @item
1.81      anton    15705: The installation options (you can find the configure options at the
                   15706: start of @file{config.status}) and configuration (@code{configure}
                   15707: output or @file{config.cache}).
1.21      crook    15708: @item
                   15709: A complete list of changes (if any) you (or your installer) have made to the
                   15710: Gforth sources.
                   15711: @end itemize
1.1       anton    15712: 
                   15713: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   15714: to Report Bugs, gcc.info, GNU C Manual}.
                   15715: 
                   15716: 
1.21      crook    15717: @node Origin, Forth-related information, Bugs, Top
                   15718: @appendix Authors and Ancestors of Gforth
1.1       anton    15719: 
                   15720: @section Authors and Contributors
                   15721: @cindex authors of Gforth
                   15722: @cindex contributors to Gforth
                   15723: 
                   15724: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81      anton    15725: Ertl. The third major author was Jens Wilke.  Neal Crook contributed a
                   15726: lot to the manual.  Assemblers and disassemblers were contributed by
1.161     anton    15727: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
                   15728: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
                   15729: and Stuart Ramsden inspired us with their continuous feedback. Lennart
                   15730: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
                   15731: working on automatic support for calling C libraries. Helpful comments
                   15732: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
                   15733: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
                   15734: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
                   15735: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
                   15736: comments from many others; thank you all, sorry for not listing you
                   15737: here (but digging through my mailbox to extract your names is on my
                   15738: to-do list).
1.1       anton    15739: 
                   15740: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   15741: and autoconf, among others), and to the creators of the Internet: Gforth
1.21      crook    15742: was developed across the Internet, and its authors did not meet
1.20      pazsan   15743: physically for the first 4 years of development.
1.1       anton    15744: 
                   15745: @section Pedigree
1.26      crook    15746: @cindex pedigree of Gforth
1.1       anton    15747: 
1.81      anton    15748: Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
                   15749: significant part of the design of Gforth was prescribed by ANS Forth.
1.1       anton    15750: 
1.20      pazsan   15751: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1       anton    15752: 32 bit native code version of VolksForth for the Atari ST, written
                   15753: mostly by Dietrich Weineck.
                   15754: 
1.81      anton    15755: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
                   15756: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147     anton    15757: the mid-80s and ported to the Atari ST in 1986.  It descends from fig-Forth.
1.1       anton    15758: 
1.147     anton    15759: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   15760: @c Forth-83 standard. !! Pedigree? When?
1.1       anton    15761: 
                   15762: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   15763: 1979. Robert Selzer and Bill Ragsdale developed the original
                   15764: implementation of fig-Forth for the 6502 based on microForth.
                   15765: 
                   15766: The principal architect of microForth was Dean Sanderson. microForth was
                   15767: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   15768: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   15769: Z80.
                   15770: 
                   15771: All earlier Forth systems were custom-made, usually by Charles Moore,
                   15772: who discovered (as he puts it) Forth during the late 60s. The first full
                   15773: Forth existed in 1971.
                   15774: 
1.81      anton    15775: A part of the information in this section comes from
                   15776: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
                   15777: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147     anton    15778: Charles H. Moore, presented at the HOPL-II conference and preprinted
                   15779: in SIGPLAN Notices 28(3), 1993.  You can find more historical and
                   15780: genealogical information about Forth there.  For a more general (and
                   15781: graphical) Forth family tree look see
                   15782: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
                   15783: Forth Family Tree and Timeline}.
1.1       anton    15784: 
1.81      anton    15785: @c ------------------------------------------------------------------
1.113     anton    15786: @node Forth-related information, Licenses, Origin, Top
1.21      crook    15787: @appendix Other Forth-related information
                   15788: @cindex Forth-related information
                   15789: 
1.81      anton    15790: @c anton: I threw most of this stuff out, because it can be found through
                   15791: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21      crook    15792: 
                   15793: @cindex comp.lang.forth
                   15794: @cindex frequently asked questions
1.81      anton    15795: There is an active news group (comp.lang.forth) discussing Forth
                   15796: (including Gforth) and Forth-related issues. Its
                   15797: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
                   15798: (frequently asked questions and their answers) contains a lot of
                   15799: information on Forth.  You should read it before posting to
                   15800: comp.lang.forth.
1.21      crook    15801: 
1.81      anton    15802: The ANS Forth standard is most usable in its
                   15803: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21      crook    15804: 
1.113     anton    15805: @c ---------------------------------------------------
                   15806: @node  Licenses, Word Index, Forth-related information, Top
                   15807: @appendix Licenses
                   15808: 
                   15809: @menu
                   15810: * GNU Free Documentation License::  License for copying this manual.
                   15811: * Copying::                         GPL (for copying this software).
                   15812: @end menu
                   15813: 
                   15814: @include fdl.texi
                   15815: 
                   15816: @include gpl.texi
                   15817: 
                   15818: 
                   15819: 
1.81      anton    15820: @c ------------------------------------------------------------------
1.113     anton    15821: @node Word Index, Concept Index, Licenses, Top
1.1       anton    15822: @unnumbered Word Index
                   15823: 
1.26      crook    15824: This index is a list of Forth words that have ``glossary'' entries
                   15825: within this manual. Each word is listed with its stack effect and
                   15826: wordset.
1.1       anton    15827: 
                   15828: @printindex fn
                   15829: 
1.81      anton    15830: @c anton: the name index seems superfluous given the word and concept indices.
                   15831: 
                   15832: @c @node Name Index, Concept Index, Word Index, Top
                   15833: @c @unnumbered Name Index
1.41      anton    15834: 
1.81      anton    15835: @c This index is a list of Forth words that have ``glossary'' entries
                   15836: @c within this manual.
1.41      anton    15837: 
1.81      anton    15838: @c @printindex ky
1.41      anton    15839: 
1.113     anton    15840: @c -------------------------------------------------------
1.81      anton    15841: @node Concept Index,  , Word Index, Top
1.1       anton    15842: @unnumbered Concept and Word Index
                   15843: 
1.26      crook    15844: Not all entries listed in this index are present verbatim in the
                   15845: text. This index also duplicates, in abbreviated form, all of the words
                   15846: listed in the Word Index (only the names are listed for the words here).
1.1       anton    15847: 
                   15848: @printindex cp
                   15849: 
                   15850: @bye
1.81      anton    15851: 
                   15852: 
1.1       anton    15853: 

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