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

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
                     59: This manual is for Gforth
                     60: (version @value{VERSION}, @value{UPDATED}),
                     61: a fast and portable implementation of the ANS Forth language
1.29      crook      62: 
1.113     anton      63: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003 Free Software Foundation, Inc.
1.29      crook      64: 
1.113     anton      65: @quotation
                     66: Permission is granted to copy, distribute and/or modify this document
                     67: under the terms of the GNU Free Documentation License, Version 1.1 or
                     68: any later version published by the Free Software Foundation; with no
                     69: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
                     70: and with the Back-Cover Texts as in (a) below.  A copy of the
                     71: license is included in the section entitled ``GNU Free Documentation
                     72: License.''
                     73: 
                     74: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
                     75: this GNU Manual, like GNU software.  Copies published by the Free
                     76: Software Foundation raise funds for GNU development.''
                     77: @end quotation
                     78: @end copying
1.10      anton      79: 
1.113     anton      80: @dircategory Software development
                     81: @direntry
                     82: * Gforth: (gforth).             A fast interpreter for the Forth language.
                     83: @end direntry
                     84: @c The Texinfo manual also recommends doing this, but for Gforth it may
                     85: @c  not make much sense
                     86: @c @dircategory Individual utilities
                     87: @c @direntry
                     88: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
                     89: @c @end direntry
1.1       anton      90: 
                     91: @titlepage
1.113     anton      92: @title Gforth
                     93: @subtitle for version @value{VERSION}, @value{UPDATED}
                     94: @author Neal Crook
                     95: @author Anton Ertl
1.114     anton      96: @author David Kuehling
1.113     anton      97: @author Bernd Paysan
                     98: @author Jens Wilke
1.1       anton      99: @page
                    100: @vskip 0pt plus 1filll
1.113     anton     101: @insertcopying
                    102: @end titlepage
1.1       anton     103: 
1.113     anton     104: @contents
1.1       anton     105: 
1.113     anton     106: @ifnottex
                    107: @node Top, Goals, (dir), (dir)
                    108: @top Gforth
1.1       anton     109: 
1.113     anton     110: @insertcopying
1.49      anton     111: @end ifnottex
1.1       anton     112: 
                    113: @menu
1.26      crook     114: * Goals::                       About the Gforth Project
1.29      crook     115: * Gforth Environment::          Starting (and exiting) Gforth
1.48      anton     116: * Tutorial::                    Hands-on Forth Tutorial
1.21      crook     117: * Introduction::                An introduction to ANS Forth
1.1       anton     118: * Words::                       Forth words available in Gforth
1.24      anton     119: * Error messages::              How to interpret them
1.1       anton     120: * Tools::                       Programming tools
                    121: * ANS conformance::             Implementation-defined options etc.
1.65      anton     122: * Standard vs Extensions::      Should I use extensions?
1.1       anton     123: * Model::                       The abstract machine of Gforth
                    124: * Integrating Gforth::          Forth as scripting language for applications
                    125: * Emacs and Gforth::            The Gforth Mode
                    126: * Image Files::                 @code{.fi} files contain compiled code
                    127: * Engine::                      The inner interpreter and the primitives
1.13      pazsan    128: * Cross Compiler::              The Cross Compiler
1.1       anton     129: * Bugs::                        How to report them
                    130: * Origin::                      Authors and ancestors of Gforth
1.21      crook     131: * Forth-related information::   Books and places to look on the WWW
1.113     anton     132: * Licenses::                    
1.1       anton     133: * Word Index::                  An item for each Forth word
                    134: * Concept Index::               A menu covering many topics
1.12      anton     135: 
1.91      anton     136: @detailmenu
                    137:  --- The Detailed Node Listing ---
1.12      anton     138: 
1.29      crook     139: Gforth Environment
                    140: 
1.32      anton     141: * Invoking Gforth::             Getting in
                    142: * Leaving Gforth::              Getting out
                    143: * Command-line editing::        
1.48      anton     144: * Environment variables::       that affect how Gforth starts up
1.32      anton     145: * Gforth Files::                What gets installed and where
1.112     anton     146: * Gforth in pipes::             
1.48      anton     147: * Startup speed::               When 35ms is not fast enough ...
                    148: 
                    149: Forth Tutorial
                    150: 
                    151: * Starting Gforth Tutorial::    
                    152: * Syntax Tutorial::             
                    153: * Crash Course Tutorial::       
                    154: * Stack Tutorial::              
                    155: * Arithmetics Tutorial::        
                    156: * Stack Manipulation Tutorial::  
                    157: * Using files for Forth code Tutorial::  
                    158: * Comments Tutorial::           
                    159: * Colon Definitions Tutorial::  
                    160: * Decompilation Tutorial::      
                    161: * Stack-Effect Comments Tutorial::  
                    162: * Types Tutorial::              
                    163: * Factoring Tutorial::          
                    164: * Designing the stack effect Tutorial::  
                    165: * Local Variables Tutorial::    
                    166: * Conditional execution Tutorial::  
                    167: * Flags and Comparisons Tutorial::  
                    168: * General Loops Tutorial::      
                    169: * Counted loops Tutorial::      
                    170: * Recursion Tutorial::          
                    171: * Leaving definitions or loops Tutorial::  
                    172: * Return Stack Tutorial::       
                    173: * Memory Tutorial::             
                    174: * Characters and Strings Tutorial::  
                    175: * Alignment Tutorial::          
1.87      anton     176: * Files Tutorial::              
1.48      anton     177: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                    178: * Execution Tokens Tutorial::   
                    179: * Exceptions Tutorial::         
                    180: * Defining Words Tutorial::     
                    181: * Arrays and Records Tutorial::  
                    182: * POSTPONE Tutorial::           
                    183: * Literal Tutorial::            
                    184: * Advanced macros Tutorial::    
                    185: * Compilation Tokens Tutorial::  
                    186: * Wordlists and Search Order Tutorial::  
1.29      crook     187: 
1.24      anton     188: An Introduction to ANS Forth
                    189: 
1.67      anton     190: * Introducing the Text Interpreter::  
                    191: * Stacks and Postfix notation::  
                    192: * Your first definition::       
                    193: * How does that work?::         
                    194: * Forth is written in Forth::   
                    195: * Review - elements of a Forth system::  
                    196: * Where to go next::            
                    197: * Exercises::                   
1.24      anton     198: 
1.12      anton     199: Forth Words
                    200: 
                    201: * Notation::                    
1.65      anton     202: * Case insensitivity::          
                    203: * Comments::                    
                    204: * Boolean Flags::               
1.12      anton     205: * Arithmetic::                  
                    206: * Stack Manipulation::          
                    207: * Memory::                      
                    208: * Control Structures::          
                    209: * Defining Words::              
1.65      anton     210: * Interpretation and Compilation Semantics::  
1.47      crook     211: * Tokens for Words::            
1.81      anton     212: * Compiling words::             
1.65      anton     213: * The Text Interpreter::        
1.111     anton     214: * The Input Stream::            
1.65      anton     215: * Word Lists::                  
                    216: * Environmental Queries::       
1.12      anton     217: * Files::                       
                    218: * Blocks::                      
                    219: * Other I/O::                   
1.121     anton     220: * OS command line arguments::   
1.78      anton     221: * Locals::                      
                    222: * Structures::                  
                    223: * Object-oriented Forth::       
1.12      anton     224: * Programming Tools::           
                    225: * Assembler and Code Words::    
                    226: * Threading Words::             
1.65      anton     227: * Passing Commands to the OS::  
                    228: * Keeping track of Time::       
                    229: * Miscellaneous Words::         
1.12      anton     230: 
                    231: Arithmetic
                    232: 
                    233: * Single precision::            
1.67      anton     234: * Double precision::            Double-cell integer arithmetic
1.12      anton     235: * Bitwise operations::          
1.67      anton     236: * Numeric comparison::          
1.32      anton     237: * Mixed precision::             Operations with single and double-cell integers
1.12      anton     238: * Floating Point::              
                    239: 
                    240: Stack Manipulation
                    241: 
                    242: * Data stack::                  
                    243: * Floating point stack::        
                    244: * Return stack::                
                    245: * Locals stack::                
                    246: * Stack pointer manipulation::  
                    247: 
                    248: Memory
                    249: 
1.32      anton     250: * Memory model::                
                    251: * Dictionary allocation::       
                    252: * Heap Allocation::             
                    253: * Memory Access::               
                    254: * Address arithmetic::          
                    255: * Memory Blocks::               
1.12      anton     256: 
                    257: Control Structures
                    258: 
1.41      anton     259: * Selection::                   IF ... ELSE ... ENDIF
                    260: * Simple Loops::                BEGIN ...
1.32      anton     261: * Counted Loops::               DO
1.67      anton     262: * Arbitrary control structures::  
                    263: * Calls and returns::           
1.12      anton     264: * Exception Handling::          
                    265: 
                    266: Defining Words
                    267: 
1.67      anton     268: * CREATE::                      
1.44      crook     269: * Variables::                   Variables and user variables
1.67      anton     270: * Constants::                   
1.44      crook     271: * Values::                      Initialised variables
1.67      anton     272: * Colon Definitions::           
1.44      crook     273: * Anonymous Definitions::       Definitions without names
1.71      anton     274: * Supplying names::             Passing definition names as strings
1.67      anton     275: * User-defined Defining Words::  
1.44      crook     276: * Deferred words::              Allow forward references
1.67      anton     277: * Aliases::                     
1.47      crook     278: 
1.63      anton     279: User-defined Defining Words
                    280: 
                    281: * CREATE..DOES> applications::  
                    282: * CREATE..DOES> details::       
                    283: * Advanced does> usage example::  
1.91      anton     284: * @code{Const-does>}::          
1.63      anton     285: 
1.47      crook     286: Interpretation and Compilation Semantics
                    287: 
1.67      anton     288: * Combined words::              
1.12      anton     289: 
1.71      anton     290: Tokens for Words
                    291: 
                    292: * Execution token::             represents execution/interpretation semantics
                    293: * Compilation token::           represents compilation semantics
                    294: * Name token::                  represents named words
                    295: 
1.82      anton     296: Compiling words
                    297: 
                    298: * Literals::                    Compiling data values
                    299: * Macros::                      Compiling words
                    300: 
1.21      crook     301: The Text Interpreter
                    302: 
1.67      anton     303: * Input Sources::               
                    304: * Number Conversion::           
                    305: * Interpret/Compile states::    
                    306: * Interpreter Directives::      
1.21      crook     307: 
1.26      crook     308: Word Lists
                    309: 
1.75      anton     310: * Vocabularies::                
1.67      anton     311: * Why use word lists?::         
1.75      anton     312: * Word list example::           
1.26      crook     313: 
                    314: Files
                    315: 
1.48      anton     316: * Forth source files::          
                    317: * General files::               
                    318: * Search Paths::                
                    319: 
                    320: Search Paths
                    321: 
1.75      anton     322: * Source Search Paths::         
1.26      crook     323: * General Search Paths::        
                    324: 
                    325: Other I/O
                    326: 
1.32      anton     327: * Simple numeric output::       Predefined formats
                    328: * Formatted numeric output::    Formatted (pictured) output
                    329: * String Formats::              How Forth stores strings in memory
1.67      anton     330: * Displaying characters and strings::  Other stuff
1.32      anton     331: * Input::                       Input
1.112     anton     332: * Pipes::                       How to create your own pipes
1.26      crook     333: 
                    334: Locals
                    335: 
                    336: * Gforth locals::               
                    337: * ANS Forth locals::            
                    338: 
                    339: Gforth locals
                    340: 
                    341: * Where are locals visible by name?::  
                    342: * How long do locals live?::    
1.78      anton     343: * Locals programming style::    
                    344: * Locals implementation::       
1.26      crook     345: 
1.12      anton     346: Structures
                    347: 
                    348: * Why explicit structure support?::  
                    349: * Structure Usage::             
                    350: * Structure Naming Convention::  
                    351: * Structure Implementation::    
                    352: * Structure Glossary::          
                    353: 
                    354: Object-oriented Forth
                    355: 
1.48      anton     356: * Why object-oriented programming?::  
                    357: * Object-Oriented Terminology::  
                    358: * Objects::                     
                    359: * OOF::                         
                    360: * Mini-OOF::                    
1.23      crook     361: * Comparison with other object models::  
1.12      anton     362: 
1.24      anton     363: The @file{objects.fs} model
1.12      anton     364: 
                    365: * Properties of the Objects model::  
                    366: * Basic Objects Usage::         
1.41      anton     367: * The Objects base class::      
1.12      anton     368: * Creating objects::            
                    369: * Object-Oriented Programming Style::  
                    370: * Class Binding::               
                    371: * Method conveniences::         
                    372: * Classes and Scoping::         
1.41      anton     373: * Dividing classes::            
1.12      anton     374: * Object Interfaces::           
                    375: * Objects Implementation::      
                    376: * Objects Glossary::            
                    377: 
1.24      anton     378: The @file{oof.fs} model
1.12      anton     379: 
1.67      anton     380: * Properties of the OOF model::  
                    381: * Basic OOF Usage::             
                    382: * The OOF base class::          
                    383: * Class Declaration::           
                    384: * Class Implementation::        
1.12      anton     385: 
1.24      anton     386: The @file{mini-oof.fs} model
1.23      crook     387: 
1.48      anton     388: * Basic Mini-OOF Usage::        
                    389: * Mini-OOF Example::            
                    390: * Mini-OOF Implementation::     
1.23      crook     391: 
1.78      anton     392: Programming Tools
                    393: 
                    394: * Examining::                   
                    395: * Forgetting words::            
                    396: * Debugging::                   Simple and quick.
                    397: * Assertions::                  Making your programs self-checking.
                    398: * Singlestep Debugger::         Executing your program word by word.
                    399: 
                    400: Assembler and Code Words
                    401: 
                    402: * Code and ;code::              
                    403: * Common Assembler::            Assembler Syntax
                    404: * Common Disassembler::         
                    405: * 386 Assembler::               Deviations and special cases
                    406: * Alpha Assembler::             Deviations and special cases
                    407: * MIPS assembler::              Deviations and special cases
                    408: * Other assemblers::            How to write them
                    409: 
1.12      anton     410: Tools
                    411: 
                    412: * ANS Report::                  Report the words used, sorted by wordset.
                    413: 
                    414: ANS conformance
                    415: 
                    416: * The Core Words::              
                    417: * The optional Block word set::  
                    418: * The optional Double Number word set::  
                    419: * The optional Exception word set::  
                    420: * The optional Facility word set::  
                    421: * The optional File-Access word set::  
                    422: * The optional Floating-Point word set::  
                    423: * The optional Locals word set::  
                    424: * The optional Memory-Allocation word set::  
                    425: * The optional Programming-Tools word set::  
                    426: * The optional Search-Order word set::  
                    427: 
                    428: The Core Words
                    429: 
                    430: * core-idef::                   Implementation Defined Options                   
                    431: * core-ambcond::                Ambiguous Conditions                
                    432: * core-other::                  Other System Documentation                  
                    433: 
                    434: The optional Block word set
                    435: 
                    436: * block-idef::                  Implementation Defined Options
                    437: * block-ambcond::               Ambiguous Conditions               
                    438: * block-other::                 Other System Documentation                 
                    439: 
                    440: The optional Double Number word set
                    441: 
                    442: * double-ambcond::              Ambiguous Conditions              
                    443: 
                    444: The optional Exception word set
                    445: 
                    446: * exception-idef::              Implementation Defined Options              
                    447: 
                    448: The optional Facility word set
                    449: 
                    450: * facility-idef::               Implementation Defined Options               
                    451: * facility-ambcond::            Ambiguous Conditions            
                    452: 
                    453: The optional File-Access word set
                    454: 
                    455: * file-idef::                   Implementation Defined Options
                    456: * file-ambcond::                Ambiguous Conditions                
                    457: 
                    458: The optional Floating-Point word set
                    459: 
                    460: * floating-idef::               Implementation Defined Options
                    461: * floating-ambcond::            Ambiguous Conditions            
                    462: 
                    463: The optional Locals word set
                    464: 
                    465: * locals-idef::                 Implementation Defined Options                 
                    466: * locals-ambcond::              Ambiguous Conditions              
                    467: 
                    468: The optional Memory-Allocation word set
                    469: 
                    470: * memory-idef::                 Implementation Defined Options                 
                    471: 
                    472: The optional Programming-Tools word set
                    473: 
                    474: * programming-idef::            Implementation Defined Options            
                    475: * programming-ambcond::         Ambiguous Conditions         
                    476: 
                    477: The optional Search-Order word set
                    478: 
                    479: * search-idef::                 Implementation Defined Options                 
                    480: * search-ambcond::              Ambiguous Conditions              
                    481: 
1.109     anton     482: Emacs and Gforth
                    483: 
                    484: * Installing gforth.el::        Making Emacs aware of Forth.
                    485: * Emacs Tags::                  Viewing the source of a word in Emacs.
                    486: * Hilighting::                  Making Forth code look prettier.
                    487: * Auto-Indentation::            Customizing auto-indentation.
                    488: * Blocks Files::                Reading and writing blocks files.
                    489: 
1.12      anton     490: Image Files
                    491: 
1.24      anton     492: * Image Licensing Issues::      Distribution terms for images.
                    493: * Image File Background::       Why have image files?
1.67      anton     494: * Non-Relocatable Image Files::  don't always work.
1.24      anton     495: * Data-Relocatable Image Files::  are better.
1.67      anton     496: * Fully Relocatable Image Files::  better yet.
1.24      anton     497: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.32      anton     498: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.24      anton     499: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     500: 
                    501: Fully Relocatable Image Files
                    502: 
1.27      crook     503: * gforthmi::                    The normal way
1.12      anton     504: * cross.fs::                    The hard way
                    505: 
                    506: Engine
                    507: 
                    508: * Portability::                 
                    509: * Threading::                   
                    510: * Primitives::                  
                    511: * Performance::                 
                    512: 
                    513: Threading
                    514: 
                    515: * Scheduling::                  
                    516: * Direct or Indirect Threaded?::  
1.109     anton     517: * Dynamic Superinstructions::   
1.12      anton     518: * DOES>::                       
                    519: 
                    520: Primitives
                    521: 
                    522: * Automatic Generation::        
                    523: * TOS Optimization::            
                    524: * Produced code::               
1.13      pazsan    525: 
                    526: Cross Compiler
                    527: 
1.67      anton     528: * Using the Cross Compiler::    
                    529: * How the Cross Compiler Works::  
1.13      pazsan    530: 
1.113     anton     531: Licenses
                    532: 
                    533: * GNU Free Documentation License::  License for copying this manual.
                    534: * Copying::                         GPL (for copying this software).
                    535: 
1.24      anton     536: @end detailmenu
1.1       anton     537: @end menu
                    538: 
1.113     anton     539: @c ----------------------------------------------------------
1.1       anton     540: @iftex
                    541: @unnumbered Preface
                    542: @cindex Preface
1.21      crook     543: This manual documents Gforth. Some introductory material is provided for
                    544: readers who are unfamiliar with Forth or who are migrating to Gforth
                    545: from other Forth compilers. However, this manual is primarily a
                    546: reference manual.
1.1       anton     547: @end iftex
                    548: 
1.28      crook     549: @comment TODO much more blurb here.
1.26      crook     550: 
                    551: @c ******************************************************************
1.113     anton     552: @node Goals, Gforth Environment, Top, Top
1.26      crook     553: @comment node-name,     next,           previous, up
                    554: @chapter Goals of Gforth
                    555: @cindex goals of the Gforth project
                    556: The goal of the Gforth Project is to develop a standard model for
                    557: ANS Forth. This can be split into several subgoals:
                    558: 
                    559: @itemize @bullet
                    560: @item
                    561: Gforth should conform to the ANS Forth Standard.
                    562: @item
                    563: It should be a model, i.e. it should define all the
                    564: implementation-dependent things.
                    565: @item
                    566: It should become standard, i.e. widely accepted and used. This goal
                    567: is the most difficult one.
                    568: @end itemize
                    569: 
                    570: To achieve these goals Gforth should be
                    571: @itemize @bullet
                    572: @item
                    573: Similar to previous models (fig-Forth, F83)
                    574: @item
                    575: Powerful. It should provide for all the things that are considered
                    576: necessary today and even some that are not yet considered necessary.
                    577: @item
                    578: Efficient. It should not get the reputation of being exceptionally
                    579: slow.
                    580: @item
                    581: Free.
                    582: @item
                    583: Available on many machines/easy to port.
                    584: @end itemize
                    585: 
                    586: Have we achieved these goals? Gforth conforms to the ANS Forth
                    587: standard. It may be considered a model, but we have not yet documented
                    588: which parts of the model are stable and which parts we are likely to
                    589: change. It certainly has not yet become a de facto standard, but it
                    590: appears to be quite popular. It has some similarities to and some
                    591: differences from previous models. It has some powerful features, but not
                    592: yet everything that we envisioned. We certainly have achieved our
1.65      anton     593: execution speed goals (@pxref{Performance})@footnote{However, in 1998
                    594: the bar was raised when the major commercial Forth vendors switched to
                    595: native code compilers.}.  It is free and available on many machines.
1.29      crook     596: 
1.26      crook     597: @c ******************************************************************
1.48      anton     598: @node Gforth Environment, Tutorial, Goals, Top
1.29      crook     599: @chapter Gforth Environment
                    600: @cindex Gforth environment
1.21      crook     601: 
1.45      crook     602: Note: ultimately, the Gforth man page will be auto-generated from the
1.29      crook     603: material in this chapter.
1.21      crook     604: 
                    605: @menu
1.29      crook     606: * Invoking Gforth::             Getting in
                    607: * Leaving Gforth::              Getting out
                    608: * Command-line editing::        
1.48      anton     609: * Environment variables::       that affect how Gforth starts up
1.29      crook     610: * Gforth Files::                What gets installed and where
1.112     anton     611: * Gforth in pipes::             
1.48      anton     612: * Startup speed::               When 35ms is not fast enough ...
1.21      crook     613: @end menu
                    614: 
1.49      anton     615: For related information about the creation of images see @ref{Image Files}.
1.29      crook     616: 
1.21      crook     617: @comment ----------------------------------------------
1.48      anton     618: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29      crook     619: @section Invoking Gforth
                    620: @cindex invoking Gforth
                    621: @cindex running Gforth
                    622: @cindex command-line options
                    623: @cindex options on the command line
                    624: @cindex flags on the command line
1.21      crook     625: 
1.30      anton     626: Gforth is made up of two parts; an executable ``engine'' (named
1.109     anton     627: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30      anton     628: will usually just say @code{gforth} -- this automatically loads the
                    629: default image file @file{gforth.fi}. In many other cases the default
                    630: Gforth image will be invoked like this:
1.21      crook     631: @example
1.30      anton     632: gforth [file | -e forth-code] ...
1.21      crook     633: @end example
1.29      crook     634: @noindent
                    635: This interprets the contents of the files and the Forth code in the order they
                    636: are given.
1.21      crook     637: 
1.109     anton     638: In addition to the @command{gforth} engine, there is also an engine
                    639: called @command{gforth-fast}, which is faster, but gives less
                    640: informative error messages (@pxref{Error messages}) and may catch some
                    641: stack underflows later or not at all.  You should use it for debugged,
                    642: performance-critical programs.
                    643: 
                    644: Moreover, there is an engine called @command{gforth-itc}, which is
                    645: useful in some backwards-compatibility situations (@pxref{Direct or
                    646: Indirect Threaded?}).
1.30      anton     647: 
1.29      crook     648: In general, the command line looks like this:
1.21      crook     649: 
                    650: @example
1.30      anton     651: gforth[-fast] [engine options] [image options]
1.21      crook     652: @end example
                    653: 
1.30      anton     654: The engine options must come before the rest of the command
1.29      crook     655: line. They are:
1.26      crook     656: 
1.29      crook     657: @table @code
                    658: @cindex -i, command-line option
                    659: @cindex --image-file, command-line option
                    660: @item --image-file @i{file}
                    661: @itemx -i @i{file}
                    662: Loads the Forth image @i{file} instead of the default
                    663: @file{gforth.fi} (@pxref{Image Files}).
1.21      crook     664: 
1.39      anton     665: @cindex --appl-image, command-line option
                    666: @item --appl-image @i{file}
                    667: Loads the image @i{file} and leaves all further command-line arguments
1.65      anton     668: to the image (instead of processing them as engine options).  This is
                    669: useful for building executable application images on Unix, built with
1.39      anton     670: @code{gforthmi --application ...}.
                    671: 
1.29      crook     672: @cindex --path, command-line option
                    673: @cindex -p, command-line option
                    674: @item --path @i{path}
                    675: @itemx -p @i{path}
                    676: Uses @i{path} for searching the image file and Forth source code files
                    677: instead of the default in the environment variable @code{GFORTHPATH} or
                    678: the path specified at installation time (e.g.,
                    679: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                    680: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook     681: 
1.29      crook     682: @cindex --dictionary-size, command-line option
                    683: @cindex -m, command-line option
                    684: @cindex @i{size} parameters for command-line options
                    685: @cindex size of the dictionary and the stacks
                    686: @item --dictionary-size @i{size}
                    687: @itemx -m @i{size}
                    688: Allocate @i{size} space for the Forth dictionary space instead of
                    689: using the default specified in the image (typically 256K). The
                    690: @i{size} specification for this and subsequent options consists of
                    691: an integer and a unit (e.g.,
                    692: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
                    693: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                    694: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                    695: @code{e} is used.
1.21      crook     696: 
1.29      crook     697: @cindex --data-stack-size, command-line option
                    698: @cindex -d, command-line option
                    699: @item --data-stack-size @i{size}
                    700: @itemx -d @i{size}
                    701: Allocate @i{size} space for the data stack instead of using the
                    702: default specified in the image (typically 16K).
1.21      crook     703: 
1.29      crook     704: @cindex --return-stack-size, command-line option
                    705: @cindex -r, command-line option
                    706: @item --return-stack-size @i{size}
                    707: @itemx -r @i{size}
                    708: Allocate @i{size} space for the return stack instead of using the
                    709: default specified in the image (typically 15K).
1.21      crook     710: 
1.29      crook     711: @cindex --fp-stack-size, command-line option
                    712: @cindex -f, command-line option
                    713: @item --fp-stack-size @i{size}
                    714: @itemx -f @i{size}
                    715: Allocate @i{size} space for the floating point stack instead of
                    716: using the default specified in the image (typically 15.5K). In this case
                    717: the unit specifier @code{e} refers to floating point numbers.
1.21      crook     718: 
1.48      anton     719: @cindex --locals-stack-size, command-line option
                    720: @cindex -l, command-line option
                    721: @item --locals-stack-size @i{size}
                    722: @itemx -l @i{size}
                    723: Allocate @i{size} space for the locals stack instead of using the
                    724: default specified in the image (typically 14.5K).
                    725: 
                    726: @cindex -h, command-line option
                    727: @cindex --help, command-line option
                    728: @item --help
                    729: @itemx -h
                    730: Print a message about the command-line options
                    731: 
                    732: @cindex -v, command-line option
                    733: @cindex --version, command-line option
                    734: @item --version
                    735: @itemx -v
                    736: Print version and exit
                    737: 
                    738: @cindex --debug, command-line option
                    739: @item --debug
                    740: Print some information useful for debugging on startup.
                    741: 
                    742: @cindex --offset-image, command-line option
                    743: @item --offset-image
                    744: Start the dictionary at a slightly different position than would be used
                    745: otherwise (useful for creating data-relocatable images,
                    746: @pxref{Data-Relocatable Image Files}).
                    747: 
                    748: @cindex --no-offset-im, command-line option
                    749: @item --no-offset-im
                    750: Start the dictionary at the normal position.
                    751: 
                    752: @cindex --clear-dictionary, command-line option
                    753: @item --clear-dictionary
                    754: Initialize all bytes in the dictionary to 0 before loading the image
                    755: (@pxref{Data-Relocatable Image Files}).
                    756: 
                    757: @cindex --die-on-signal, command-line-option
                    758: @item --die-on-signal
                    759: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                    760: or the segmentation violation SIGSEGV) by translating it into a Forth
                    761: @code{THROW}. With this option, Gforth exits if it receives such a
                    762: signal. This option is useful when the engine and/or the image might be
                    763: severely broken (such that it causes another signal before recovering
                    764: from the first); this option avoids endless loops in such cases.
1.109     anton     765: 
1.119     anton     766: @cindex --no-dynamic, command-line option
                    767: @cindex --dynamic, command-line option
1.109     anton     768: @item --no-dynamic
                    769: @item --dynamic
                    770: Disable or enable dynamic superinstructions with replication
                    771: (@pxref{Dynamic Superinstructions}).
                    772: 
1.119     anton     773: @cindex --no-super, command-line option
1.109     anton     774: @item --no-super
1.110     anton     775: Disable dynamic superinstructions, use just dynamic replication; this is
                    776: useful if you want to patch threaded code (@pxref{Dynamic
                    777: Superinstructions}).
1.119     anton     778: 
                    779: @cindex --ss-number, command-line option
                    780: @item --ss-number=@var{N}
                    781: Use only the first @var{N} static superinstructions compiled into the
                    782: engine (default: use them all; note that only @code{gforth-fast} has
                    783: any).  This option is useful for measuring the performance impact of
                    784: static superinstructions.
                    785: 
                    786: @cindex --ss-min-..., command-line options
                    787: @item --ss-min-codesize
                    788: @item --ss-min-ls
                    789: @item --ss-min-lsu
                    790: @item --ss-min-nexts
                    791: Use specified metric for determining the cost of a primitive or static
                    792: superinstruction for static superinstruction selection.  @code{Codesize}
                    793: is the native code size of the primive or static superinstruction,
                    794: @code{ls} is the number of loads and stores, @code{lsu} is the number of
                    795: loads, stores, and updates, and @code{nexts} is the number of dispatches
                    796: (not taking dynamic superinstructions into account), i.e. every
                    797: primitive or static superinstruction has cost 1. Default:
                    798: @code{codesize} if you use dynamic code generation, otherwise
                    799: @code{nexts}.
                    800: 
                    801: @cindex --ss-greedy, command-line option
                    802: @item --ss-greedy
                    803: This option is useful for measuring the performance impact of static
                    804: superinstructions.  By default, an optimal shortest-path algorithm is
                    805: used for selecting static superinstructions.  With @option{--ss-greedy}
                    806: this algorithm is modified to assume that anything after the static
                    807: superinstruction currently under consideration is not combined into
                    808: static superinstructions.  With @option{--ss-min-nexts} this produces
                    809: the same result as a greedy algorithm that always selects the longest
                    810: superinstruction available at the moment.  E.g., if there are
                    811: superinstructions AB and BCD, then for the sequence A B C D the optimal
                    812: algorithm will select A BCD and the greedy algorithm will select AB C D.
                    813: 
                    814: @cindex --print-metrics, command-line option
                    815: @item --print-metrics
                    816: Prints some metrics used during static superinstruction selection:
                    817: @code{code size} is the actual size of the dynamically generated code.
                    818: @code{Metric codesize} is the sum of the codesize metrics as seen by
                    819: static superinstruction selection; there is a difference from @code{code
                    820: size}, because not all primitives and static superinstructions are
                    821: compiled into dynamically generated code, and because of markers.  The
                    822: other metrics correspond to the @option{ss-min-...} options.  This
                    823: option is useful for evaluating the effects of the @option{--ss-...}
                    824: options.
1.109     anton     825: 
1.48      anton     826: @end table
                    827: 
                    828: @cindex loading files at startup
                    829: @cindex executing code on startup
                    830: @cindex batch processing with Gforth
                    831: As explained above, the image-specific command-line arguments for the
                    832: default image @file{gforth.fi} consist of a sequence of filenames and
                    833: @code{-e @var{forth-code}} options that are interpreted in the sequence
                    834: in which they are given. The @code{-e @var{forth-code}} or
1.121     anton     835: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
                    836: option takes only one argument; if you want to evaluate more Forth
                    837: words, you have to quote them or use @code{-e} several times. To exit
1.48      anton     838: after processing the command line (instead of entering interactive mode)
1.121     anton     839: append @code{-e bye} to the command line.  You can also process the
                    840: command-line arguments with a Forth program (@pxref{OS command line
                    841: arguments}).
1.48      anton     842: 
                    843: @cindex versions, invoking other versions of Gforth
                    844: If you have several versions of Gforth installed, @code{gforth} will
                    845: invoke the version that was installed last. @code{gforth-@i{version}}
                    846: invokes a specific version. If your environment contains the variable
                    847: @code{GFORTHPATH}, you may want to override it by using the
                    848: @code{--path} option.
                    849: 
                    850: Not yet implemented:
                    851: On startup the system first executes the system initialization file
                    852: (unless the option @code{--no-init-file} is given; note that the system
                    853: resulting from using this option may not be ANS Forth conformant). Then
                    854: the user initialization file @file{.gforth.fs} is executed, unless the
1.62      crook     855: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48      anton     856: then in @file{~}, then in the normal path (see above).
                    857: 
                    858: 
                    859: 
                    860: @comment ----------------------------------------------
                    861: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
                    862: @section Leaving Gforth
                    863: @cindex Gforth - leaving
                    864: @cindex leaving Gforth
                    865: 
                    866: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
                    867: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
                    868: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49      anton     869: data are discarded.  For ways of saving the state of the system before
                    870: leaving Gforth see @ref{Image Files}.
1.48      anton     871: 
                    872: doc-bye
                    873: 
                    874: 
                    875: @comment ----------------------------------------------
1.65      anton     876: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48      anton     877: @section Command-line editing
                    878: @cindex command-line editing
                    879: 
                    880: Gforth maintains a history file that records every line that you type to
                    881: the text interpreter. This file is preserved between sessions, and is
                    882: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
                    883: repeatedly you can recall successively older commands from this (or
                    884: previous) session(s). The full list of command-line editing facilities is:
                    885: 
                    886: @itemize @bullet
                    887: @item
                    888: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
                    889: commands from the history buffer.
                    890: @item
                    891: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
                    892: from the history buffer.
                    893: @item
                    894: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
                    895: @item
                    896: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
                    897: @item
                    898: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
                    899: closing up the line.
                    900: @item
                    901: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
                    902: @item
                    903: @kbd{Ctrl-a} to move the cursor to the start of the line.
                    904: @item
                    905: @kbd{Ctrl-e} to move the cursor to the end of the line.
                    906: @item
                    907: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
                    908: line.
                    909: @item
                    910: @key{TAB} to step through all possible full-word completions of the word
                    911: currently being typed.
                    912: @item
1.65      anton     913: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
                    914: using @code{bye}). 
                    915: @item
                    916: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
                    917: character under the cursor.
1.48      anton     918: @end itemize
                    919: 
                    920: When editing, displayable characters are inserted to the left of the
                    921: cursor position; the line is always in ``insert'' (as opposed to
                    922: ``overstrike'') mode.
                    923: 
                    924: @cindex history file
                    925: @cindex @file{.gforth-history}
                    926: On Unix systems, the history file is @file{~/.gforth-history} by
                    927: default@footnote{i.e. it is stored in the user's home directory.}. You
                    928: can find out the name and location of your history file using:
                    929: 
                    930: @example 
                    931: history-file type \ Unix-class systems
                    932: 
                    933: history-file type \ Other systems
                    934: history-dir  type
                    935: @end example
                    936: 
                    937: If you enter long definitions by hand, you can use a text editor to
                    938: paste them out of the history file into a Forth source file for reuse at
                    939: a later time.
                    940: 
                    941: Gforth never trims the size of the history file, so you should do this
                    942: periodically, if necessary.
                    943: 
                    944: @comment this is all defined in history.fs
                    945: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
                    946: @comment chosen?
                    947: 
                    948: 
                    949: @comment ----------------------------------------------
1.65      anton     950: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48      anton     951: @section Environment variables
                    952: @cindex environment variables
                    953: 
                    954: Gforth uses these environment variables:
                    955: 
                    956: @itemize @bullet
                    957: @item
                    958: @cindex @code{GFORTHHIST} -- environment variable
                    959: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
                    960: open/create the history file, @file{.gforth-history}. Default:
                    961: @code{$HOME}.
                    962: 
                    963: @item
                    964: @cindex @code{GFORTHPATH} -- environment variable
                    965: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
                    966: for Forth source-code files.
                    967: 
                    968: @item
                    969: @cindex @code{GFORTH} -- environment variable
1.49      anton     970: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton     971: 
                    972: @item
                    973: @cindex @code{GFORTHD} -- environment variable
1.62      crook     974: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton     975: 
                    976: @item
                    977: @cindex @code{TMP}, @code{TEMP} - environment variable
                    978: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
                    979: location for the history file.
                    980: @end itemize
                    981: 
                    982: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
                    983: @comment mentioning these.
                    984: 
                    985: All the Gforth environment variables default to sensible values if they
                    986: are not set.
                    987: 
                    988: 
                    989: @comment ----------------------------------------------
1.112     anton     990: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48      anton     991: @section Gforth files
                    992: @cindex Gforth files
                    993: 
                    994: When you install Gforth on a Unix system, it installs files in these
                    995: locations by default:
                    996: 
                    997: @itemize @bullet
                    998: @item
                    999: @file{/usr/local/bin/gforth}
                   1000: @item
                   1001: @file{/usr/local/bin/gforthmi}
                   1002: @item
                   1003: @file{/usr/local/man/man1/gforth.1} - man page.
                   1004: @item
                   1005: @file{/usr/local/info} - the Info version of this manual.
                   1006: @item
                   1007: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
                   1008: @item
                   1009: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
                   1010: @item
                   1011: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
                   1012: @item
                   1013: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
                   1014: @end itemize
                   1015: 
                   1016: You can select different places for installation by using
                   1017: @code{configure} options (listed with @code{configure --help}).
                   1018: 
                   1019: @comment ----------------------------------------------
1.112     anton    1020: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
                   1021: @section Gforth in pipes
                   1022: @cindex pipes, Gforth as part of
                   1023: 
                   1024: Gforth can be used in pipes created elsewhere (described here).  It can
                   1025: also create pipes on its own (@pxref{Pipes}).
                   1026: 
                   1027: @cindex input from pipes
                   1028: If you pipe into Gforth, your program should read with @code{read-file}
                   1029: or @code{read-line} from @code{stdin} (@pxref{General files}).
                   1030: @code{Key} does not recognize the end of input.  Words like
                   1031: @code{accept} echo the input and are therefore usually not useful for
                   1032: reading from a pipe.  You have to invoke the Forth program with an OS
                   1033: command-line option, as you have no chance to use the Forth command line
                   1034: (the text interpreter would try to interpret the pipe input).
                   1035: 
                   1036: @cindex output in pipes
                   1037: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
                   1038: 
                   1039: @cindex silent exiting from Gforth
                   1040: When you write to a pipe that has been closed at the other end, Gforth
                   1041: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
                   1042: into the exception @code{broken-pipe-error}.  If your application does
                   1043: not catch that exception, the system catches it and exits, usually
                   1044: silently (unless you were working on the Forth command line; then it
                   1045: prints an error message and exits).  This is usually the desired
                   1046: behaviour.
                   1047: 
                   1048: If you do not like this behaviour, you have to catch the exception
                   1049: yourself, and react to it.
                   1050: 
                   1051: Here's an example of an invocation of Gforth that is usable in a pipe:
                   1052: 
                   1053: @example
                   1054: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
                   1055:  type repeat ; foo bye"
                   1056: @end example
                   1057: 
                   1058: This example just copies the input verbatim to the output.  A very
                   1059: simple pipe containing this example looks like this:
                   1060: 
                   1061: @example
                   1062: cat startup.fs |
                   1063: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
                   1064:  type repeat ; foo bye"|
                   1065: head
                   1066: @end example
                   1067: 
                   1068: @cindex stderr and pipes
                   1069: Pipes involving Gforth's @code{stderr} output do not work.
                   1070: 
                   1071: @comment ----------------------------------------------
                   1072: @node Startup speed,  , Gforth in pipes, Gforth Environment
1.48      anton    1073: @section Startup speed
                   1074: @cindex Startup speed
                   1075: @cindex speed, startup
                   1076: 
                   1077: If Gforth is used for CGI scripts or in shell scripts, its startup
                   1078: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
                   1079: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
                   1080: system time.
                   1081: 
                   1082: If startup speed is a problem, you may consider the following ways to
                   1083: improve it; or you may consider ways to reduce the number of startups
1.62      crook    1084: (for example, by using Fast-CGI).
1.48      anton    1085: 
1.112     anton    1086: An easy step that influences Gforth startup speed is the use of the
                   1087: @option{--no-dynamic} option; this decreases image loading speed, but
                   1088: increases compile-time and run-time.
                   1089: 
                   1090: Another step to improve startup speed is to statically link Gforth, by
1.48      anton    1091: building it with @code{XLDFLAGS=-static}.  This requires more memory for
                   1092: the code and will therefore slow down the first invocation, but
                   1093: subsequent invocations avoid the dynamic linking overhead.  Another
                   1094: disadvantage is that Gforth won't profit from library upgrades.  As a
                   1095: result, @code{gforth-static -e bye} takes about 17.1ms user and
                   1096: 8.2ms system time.
                   1097: 
                   1098: The next step to improve startup speed is to use a non-relocatable image
1.65      anton    1099: (@pxref{Non-Relocatable Image Files}).  You can create this image with
1.48      anton    1100: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
                   1101: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
                   1102: and a part of the copy-on-write overhead.  The disadvantage is that the
1.62      crook    1103: non-relocatable image does not work if the OS gives Gforth a different
1.48      anton    1104: address for the dictionary, for whatever reason; so you better provide a
                   1105: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
                   1106: bye} takes about 15.3ms user and 7.5ms system time.
                   1107: 
                   1108: The final step is to disable dictionary hashing in Gforth.  Gforth
                   1109: builds the hash table on startup, which takes much of the startup
                   1110: overhead. You can do this by commenting out the @code{include hash.fs}
                   1111: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
                   1112: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
                   1113: The disadvantages are that functionality like @code{table} and
                   1114: @code{ekey} is missing and that text interpretation (e.g., compiling)
                   1115: now takes much longer. So, you should only use this method if there is
                   1116: no significant text interpretation to perform (the script should be
1.62      crook    1117: compiled into the image, amongst other things).  @code{gforth-static -i
1.48      anton    1118: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
                   1119: 
                   1120: @c ******************************************************************
                   1121: @node Tutorial, Introduction, Gforth Environment, Top
                   1122: @chapter Forth Tutorial
                   1123: @cindex Tutorial
                   1124: @cindex Forth Tutorial
                   1125: 
1.67      anton    1126: @c Topics from nac's Introduction that could be mentioned:
                   1127: @c press <ret> after each line
                   1128: @c Prompt
                   1129: @c numbers vs. words in dictionary on text interpretation
                   1130: @c what happens on redefinition
                   1131: @c parsing words (in particular, defining words)
                   1132: 
1.83      anton    1133: The difference of this chapter from the Introduction
                   1134: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
                   1135: be used while sitting in front of a computer, and covers much more
                   1136: material, but does not explain how the Forth system works.
                   1137: 
1.62      crook    1138: This tutorial can be used with any ANS-compliant Forth; any
                   1139: Gforth-specific features are marked as such and you can skip them if you
                   1140: work with another Forth.  This tutorial does not explain all features of
                   1141: Forth, just enough to get you started and give you some ideas about the
                   1142: facilities available in Forth.  Read the rest of the manual and the
                   1143: standard when you are through this.
1.48      anton    1144: 
                   1145: The intended way to use this tutorial is that you work through it while
                   1146: sitting in front of the console, take a look at the examples and predict
                   1147: what they will do, then try them out; if the outcome is not as expected,
                   1148: find out why (e.g., by trying out variations of the example), so you
                   1149: understand what's going on.  There are also some assignments that you
                   1150: should solve.
                   1151: 
                   1152: This tutorial assumes that you have programmed before and know what,
                   1153: e.g., a loop is.
                   1154: 
                   1155: @c !! explain compat library
                   1156: 
                   1157: @menu
                   1158: * Starting Gforth Tutorial::    
                   1159: * Syntax Tutorial::             
                   1160: * Crash Course Tutorial::       
                   1161: * Stack Tutorial::              
                   1162: * Arithmetics Tutorial::        
                   1163: * Stack Manipulation Tutorial::  
                   1164: * Using files for Forth code Tutorial::  
                   1165: * Comments Tutorial::           
                   1166: * Colon Definitions Tutorial::  
                   1167: * Decompilation Tutorial::      
                   1168: * Stack-Effect Comments Tutorial::  
                   1169: * Types Tutorial::              
                   1170: * Factoring Tutorial::          
                   1171: * Designing the stack effect Tutorial::  
                   1172: * Local Variables Tutorial::    
                   1173: * Conditional execution Tutorial::  
                   1174: * Flags and Comparisons Tutorial::  
                   1175: * General Loops Tutorial::      
                   1176: * Counted loops Tutorial::      
                   1177: * Recursion Tutorial::          
                   1178: * Leaving definitions or loops Tutorial::  
                   1179: * Return Stack Tutorial::       
                   1180: * Memory Tutorial::             
                   1181: * Characters and Strings Tutorial::  
                   1182: * Alignment Tutorial::          
1.87      anton    1183: * Files Tutorial::              
1.48      anton    1184: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                   1185: * Execution Tokens Tutorial::   
                   1186: * Exceptions Tutorial::         
                   1187: * Defining Words Tutorial::     
                   1188: * Arrays and Records Tutorial::  
                   1189: * POSTPONE Tutorial::           
                   1190: * Literal Tutorial::            
                   1191: * Advanced macros Tutorial::    
                   1192: * Compilation Tokens Tutorial::  
                   1193: * Wordlists and Search Order Tutorial::  
                   1194: @end menu
                   1195: 
                   1196: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
                   1197: @section Starting Gforth
1.66      anton    1198: @cindex starting Gforth tutorial
1.48      anton    1199: You can start Gforth by typing its name:
                   1200: 
                   1201: @example
                   1202: gforth
                   1203: @end example
                   1204: 
                   1205: That puts you into interactive mode; you can leave Gforth by typing
                   1206: @code{bye}.  While in Gforth, you can edit the command line and access
                   1207: the command line history with cursor keys, similar to bash.
                   1208: 
                   1209: 
                   1210: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
                   1211: @section Syntax
1.66      anton    1212: @cindex syntax tutorial
1.48      anton    1213: 
                   1214: A @dfn{word} is a sequence of arbitrary characters (expcept white
                   1215: space).  Words are separated by white space.  E.g., each of the
                   1216: following lines contains exactly one word:
                   1217: 
                   1218: @example
                   1219: word
                   1220: !@@#$%^&*()
                   1221: 1234567890
                   1222: 5!a
                   1223: @end example
                   1224: 
                   1225: A frequent beginner's error is to leave away necessary white space,
                   1226: resulting in an error like @samp{Undefined word}; so if you see such an
                   1227: error, check if you have put spaces wherever necessary.
                   1228: 
                   1229: @example
                   1230: ." hello, world" \ correct
                   1231: ."hello, world"  \ gives an "Undefined word" error
                   1232: @end example
                   1233: 
1.65      anton    1234: Gforth and most other Forth systems ignore differences in case (they are
1.48      anton    1235: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
                   1236: your system is case-sensitive, you may have to type all the examples
                   1237: given here in upper case.
                   1238: 
                   1239: 
                   1240: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
                   1241: @section Crash Course
                   1242: 
                   1243: Type
                   1244: 
                   1245: @example
                   1246: 0 0 !
                   1247: here execute
                   1248: ' catch >body 20 erase abort
                   1249: ' (quit) >body 20 erase
                   1250: @end example
                   1251: 
                   1252: The last two examples are guaranteed to destroy parts of Gforth (and
                   1253: most other systems), so you better leave Gforth afterwards (if it has
                   1254: not finished by itself).  On some systems you may have to kill gforth
                   1255: from outside (e.g., in Unix with @code{kill}).
                   1256: 
                   1257: Now that you know how to produce crashes (and that there's not much to
                   1258: them), let's learn how to produce meaningful programs.
                   1259: 
                   1260: 
                   1261: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
                   1262: @section Stack
1.66      anton    1263: @cindex stack tutorial
1.48      anton    1264: 
                   1265: The most obvious feature of Forth is the stack.  When you type in a
                   1266: number, it is pushed on the stack.  You can display the content of the
                   1267: stack with @code{.s}.
                   1268: 
                   1269: @example
                   1270: 1 2 .s
                   1271: 3 .s
                   1272: @end example
                   1273: 
                   1274: @code{.s} displays the top-of-stack to the right, i.e., the numbers
                   1275: appear in @code{.s} output as they appeared in the input.
                   1276: 
                   1277: You can print the top of stack element with @code{.}.
                   1278: 
                   1279: @example
                   1280: 1 2 3 . . .
                   1281: @end example
                   1282: 
                   1283: In general, words consume their stack arguments (@code{.s} is an
                   1284: exception).
                   1285: 
                   1286: @assignment
                   1287: What does the stack contain after @code{5 6 7 .}?
                   1288: @endassignment
                   1289: 
                   1290: 
                   1291: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
                   1292: @section Arithmetics
1.66      anton    1293: @cindex arithmetics tutorial
1.48      anton    1294: 
                   1295: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
                   1296: operate on the top two stack items:
                   1297: 
                   1298: @example
1.67      anton    1299: 2 2 .s
                   1300: + .s
                   1301: .
1.48      anton    1302: 2 1 - .
                   1303: 7 3 mod .
                   1304: @end example
                   1305: 
                   1306: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
                   1307: as in the corresponding infix expression (this is generally the case in
                   1308: Forth).
                   1309: 
                   1310: Parentheses are superfluous (and not available), because the order of
                   1311: the words unambiguously determines the order of evaluation and the
                   1312: operands:
                   1313: 
                   1314: @example
                   1315: 3 4 + 5 * .
                   1316: 3 4 5 * + .
                   1317: @end example
                   1318: 
                   1319: @assignment
                   1320: What are the infix expressions corresponding to the Forth code above?
                   1321: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
                   1322: known as Postfix or RPN (Reverse Polish Notation).}.
                   1323: @endassignment
                   1324: 
                   1325: To change the sign, use @code{negate}:
                   1326: 
                   1327: @example
                   1328: 2 negate .
                   1329: @end example
                   1330: 
                   1331: @assignment
                   1332: Convert -(-3)*4-5 to Forth.
                   1333: @endassignment
                   1334: 
                   1335: @code{/mod} performs both @code{/} and @code{mod}.
                   1336: 
                   1337: @example
                   1338: 7 3 /mod . .
                   1339: @end example
                   1340: 
1.66      anton    1341: Reference: @ref{Arithmetic}.
                   1342: 
                   1343: 
1.48      anton    1344: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
                   1345: @section Stack Manipulation
1.66      anton    1346: @cindex stack manipulation tutorial
1.48      anton    1347: 
                   1348: Stack manipulation words rearrange the data on the stack.
                   1349: 
                   1350: @example
                   1351: 1 .s drop .s
                   1352: 1 .s dup .s drop drop .s
                   1353: 1 2 .s over .s drop drop drop
                   1354: 1 2 .s swap .s drop drop
                   1355: 1 2 3 .s rot .s drop drop drop
                   1356: @end example
                   1357: 
                   1358: These are the most important stack manipulation words.  There are also
                   1359: variants that manipulate twice as many stack items:
                   1360: 
                   1361: @example
                   1362: 1 2 3 4 .s 2swap .s 2drop 2drop
                   1363: @end example
                   1364: 
                   1365: Two more stack manipulation words are:
                   1366: 
                   1367: @example
                   1368: 1 2 .s nip .s drop
                   1369: 1 2 .s tuck .s 2drop drop
                   1370: @end example
                   1371: 
                   1372: @assignment
                   1373: Replace @code{nip} and @code{tuck} with combinations of other stack
                   1374: manipulation words.
                   1375: 
                   1376: @example
                   1377: Given:          How do you get:
                   1378: 1 2 3           3 2 1           
                   1379: 1 2 3           1 2 3 2                 
                   1380: 1 2 3           1 2 3 3                 
                   1381: 1 2 3           1 3 3           
                   1382: 1 2 3           2 1 3           
                   1383: 1 2 3 4         4 3 2 1         
                   1384: 1 2 3           1 2 3 1 2 3             
                   1385: 1 2 3 4         1 2 3 4 1 2             
                   1386: 1 2 3
                   1387: 1 2 3           1 2 3 4                 
                   1388: 1 2 3           1 3             
                   1389: @end example
                   1390: @endassignment
                   1391: 
                   1392: @example
                   1393: 5 dup * .
                   1394: @end example
                   1395: 
                   1396: @assignment
                   1397: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
                   1398: Write a piece of Forth code that expects two numbers on the stack
                   1399: (@var{a} and @var{b}, with @var{b} on top) and computes
                   1400: @code{(a-b)(a+1)}.
                   1401: @endassignment
                   1402: 
1.66      anton    1403: Reference: @ref{Stack Manipulation}.
                   1404: 
                   1405: 
1.48      anton    1406: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
                   1407: @section Using files for Forth code
1.66      anton    1408: @cindex loading Forth code, tutorial
                   1409: @cindex files containing Forth code, tutorial
1.48      anton    1410: 
                   1411: While working at the Forth command line is convenient for one-line
                   1412: examples and short one-off code, you probably want to store your source
                   1413: code in files for convenient editing and persistence.  You can use your
                   1414: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102     anton    1415: Gforth}) to create @var{file.fs} and use
1.48      anton    1416: 
                   1417: @example
1.102     anton    1418: s" @var{file.fs}" included
1.48      anton    1419: @end example
                   1420: 
                   1421: to load it into your Forth system.  The file name extension I use for
                   1422: Forth files is @samp{.fs}.
                   1423: 
                   1424: You can easily start Gforth with some files loaded like this:
                   1425: 
                   1426: @example
1.102     anton    1427: gforth @var{file1.fs} @var{file2.fs}
1.48      anton    1428: @end example
                   1429: 
                   1430: If an error occurs during loading these files, Gforth terminates,
                   1431: whereas an error during @code{INCLUDED} within Gforth usually gives you
                   1432: a Gforth command line.  Starting the Forth system every time gives you a
                   1433: clean start every time, without interference from the results of earlier
                   1434: tries.
                   1435: 
                   1436: I often put all the tests in a file, then load the code and run the
                   1437: tests with
                   1438: 
                   1439: @example
1.102     anton    1440: gforth @var{code.fs} @var{tests.fs} -e bye
1.48      anton    1441: @end example
                   1442: 
                   1443: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
                   1444: @code{-e bye} ensures that Gforth terminates afterwards so that I can
                   1445: restart this command without ado.
                   1446: 
                   1447: The advantage of this approach is that the tests can be repeated easily
                   1448: every time the program ist changed, making it easy to catch bugs
                   1449: introduced by the change.
                   1450: 
1.66      anton    1451: Reference: @ref{Forth source files}.
                   1452: 
1.48      anton    1453: 
                   1454: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
                   1455: @section Comments
1.66      anton    1456: @cindex comments tutorial
1.48      anton    1457: 
                   1458: @example
                   1459: \ That's a comment; it ends at the end of the line
                   1460: ( Another comment; it ends here: )  .s
                   1461: @end example
                   1462: 
                   1463: @code{\} and @code{(} are ordinary Forth words and therefore have to be
                   1464: separated with white space from the following text.
                   1465: 
                   1466: @example
                   1467: \This gives an "Undefined word" error
                   1468: @end example
                   1469: 
                   1470: The first @code{)} ends a comment started with @code{(}, so you cannot
                   1471: nest @code{(}-comments; and you cannot comment out text containing a
                   1472: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
                   1473: avoid @code{)} in word names.}.
                   1474: 
                   1475: I use @code{\}-comments for descriptive text and for commenting out code
                   1476: of one or more line; I use @code{(}-comments for describing the stack
                   1477: effect, the stack contents, or for commenting out sub-line pieces of
                   1478: code.
                   1479: 
                   1480: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
                   1481: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
                   1482: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
                   1483: with @kbd{M-q}.
                   1484: 
1.66      anton    1485: Reference: @ref{Comments}.
                   1486: 
1.48      anton    1487: 
                   1488: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
                   1489: @section Colon Definitions
1.66      anton    1490: @cindex colon definitions, tutorial
                   1491: @cindex definitions, tutorial
                   1492: @cindex procedures, tutorial
                   1493: @cindex functions, tutorial
1.48      anton    1494: 
                   1495: are similar to procedures and functions in other programming languages.
                   1496: 
                   1497: @example
                   1498: : squared ( n -- n^2 )
                   1499:    dup * ;
                   1500: 5 squared .
                   1501: 7 squared .
                   1502: @end example
                   1503: 
                   1504: @code{:} starts the colon definition; its name is @code{squared}.  The
                   1505: following comment describes its stack effect.  The words @code{dup *}
                   1506: are not executed, but compiled into the definition.  @code{;} ends the
                   1507: colon definition.
                   1508: 
                   1509: The newly-defined word can be used like any other word, including using
                   1510: it in other definitions:
                   1511: 
                   1512: @example
                   1513: : cubed ( n -- n^3 )
                   1514:    dup squared * ;
                   1515: -5 cubed .
                   1516: : fourth-power ( n -- n^4 )
                   1517:    squared squared ;
                   1518: 3 fourth-power .
                   1519: @end example
                   1520: 
                   1521: @assignment
                   1522: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
                   1523: @code{/mod} in terms of other Forth words, and check if they work (hint:
                   1524: test your tests on the originals first).  Don't let the
                   1525: @samp{redefined}-Messages spook you, they are just warnings.
                   1526: @endassignment
                   1527: 
1.66      anton    1528: Reference: @ref{Colon Definitions}.
                   1529: 
1.48      anton    1530: 
                   1531: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
                   1532: @section Decompilation
1.66      anton    1533: @cindex decompilation tutorial
                   1534: @cindex see tutorial
1.48      anton    1535: 
                   1536: You can decompile colon definitions with @code{see}:
                   1537: 
                   1538: @example
                   1539: see squared
                   1540: see cubed
                   1541: @end example
                   1542: 
                   1543: In Gforth @code{see} shows you a reconstruction of the source code from
                   1544: the executable code.  Informations that were present in the source, but
                   1545: not in the executable code, are lost (e.g., comments).
                   1546: 
1.65      anton    1547: You can also decompile the predefined words:
                   1548: 
                   1549: @example
                   1550: see .
                   1551: see +
                   1552: @end example
                   1553: 
                   1554: 
1.48      anton    1555: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
                   1556: @section Stack-Effect Comments
1.66      anton    1557: @cindex stack-effect comments, tutorial
                   1558: @cindex --, tutorial
1.48      anton    1559: By convention the comment after the name of a definition describes the
                   1560: stack effect: The part in from of the @samp{--} describes the state of
                   1561: the stack before the execution of the definition, i.e., the parameters
                   1562: that are passed into the colon definition; the part behind the @samp{--}
                   1563: is the state of the stack after the execution of the definition, i.e.,
                   1564: the results of the definition.  The stack comment only shows the top
                   1565: stack items that the definition accesses and/or changes.
                   1566: 
                   1567: You should put a correct stack effect on every definition, even if it is
                   1568: just @code{( -- )}.  You should also add some descriptive comment to
                   1569: more complicated words (I usually do this in the lines following
                   1570: @code{:}).  If you don't do this, your code becomes unreadable (because
1.117     anton    1571: you have to work through every definition before you can understand
1.48      anton    1572: any).
                   1573: 
                   1574: @assignment
                   1575: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
                   1576: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
                   1577: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
1.65      anton    1578: are done, you can compare your stack effects to those in this manual
1.48      anton    1579: (@pxref{Word Index}).
                   1580: @endassignment
                   1581: 
                   1582: Sometimes programmers put comments at various places in colon
                   1583: definitions that describe the contents of the stack at that place (stack
                   1584: comments); i.e., they are like the first part of a stack-effect
                   1585: comment. E.g.,
                   1586: 
                   1587: @example
                   1588: : cubed ( n -- n^3 )
                   1589:    dup squared  ( n n^2 ) * ;
                   1590: @end example
                   1591: 
                   1592: In this case the stack comment is pretty superfluous, because the word
                   1593: is simple enough.  If you think it would be a good idea to add such a
                   1594: comment to increase readability, you should also consider factoring the
                   1595: word into several simpler words (@pxref{Factoring Tutorial,,
1.60      anton    1596: Factoring}), which typically eliminates the need for the stack comment;
1.48      anton    1597: however, if you decide not to refactor it, then having such a comment is
                   1598: better than not having it.
                   1599: 
                   1600: The names of the stack items in stack-effect and stack comments in the
                   1601: standard, in this manual, and in many programs specify the type through
                   1602: a type prefix, similar to Fortran and Hungarian notation.  The most
                   1603: frequent prefixes are:
                   1604: 
                   1605: @table @code
                   1606: @item n
                   1607: signed integer
                   1608: @item u
                   1609: unsigned integer
                   1610: @item c
                   1611: character
                   1612: @item f
                   1613: Boolean flags, i.e. @code{false} or @code{true}.
                   1614: @item a-addr,a-
                   1615: Cell-aligned address
                   1616: @item c-addr,c-
                   1617: Char-aligned address (note that a Char may have two bytes in Windows NT)
                   1618: @item xt
                   1619: Execution token, same size as Cell
                   1620: @item w,x
                   1621: Cell, can contain an integer or an address.  It usually takes 32, 64 or
                   1622: 16 bits (depending on your platform and Forth system). A cell is more
                   1623: commonly known as machine word, but the term @emph{word} already means
                   1624: something different in Forth.
                   1625: @item d
                   1626: signed double-cell integer
                   1627: @item ud
                   1628: unsigned double-cell integer
                   1629: @item r
                   1630: Float (on the FP stack)
                   1631: @end table
                   1632: 
                   1633: You can find a more complete list in @ref{Notation}.
                   1634: 
                   1635: @assignment
                   1636: Write stack-effect comments for all definitions you have written up to
                   1637: now.
                   1638: @endassignment
                   1639: 
                   1640: 
                   1641: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
                   1642: @section Types
1.66      anton    1643: @cindex types tutorial
1.48      anton    1644: 
                   1645: In Forth the names of the operations are not overloaded; so similar
                   1646: operations on different types need different names; e.g., @code{+} adds
                   1647: integers, and you have to use @code{f+} to add floating-point numbers.
                   1648: The following prefixes are often used for related operations on
                   1649: different types:
                   1650: 
                   1651: @table @code
                   1652: @item (none)
                   1653: signed integer
                   1654: @item u
                   1655: unsigned integer
                   1656: @item c
                   1657: character
                   1658: @item d
                   1659: signed double-cell integer
                   1660: @item ud, du
                   1661: unsigned double-cell integer
                   1662: @item 2
                   1663: two cells (not-necessarily double-cell numbers)
                   1664: @item m, um
                   1665: mixed single-cell and double-cell operations
                   1666: @item f
                   1667: floating-point (note that in stack comments @samp{f} represents flags,
1.66      anton    1668: and @samp{r} represents FP numbers).
1.48      anton    1669: @end table
                   1670: 
                   1671: If there are no differences between the signed and the unsigned variant
                   1672: (e.g., for @code{+}), there is only the prefix-less variant.
                   1673: 
                   1674: Forth does not perform type checking, neither at compile time, nor at
                   1675: run time.  If you use the wrong oeration, the data are interpreted
                   1676: incorrectly:
                   1677: 
                   1678: @example
                   1679: -1 u.
                   1680: @end example
                   1681: 
                   1682: If you have only experience with type-checked languages until now, and
                   1683: have heard how important type-checking is, don't panic!  In my
                   1684: experience (and that of other Forthers), type errors in Forth code are
                   1685: usually easy to find (once you get used to it), the increased vigilance
                   1686: of the programmer tends to catch some harder errors in addition to most
                   1687: type errors, and you never have to work around the type system, so in
                   1688: most situations the lack of type-checking seems to be a win (projects to
                   1689: add type checking to Forth have not caught on).
                   1690: 
                   1691: 
                   1692: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
                   1693: @section Factoring
1.66      anton    1694: @cindex factoring tutorial
1.48      anton    1695: 
                   1696: If you try to write longer definitions, you will soon find it hard to
                   1697: keep track of the stack contents.  Therefore, good Forth programmers
                   1698: tend to write only short definitions (e.g., three lines).  The art of
                   1699: finding meaningful short definitions is known as factoring (as in
                   1700: factoring polynomials).
                   1701: 
                   1702: Well-factored programs offer additional advantages: smaller, more
                   1703: general words, are easier to test and debug and can be reused more and
                   1704: better than larger, specialized words.
                   1705: 
                   1706: So, if you run into difficulties with stack management, when writing
                   1707: code, try to define meaningful factors for the word, and define the word
                   1708: in terms of those.  Even if a factor contains only two words, it is
                   1709: often helpful.
                   1710: 
1.65      anton    1711: Good factoring is not easy, and it takes some practice to get the knack
                   1712: for it; but even experienced Forth programmers often don't find the
                   1713: right solution right away, but only when rewriting the program.  So, if
                   1714: you don't come up with a good solution immediately, keep trying, don't
                   1715: despair.
1.48      anton    1716: 
                   1717: @c example !!
                   1718: 
                   1719: 
                   1720: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
                   1721: @section Designing the stack effect
1.66      anton    1722: @cindex Stack effect design, tutorial
                   1723: @cindex design of stack effects, tutorial
1.48      anton    1724: 
                   1725: In other languages you can use an arbitrary order of parameters for a
1.65      anton    1726: function; and since there is only one result, you don't have to deal with
1.48      anton    1727: the order of results, either.
                   1728: 
1.117     anton    1729: In Forth (and other stack-based languages, e.g., PostScript) the
1.48      anton    1730: parameter and result order of a definition is important and should be
                   1731: designed well.  The general guideline is to design the stack effect such
                   1732: that the word is simple to use in most cases, even if that complicates
                   1733: the implementation of the word.  Some concrete rules are:
                   1734: 
                   1735: @itemize @bullet
                   1736: 
                   1737: @item
                   1738: Words consume all of their parameters (e.g., @code{.}).
                   1739: 
                   1740: @item
                   1741: If there is a convention on the order of parameters (e.g., from
                   1742: mathematics or another programming language), stick with it (e.g.,
                   1743: @code{-}).
                   1744: 
                   1745: @item
                   1746: If one parameter usually requires only a short computation (e.g., it is
                   1747: a constant), pass it on the top of the stack.  Conversely, parameters
                   1748: that usually require a long sequence of code to compute should be passed
                   1749: as the bottom (i.e., first) parameter.  This makes the code easier to
                   1750: read, because reader does not need to keep track of the bottom item
                   1751: through a long sequence of code (or, alternatively, through stack
1.49      anton    1752: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48      anton    1753: address on top of the stack because it is usually simpler to compute
                   1754: than the stored value (often the address is just a variable).
                   1755: 
                   1756: @item
                   1757: Similarly, results that are usually consumed quickly should be returned
                   1758: on the top of stack, whereas a result that is often used in long
                   1759: computations should be passed as bottom result.  E.g., the file words
                   1760: like @code{open-file} return the error code on the top of stack, because
                   1761: it is usually consumed quickly by @code{throw}; moreover, the error code
                   1762: has to be checked before doing anything with the other results.
                   1763: 
                   1764: @end itemize
                   1765: 
                   1766: These rules are just general guidelines, don't lose sight of the overall
                   1767: goal to make the words easy to use.  E.g., if the convention rule
                   1768: conflicts with the computation-length rule, you might decide in favour
                   1769: of the convention if the word will be used rarely, and in favour of the
                   1770: computation-length rule if the word will be used frequently (because
                   1771: with frequent use the cost of breaking the computation-length rule would
                   1772: be quite high, and frequent use makes it easier to remember an
                   1773: unconventional order).
                   1774: 
                   1775: @c example !! structure package
                   1776: 
1.65      anton    1777: 
1.48      anton    1778: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
                   1779: @section Local Variables
1.66      anton    1780: @cindex local variables, tutorial
1.48      anton    1781: 
                   1782: You can define local variables (@emph{locals}) in a colon definition:
                   1783: 
                   1784: @example
                   1785: : swap @{ a b -- b a @}
                   1786:   b a ;
                   1787: 1 2 swap .s 2drop
                   1788: @end example
                   1789: 
                   1790: (If your Forth system does not support this syntax, include
                   1791: @file{compat/anslocals.fs} first).
                   1792: 
                   1793: In this example @code{@{ a b -- b a @}} is the locals definition; it
                   1794: takes two cells from the stack, puts the top of stack in @code{b} and
                   1795: the next stack element in @code{a}.  @code{--} starts a comment ending
                   1796: with @code{@}}.  After the locals definition, using the name of the
                   1797: local will push its value on the stack.  You can leave the comment
                   1798: part (@code{-- b a}) away:
                   1799: 
                   1800: @example
                   1801: : swap ( x1 x2 -- x2 x1 )
                   1802:   @{ a b @} b a ;
                   1803: @end example
                   1804: 
                   1805: In Gforth you can have several locals definitions, anywhere in a colon
                   1806: definition; in contrast, in a standard program you can have only one
                   1807: locals definition per colon definition, and that locals definition must
                   1808: be outside any controll structure.
                   1809: 
                   1810: With locals you can write slightly longer definitions without running
                   1811: into stack trouble.  However, I recommend trying to write colon
                   1812: definitions without locals for exercise purposes to help you gain the
                   1813: essential factoring skills.
                   1814: 
                   1815: @assignment
                   1816: Rewrite your definitions until now with locals
                   1817: @endassignment
                   1818: 
1.66      anton    1819: Reference: @ref{Locals}.
                   1820: 
1.48      anton    1821: 
                   1822: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
                   1823: @section Conditional execution
1.66      anton    1824: @cindex conditionals, tutorial
                   1825: @cindex if, tutorial
1.48      anton    1826: 
                   1827: In Forth you can use control structures only inside colon definitions.
                   1828: An @code{if}-structure looks like this:
                   1829: 
                   1830: @example
                   1831: : abs ( n1 -- +n2 )
                   1832:     dup 0 < if
                   1833:         negate
                   1834:     endif ;
                   1835: 5 abs .
                   1836: -5 abs .
                   1837: @end example
                   1838: 
                   1839: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
                   1840: the following code is performed, otherwise execution continues after the
1.51      pazsan   1841: @code{endif} (or @code{else}).  @code{<} compares the top two stack
1.48      anton    1842: elements and prioduces a flag:
                   1843: 
                   1844: @example
                   1845: 1 2 < .
                   1846: 2 1 < .
                   1847: 1 1 < .
                   1848: @end example
                   1849: 
                   1850: Actually the standard name for @code{endif} is @code{then}.  This
                   1851: tutorial presents the examples using @code{endif}, because this is often
                   1852: less confusing for people familiar with other programming languages
                   1853: where @code{then} has a different meaning.  If your system does not have
                   1854: @code{endif}, define it with
                   1855: 
                   1856: @example
                   1857: : endif postpone then ; immediate
                   1858: @end example
                   1859: 
                   1860: You can optionally use an @code{else}-part:
                   1861: 
                   1862: @example
                   1863: : min ( n1 n2 -- n )
                   1864:   2dup < if
                   1865:     drop
                   1866:   else
                   1867:     nip
                   1868:   endif ;
                   1869: 2 3 min .
                   1870: 3 2 min .
                   1871: @end example
                   1872: 
                   1873: @assignment
                   1874: Write @code{min} without @code{else}-part (hint: what's the definition
                   1875: of @code{nip}?).
                   1876: @endassignment
                   1877: 
1.66      anton    1878: Reference: @ref{Selection}.
                   1879: 
1.48      anton    1880: 
                   1881: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
                   1882: @section Flags and Comparisons
1.66      anton    1883: @cindex flags tutorial
                   1884: @cindex comparison tutorial
1.48      anton    1885: 
                   1886: In a false-flag all bits are clear (0 when interpreted as integer).  In
                   1887: a canonical true-flag all bits are set (-1 as a twos-complement signed
                   1888: integer); in many contexts (e.g., @code{if}) any non-zero value is
                   1889: treated as true flag.
                   1890: 
                   1891: @example
                   1892: false .
                   1893: true .
                   1894: true hex u. decimal
                   1895: @end example
                   1896: 
                   1897: Comparison words produce canonical flags:
                   1898: 
                   1899: @example
                   1900: 1 1 = .
                   1901: 1 0= .
                   1902: 0 1 < .
                   1903: 0 0 < .
                   1904: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
                   1905: -1 1 < .
                   1906: @end example
                   1907: 
1.66      anton    1908: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
                   1909: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
                   1910: these combinations are standard (for details see the standard,
                   1911: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48      anton    1912: 
                   1913: You can use @code{and or xor invert} can be used as operations on
                   1914: canonical flags.  Actually they are bitwise operations:
                   1915: 
                   1916: @example
                   1917: 1 2 and .
                   1918: 1 2 or .
                   1919: 1 3 xor .
                   1920: 1 invert .
                   1921: @end example
                   1922: 
                   1923: You can convert a zero/non-zero flag into a canonical flag with
                   1924: @code{0<>} (and complement it on the way with @code{0=}).
                   1925: 
                   1926: @example
                   1927: 1 0= .
                   1928: 1 0<> .
                   1929: @end example
                   1930: 
1.65      anton    1931: You can use the all-bits-set feature of canonical flags and the bitwise
1.48      anton    1932: operation of the Boolean operations to avoid @code{if}s:
                   1933: 
                   1934: @example
                   1935: : foo ( n1 -- n2 )
                   1936:   0= if
                   1937:     14
                   1938:   else
                   1939:     0
                   1940:   endif ;
                   1941: 0 foo .
                   1942: 1 foo .
                   1943: 
                   1944: : foo ( n1 -- n2 )
                   1945:   0= 14 and ;
                   1946: 0 foo .
                   1947: 1 foo .
                   1948: @end example
                   1949: 
                   1950: @assignment
                   1951: Write @code{min} without @code{if}.
                   1952: @endassignment
                   1953: 
1.66      anton    1954: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
                   1955: @ref{Bitwise operations}.
                   1956: 
1.48      anton    1957: 
                   1958: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
                   1959: @section General Loops
1.66      anton    1960: @cindex loops, indefinite, tutorial
1.48      anton    1961: 
                   1962: The endless loop is the most simple one:
                   1963: 
                   1964: @example
                   1965: : endless ( -- )
                   1966:   0 begin
                   1967:     dup . 1+
                   1968:   again ;
                   1969: endless
                   1970: @end example
                   1971: 
                   1972: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
                   1973: does nothing at run-time, @code{again} jumps back to @code{begin}.
                   1974: 
                   1975: A loop with one exit at any place looks like this:
                   1976: 
                   1977: @example
                   1978: : log2 ( +n1 -- n2 )
                   1979: \ logarithmus dualis of n1>0, rounded down to the next integer
                   1980:   assert( dup 0> )
                   1981:   2/ 0 begin
                   1982:     over 0> while
                   1983:       1+ swap 2/ swap
                   1984:   repeat
                   1985:   nip ;
                   1986: 7 log2 .
                   1987: 8 log2 .
                   1988: @end example
                   1989: 
                   1990: At run-time @code{while} consumes a flag; if it is 0, execution
1.51      pazsan   1991: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48      anton    1992: continues behind the @code{while}.  @code{Repeat} jumps back to
                   1993: @code{begin}, just like @code{again}.
                   1994: 
                   1995: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90      anton    1996: However, @code{2/} is not one of them; it shifts its argument right by
1.48      anton    1997: one bit (arithmetic shift right):
                   1998: 
                   1999: @example
                   2000: -5 2 / .
                   2001: -5 2/ .
                   2002: @end example
                   2003: 
                   2004: @code{assert(} is no standard word, but you can get it on systems other
                   2005: then Gforth by including @file{compat/assert.fs}.  You can see what it
                   2006: does by trying
                   2007: 
                   2008: @example
                   2009: 0 log2 .
                   2010: @end example
                   2011: 
                   2012: Here's a loop with an exit at the end:
                   2013: 
                   2014: @example
                   2015: : log2 ( +n1 -- n2 )
                   2016: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2017:   assert( dup 0 > )
                   2018:   -1 begin
                   2019:     1+ swap 2/ swap
                   2020:     over 0 <=
                   2021:   until
                   2022:   nip ;
                   2023: @end example
                   2024: 
                   2025: @code{Until} consumes a flag; if it is non-zero, execution continues at
                   2026: the @code{begin}, otherwise after the @code{until}.
                   2027: 
                   2028: @assignment
                   2029: Write a definition for computing the greatest common divisor.
                   2030: @endassignment
                   2031: 
1.66      anton    2032: Reference: @ref{Simple Loops}.
                   2033: 
1.48      anton    2034: 
                   2035: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
                   2036: @section Counted loops
1.66      anton    2037: @cindex loops, counted, tutorial
1.48      anton    2038: 
                   2039: @example
                   2040: : ^ ( n1 u -- n )
                   2041: \ n = the uth power of u1
                   2042:   1 swap 0 u+do
                   2043:     over *
                   2044:   loop
                   2045:   nip ;
                   2046: 3 2 ^ .
                   2047: 4 3 ^ .
                   2048: @end example
                   2049: 
                   2050: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
                   2051: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
                   2052: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
                   2053: times (or not at all, if @code{u3-u4<0}).
                   2054: 
                   2055: You can see the stack effect design rules at work in the stack effect of
                   2056: the loop start words: Since the start value of the loop is more
                   2057: frequently constant than the end value, the start value is passed on
                   2058: the top-of-stack.
                   2059: 
                   2060: You can access the counter of a counted loop with @code{i}:
                   2061: 
                   2062: @example
                   2063: : fac ( u -- u! )
                   2064:   1 swap 1+ 1 u+do
                   2065:     i *
                   2066:   loop ;
                   2067: 5 fac .
                   2068: 7 fac .
                   2069: @end example
                   2070: 
                   2071: There is also @code{+do}, which expects signed numbers (important for
                   2072: deciding whether to enter the loop).
                   2073: 
                   2074: @assignment
                   2075: Write a definition for computing the nth Fibonacci number.
                   2076: @endassignment
                   2077: 
1.65      anton    2078: You can also use increments other than 1:
                   2079: 
                   2080: @example
                   2081: : up2 ( n1 n2 -- )
                   2082:   +do
                   2083:     i .
                   2084:   2 +loop ;
                   2085: 10 0 up2
                   2086: 
                   2087: : down2 ( n1 n2 -- )
                   2088:   -do
                   2089:     i .
                   2090:   2 -loop ;
                   2091: 0 10 down2
                   2092: @end example
1.48      anton    2093: 
1.66      anton    2094: Reference: @ref{Counted Loops}.
                   2095: 
1.48      anton    2096: 
                   2097: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
                   2098: @section Recursion
1.66      anton    2099: @cindex recursion tutorial
1.48      anton    2100: 
                   2101: Usually the name of a definition is not visible in the definition; but
                   2102: earlier definitions are usually visible:
                   2103: 
                   2104: @example
                   2105: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
                   2106: : / ( n1 n2 -- n )
                   2107:   dup 0= if
                   2108:     -10 throw \ report division by zero
                   2109:   endif
                   2110:   /           \ old version
                   2111: ;
                   2112: 1 0 /
                   2113: @end example
                   2114: 
                   2115: For recursive definitions you can use @code{recursive} (non-standard) or
                   2116: @code{recurse}:
                   2117: 
                   2118: @example
                   2119: : fac1 ( n -- n! ) recursive
                   2120:  dup 0> if
                   2121:    dup 1- fac1 *
                   2122:  else
                   2123:    drop 1
                   2124:  endif ;
                   2125: 7 fac1 .
                   2126: 
                   2127: : fac2 ( n -- n! )
                   2128:  dup 0> if
                   2129:    dup 1- recurse *
                   2130:  else
                   2131:    drop 1
                   2132:  endif ;
                   2133: 8 fac2 .
                   2134: @end example
                   2135: 
                   2136: @assignment
                   2137: Write a recursive definition for computing the nth Fibonacci number.
                   2138: @endassignment
                   2139: 
1.66      anton    2140: Reference (including indirect recursion): @xref{Calls and returns}.
                   2141: 
1.48      anton    2142: 
                   2143: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
                   2144: @section Leaving definitions or loops
1.66      anton    2145: @cindex leaving definitions, tutorial
                   2146: @cindex leaving loops, tutorial
1.48      anton    2147: 
                   2148: @code{EXIT} exits the current definition right away.  For every counted
                   2149: loop that is left in this way, an @code{UNLOOP} has to be performed
                   2150: before the @code{EXIT}:
                   2151: 
                   2152: @c !! real examples
                   2153: @example
                   2154: : ...
                   2155:  ... u+do
                   2156:    ... if
                   2157:      ... unloop exit
                   2158:    endif
                   2159:    ...
                   2160:  loop
                   2161:  ... ;
                   2162: @end example
                   2163: 
                   2164: @code{LEAVE} leaves the innermost counted loop right away:
                   2165: 
                   2166: @example
                   2167: : ...
                   2168:  ... u+do
                   2169:    ... if
                   2170:      ... leave
                   2171:    endif
                   2172:    ...
                   2173:  loop
                   2174:  ... ;
                   2175: @end example
                   2176: 
1.65      anton    2177: @c !! example
1.48      anton    2178: 
1.66      anton    2179: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
                   2180: 
                   2181: 
1.48      anton    2182: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
                   2183: @section Return Stack
1.66      anton    2184: @cindex return stack tutorial
1.48      anton    2185: 
                   2186: In addition to the data stack Forth also has a second stack, the return
                   2187: stack; most Forth systems store the return addresses of procedure calls
                   2188: there (thus its name).  Programmers can also use this stack:
                   2189: 
                   2190: @example
                   2191: : foo ( n1 n2 -- )
                   2192:  .s
                   2193:  >r .s
1.50      anton    2194:  r@@ .
1.48      anton    2195:  >r .s
1.50      anton    2196:  r@@ .
1.48      anton    2197:  r> .
1.50      anton    2198:  r@@ .
1.48      anton    2199:  r> . ;
                   2200: 1 2 foo
                   2201: @end example
                   2202: 
                   2203: @code{>r} takes an element from the data stack and pushes it onto the
                   2204: return stack; conversely, @code{r>} moves an elementm from the return to
                   2205: the data stack; @code{r@@} pushes a copy of the top of the return stack
                   2206: on the return stack.
                   2207: 
                   2208: Forth programmers usually use the return stack for storing data
                   2209: temporarily, if using the data stack alone would be too complex, and
                   2210: factoring and locals are not an option:
                   2211: 
                   2212: @example
                   2213: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
                   2214:  rot >r rot r> ;
                   2215: @end example
                   2216: 
                   2217: The return address of the definition and the loop control parameters of
                   2218: counted loops usually reside on the return stack, so you have to take
                   2219: all items, that you have pushed on the return stack in a colon
                   2220: definition or counted loop, from the return stack before the definition
                   2221: or loop ends.  You cannot access items that you pushed on the return
                   2222: stack outside some definition or loop within the definition of loop.
                   2223: 
                   2224: If you miscount the return stack items, this usually ends in a crash:
                   2225: 
                   2226: @example
                   2227: : crash ( n -- )
                   2228:   >r ;
                   2229: 5 crash
                   2230: @end example
                   2231: 
                   2232: You cannot mix using locals and using the return stack (according to the
                   2233: standard; Gforth has no problem).  However, they solve the same
                   2234: problems, so this shouldn't be an issue.
                   2235: 
                   2236: @assignment
                   2237: Can you rewrite any of the definitions you wrote until now in a better
                   2238: way using the return stack?
                   2239: @endassignment
                   2240: 
1.66      anton    2241: Reference: @ref{Return stack}.
                   2242: 
1.48      anton    2243: 
                   2244: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
                   2245: @section Memory
1.66      anton    2246: @cindex memory access/allocation tutorial
1.48      anton    2247: 
                   2248: You can create a global variable @code{v} with
                   2249: 
                   2250: @example
                   2251: variable v ( -- addr )
                   2252: @end example
                   2253: 
                   2254: @code{v} pushes the address of a cell in memory on the stack.  This cell
                   2255: was reserved by @code{variable}.  You can use @code{!} (store) to store
                   2256: values into this cell and @code{@@} (fetch) to load the value from the
                   2257: stack into memory:
                   2258: 
                   2259: @example
                   2260: v .
                   2261: 5 v ! .s
1.50      anton    2262: v @@ .
1.48      anton    2263: @end example
                   2264: 
1.65      anton    2265: You can see a raw dump of memory with @code{dump}:
                   2266: 
                   2267: @example
                   2268: v 1 cells .s dump
                   2269: @end example
                   2270: 
                   2271: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
                   2272: generally, address units (aus)) that @code{n1 cells} occupy.  You can
                   2273: also reserve more memory:
1.48      anton    2274: 
                   2275: @example
                   2276: create v2 20 cells allot
1.65      anton    2277: v2 20 cells dump
1.48      anton    2278: @end example
                   2279: 
1.65      anton    2280: creates a word @code{v2} and reserves 20 uninitialized cells; the
                   2281: address pushed by @code{v2} points to the start of these 20 cells.  You
                   2282: can use address arithmetic to access these cells:
1.48      anton    2283: 
                   2284: @example
                   2285: 3 v2 5 cells + !
1.65      anton    2286: v2 20 cells dump
1.48      anton    2287: @end example
                   2288: 
                   2289: You can reserve and initialize memory with @code{,}:
                   2290: 
                   2291: @example
                   2292: create v3
                   2293:   5 , 4 , 3 , 2 , 1 ,
1.50      anton    2294: v3 @@ .
                   2295: v3 cell+ @@ .
                   2296: v3 2 cells + @@ .
1.65      anton    2297: v3 5 cells dump
1.48      anton    2298: @end example
                   2299: 
                   2300: @assignment
                   2301: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
                   2302: @code{u} cells, with the first of these cells at @code{addr}, the next
                   2303: one at @code{addr cell+} etc.
                   2304: @endassignment
                   2305: 
                   2306: You can also reserve memory without creating a new word:
                   2307: 
                   2308: @example
1.60      anton    2309: here 10 cells allot .
                   2310: here .
1.48      anton    2311: @end example
                   2312: 
                   2313: @code{Here} pushes the start address of the memory area.  You should
                   2314: store it somewhere, or you will have a hard time finding the memory area
                   2315: again.
                   2316: 
                   2317: @code{Allot} manages dictionary memory.  The dictionary memory contains
                   2318: the system's data structures for words etc. on Gforth and most other
                   2319: Forth systems.  It is managed like a stack: You can free the memory that
                   2320: you have just @code{allot}ed with
                   2321: 
                   2322: @example
                   2323: -10 cells allot
1.60      anton    2324: here .
1.48      anton    2325: @end example
                   2326: 
                   2327: Note that you cannot do this if you have created a new word in the
                   2328: meantime (because then your @code{allot}ed memory is no longer on the
                   2329: top of the dictionary ``stack'').
                   2330: 
                   2331: Alternatively, you can use @code{allocate} and @code{free} which allow
                   2332: freeing memory in any order:
                   2333: 
                   2334: @example
                   2335: 10 cells allocate throw .s
                   2336: 20 cells allocate throw .s
                   2337: swap
                   2338: free throw
                   2339: free throw
                   2340: @end example
                   2341: 
                   2342: The @code{throw}s deal with errors (e.g., out of memory).
                   2343: 
1.65      anton    2344: And there is also a
                   2345: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   2346: garbage collector}, which eliminates the need to @code{free} memory
                   2347: explicitly.
1.48      anton    2348: 
1.66      anton    2349: Reference: @ref{Memory}.
                   2350: 
1.48      anton    2351: 
                   2352: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
                   2353: @section Characters and Strings
1.66      anton    2354: @cindex strings tutorial
                   2355: @cindex characters tutorial
1.48      anton    2356: 
                   2357: On the stack characters take up a cell, like numbers.  In memory they
                   2358: have their own size (one 8-bit byte on most systems), and therefore
                   2359: require their own words for memory access:
                   2360: 
                   2361: @example
                   2362: create v4 
                   2363:   104 c, 97 c, 108 c, 108 c, 111 c,
1.50      anton    2364: v4 4 chars + c@@ .
1.65      anton    2365: v4 5 chars dump
1.48      anton    2366: @end example
                   2367: 
                   2368: The preferred representation of strings on the stack is @code{addr
                   2369: u-count}, where @code{addr} is the address of the first character and
                   2370: @code{u-count} is the number of characters in the string.
                   2371: 
                   2372: @example
                   2373: v4 5 type
                   2374: @end example
                   2375: 
                   2376: You get a string constant with
                   2377: 
                   2378: @example
                   2379: s" hello, world" .s
                   2380: type
                   2381: @end example
                   2382: 
                   2383: Make sure you have a space between @code{s"} and the string; @code{s"}
                   2384: is a normal Forth word and must be delimited with white space (try what
                   2385: happens when you remove the space).
                   2386: 
                   2387: However, this interpretive use of @code{s"} is quite restricted: the
                   2388: string exists only until the next call of @code{s"} (some Forth systems
                   2389: keep more than one of these strings, but usually they still have a
1.62      crook    2390: limited lifetime).
1.48      anton    2391: 
                   2392: @example
                   2393: s" hello," s" world" .s
                   2394: type
                   2395: type
                   2396: @end example
                   2397: 
1.62      crook    2398: You can also use @code{s"} in a definition, and the resulting
                   2399: strings then live forever (well, for as long as the definition):
1.48      anton    2400: 
                   2401: @example
                   2402: : foo s" hello," s" world" ;
                   2403: foo .s
                   2404: type
                   2405: type
                   2406: @end example
                   2407: 
                   2408: @assignment
                   2409: @code{Emit ( c -- )} types @code{c} as character (not a number).
                   2410: Implement @code{type ( addr u -- )}.
                   2411: @endassignment
                   2412: 
1.66      anton    2413: Reference: @ref{Memory Blocks}.
                   2414: 
                   2415: 
1.84      pazsan   2416: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48      anton    2417: @section Alignment
1.66      anton    2418: @cindex alignment tutorial
                   2419: @cindex memory alignment tutorial
1.48      anton    2420: 
                   2421: On many processors cells have to be aligned in memory, if you want to
                   2422: access them with @code{@@} and @code{!} (and even if the processor does
1.62      crook    2423: not require alignment, access to aligned cells is faster).
1.48      anton    2424: 
                   2425: @code{Create} aligns @code{here} (i.e., the place where the next
                   2426: allocation will occur, and that the @code{create}d word points to).
                   2427: Likewise, the memory produced by @code{allocate} starts at an aligned
                   2428: address.  Adding a number of @code{cells} to an aligned address produces
                   2429: another aligned address.
                   2430: 
                   2431: However, address arithmetic involving @code{char+} and @code{chars} can
                   2432: create an address that is not cell-aligned.  @code{Aligned ( addr --
                   2433: a-addr )} produces the next aligned address:
                   2434: 
                   2435: @example
1.50      anton    2436: v3 char+ aligned .s @@ .
                   2437: v3 char+ .s @@ .
1.48      anton    2438: @end example
                   2439: 
                   2440: Similarly, @code{align} advances @code{here} to the next aligned
                   2441: address:
                   2442: 
                   2443: @example
                   2444: create v5 97 c,
                   2445: here .
                   2446: align here .
                   2447: 1000 ,
                   2448: @end example
                   2449: 
                   2450: Note that you should use aligned addresses even if your processor does
                   2451: not require them, if you want your program to be portable.
                   2452: 
1.66      anton    2453: Reference: @ref{Address arithmetic}.
                   2454: 
1.48      anton    2455: 
1.84      pazsan   2456: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
                   2457: @section Files
                   2458: @cindex files tutorial
                   2459: 
                   2460: This section gives a short introduction into how to use files inside
                   2461: Forth. It's broken up into five easy steps:
                   2462: 
                   2463: @enumerate 1
                   2464: @item Opened an ASCII text file for input
                   2465: @item Opened a file for output
                   2466: @item Read input file until string matched (or some other condition matched)
                   2467: @item Wrote some lines from input ( modified or not) to output
                   2468: @item Closed the files.
                   2469: @end enumerate
                   2470: 
                   2471: @subsection Open file for input
                   2472: 
                   2473: @example
                   2474: s" foo.in"  r/o open-file throw Value fd-in
                   2475: @end example
                   2476: 
                   2477: @subsection Create file for output
                   2478: 
                   2479: @example
                   2480: s" foo.out" w/o create-file throw Value fd-out
                   2481: @end example
                   2482: 
                   2483: The available file modes are r/o for read-only access, r/w for
                   2484: read-write access, and w/o for write-only access. You could open both
                   2485: files with r/w, too, if you like. All file words return error codes; for
                   2486: most applications, it's best to pass there error codes with @code{throw}
                   2487: to the outer error handler.
                   2488: 
                   2489: If you want words for opening and assigning, define them as follows:
                   2490: 
                   2491: @example
                   2492: 0 Value fd-in
                   2493: 0 Value fd-out
                   2494: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
                   2495: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
                   2496: @end example
                   2497: 
                   2498: Usage example:
                   2499: 
                   2500: @example
                   2501: s" foo.in" open-input
                   2502: s" foo.out" open-output
                   2503: @end example
                   2504: 
                   2505: @subsection Scan file for a particular line
                   2506: 
                   2507: @example
                   2508: 256 Constant max-line
                   2509: Create line-buffer  max-line 2 + allot
                   2510: 
                   2511: : scan-file ( addr u -- )
                   2512:   begin
                   2513:       line-buffer max-line fd-in read-line throw
                   2514:   while
                   2515:          >r 2dup line-buffer r> compare 0=
                   2516:      until
                   2517:   else
                   2518:      drop
                   2519:   then
                   2520:   2drop ;
                   2521: @end example
                   2522: 
                   2523: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94      anton    2524: the buffer at addr, and returns the number of bytes read, a flag that is
                   2525: false when the end of file is reached, and an error code.
1.84      pazsan   2526: 
                   2527: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
                   2528: returns zero if both strings are equal. It returns a positive number if
                   2529: the first string is lexically greater, a negative if the second string
                   2530: is lexically greater.
                   2531: 
                   2532: We haven't seen this loop here; it has two exits. Since the @code{while}
                   2533: exits with the number of bytes read on the stack, we have to clean up
                   2534: that separately; that's after the @code{else}.
                   2535: 
                   2536: Usage example:
                   2537: 
                   2538: @example
                   2539: s" The text I search is here" scan-file
                   2540: @end example
                   2541: 
                   2542: @subsection Copy input to output
                   2543: 
                   2544: @example
                   2545: : copy-file ( -- )
                   2546:   begin
                   2547:       line-buffer max-line fd-in read-line throw
                   2548:   while
                   2549:       line-buffer swap fd-out write-file throw
                   2550:   repeat ;
                   2551: @end example
                   2552: 
                   2553: @subsection Close files
                   2554: 
                   2555: @example
                   2556: fd-in close-file throw
                   2557: fd-out close-file throw
                   2558: @end example
                   2559: 
                   2560: Likewise, you can put that into definitions, too:
                   2561: 
                   2562: @example
                   2563: : close-input ( -- )  fd-in close-file throw ;
                   2564: : close-output ( -- )  fd-out close-file throw ;
                   2565: @end example
                   2566: 
                   2567: @assignment
                   2568: How could you modify @code{copy-file} so that it copies until a second line is
                   2569: matched? Can you write a program that extracts a section of a text file,
                   2570: given the line that starts and the line that terminates that section?
                   2571: @endassignment
                   2572: 
                   2573: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48      anton    2574: @section Interpretation and Compilation Semantics and Immediacy
1.66      anton    2575: @cindex semantics tutorial
                   2576: @cindex interpretation semantics tutorial
                   2577: @cindex compilation semantics tutorial
                   2578: @cindex immediate, tutorial
1.48      anton    2579: 
                   2580: When a word is compiled, it behaves differently from being interpreted.
                   2581: E.g., consider @code{+}:
                   2582: 
                   2583: @example
                   2584: 1 2 + .
                   2585: : foo + ;
                   2586: @end example
                   2587: 
                   2588: These two behaviours are known as compilation and interpretation
                   2589: semantics.  For normal words (e.g., @code{+}), the compilation semantics
                   2590: is to append the interpretation semantics to the currently defined word
                   2591: (@code{foo} in the example above).  I.e., when @code{foo} is executed
                   2592: later, the interpretation semantics of @code{+} (i.e., adding two
                   2593: numbers) will be performed.
                   2594: 
                   2595: However, there are words with non-default compilation semantics, e.g.,
                   2596: the control-flow words like @code{if}.  You can use @code{immediate} to
                   2597: change the compilation semantics of the last defined word to be equal to
                   2598: the interpretation semantics:
                   2599: 
                   2600: @example
                   2601: : [FOO] ( -- )
                   2602:  5 . ; immediate
                   2603: 
                   2604: [FOO]
                   2605: : bar ( -- )
                   2606:   [FOO] ;
                   2607: bar
                   2608: see bar
                   2609: @end example
                   2610: 
                   2611: Two conventions to mark words with non-default compilation semnatics are
                   2612: names with brackets (more frequently used) and to write them all in
                   2613: upper case (less frequently used).
                   2614: 
                   2615: In Gforth (and many other systems) you can also remove the
                   2616: interpretation semantics with @code{compile-only} (the compilation
                   2617: semantics is derived from the original interpretation semantics):
                   2618: 
                   2619: @example
                   2620: : flip ( -- )
                   2621:  6 . ; compile-only \ but not immediate
                   2622: flip
                   2623: 
                   2624: : flop ( -- )
                   2625:  flip ;
                   2626: flop
                   2627: @end example
                   2628: 
                   2629: In this example the interpretation semantics of @code{flop} is equal to
                   2630: the original interpretation semantics of @code{flip}.
                   2631: 
                   2632: The text interpreter has two states: in interpret state, it performs the
                   2633: interpretation semantics of words it encounters; in compile state, it
                   2634: performs the compilation semantics of these words.
                   2635: 
                   2636: Among other things, @code{:} switches into compile state, and @code{;}
                   2637: switches back to interpret state.  They contain the factors @code{]}
                   2638: (switch to compile state) and @code{[} (switch to interpret state), that
                   2639: do nothing but switch the state.
                   2640: 
                   2641: @example
                   2642: : xxx ( -- )
                   2643:   [ 5 . ]
                   2644: ;
                   2645: 
                   2646: xxx
                   2647: see xxx
                   2648: @end example
                   2649: 
                   2650: These brackets are also the source of the naming convention mentioned
                   2651: above.
                   2652: 
1.66      anton    2653: Reference: @ref{Interpretation and Compilation Semantics}.
                   2654: 
1.48      anton    2655: 
                   2656: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
                   2657: @section Execution Tokens
1.66      anton    2658: @cindex execution tokens tutorial
                   2659: @cindex XT tutorial
1.48      anton    2660: 
                   2661: @code{' word} gives you the execution token (XT) of a word.  The XT is a
                   2662: cell representing the interpretation semantics of a word.  You can
                   2663: execute this semantics with @code{execute}:
                   2664: 
                   2665: @example
                   2666: ' + .s
                   2667: 1 2 rot execute .
                   2668: @end example
                   2669: 
                   2670: The XT is similar to a function pointer in C.  However, parameter
                   2671: passing through the stack makes it a little more flexible:
                   2672: 
                   2673: @example
                   2674: : map-array ( ... addr u xt -- ... )
1.50      anton    2675: \ executes xt ( ... x -- ... ) for every element of the array starting
                   2676: \ at addr and containing u elements
1.48      anton    2677:   @{ xt @}
                   2678:   cells over + swap ?do
1.50      anton    2679:     i @@ xt execute
1.48      anton    2680:   1 cells +loop ;
                   2681: 
                   2682: create a 3 , 4 , 2 , -1 , 4 ,
                   2683: a 5 ' . map-array .s
                   2684: 0 a 5 ' + map-array .
                   2685: s" max-n" environment? drop .s
                   2686: a 5 ' min map-array .
                   2687: @end example
                   2688: 
                   2689: You can use map-array with the XTs of words that consume one element
                   2690: more than they produce.  In theory you can also use it with other XTs,
                   2691: but the stack effect then depends on the size of the array, which is
                   2692: hard to understand.
                   2693: 
1.51      pazsan   2694: Since XTs are cell-sized, you can store them in memory and manipulate
                   2695: them on the stack like other cells.  You can also compile the XT into a
1.48      anton    2696: word with @code{compile,}:
                   2697: 
                   2698: @example
                   2699: : foo1 ( n1 n2 -- n )
                   2700:    [ ' + compile, ] ;
                   2701: see foo
                   2702: @end example
                   2703: 
                   2704: This is non-standard, because @code{compile,} has no compilation
                   2705: semantics in the standard, but it works in good Forth systems.  For the
                   2706: broken ones, use
                   2707: 
                   2708: @example
                   2709: : [compile,] compile, ; immediate
                   2710: 
                   2711: : foo1 ( n1 n2 -- n )
                   2712:    [ ' + ] [compile,] ;
                   2713: see foo
                   2714: @end example
                   2715: 
                   2716: @code{'} is a word with default compilation semantics; it parses the
                   2717: next word when its interpretation semantics are executed, not during
                   2718: compilation:
                   2719: 
                   2720: @example
                   2721: : foo ( -- xt )
                   2722:   ' ;
                   2723: see foo
                   2724: : bar ( ... "word" -- ... )
                   2725:   ' execute ;
                   2726: see bar
1.60      anton    2727: 1 2 bar + .
1.48      anton    2728: @end example
                   2729: 
                   2730: You often want to parse a word during compilation and compile its XT so
                   2731: it will be pushed on the stack at run-time.  @code{[']} does this:
                   2732: 
                   2733: @example
                   2734: : xt-+ ( -- xt )
                   2735:   ['] + ;
                   2736: see xt-+
                   2737: 1 2 xt-+ execute .
                   2738: @end example
                   2739: 
                   2740: Many programmers tend to see @code{'} and the word it parses as one
                   2741: unit, and expect it to behave like @code{[']} when compiled, and are
                   2742: confused by the actual behaviour.  If you are, just remember that the
                   2743: Forth system just takes @code{'} as one unit and has no idea that it is
                   2744: a parsing word (attempts to convenience programmers in this issue have
                   2745: usually resulted in even worse pitfalls, see
1.66      anton    2746: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
                   2747: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48      anton    2748: 
                   2749: Note that the state of the interpreter does not come into play when
1.51      pazsan   2750: creating and executing XTs.  I.e., even when you execute @code{'} in
1.48      anton    2751: compile state, it still gives you the interpretation semantics.  And
                   2752: whatever that state is, @code{execute} performs the semantics
1.66      anton    2753: represented by the XT (i.e., for XTs produced with @code{'} the
                   2754: interpretation semantics).
                   2755: 
                   2756: Reference: @ref{Tokens for Words}.
1.48      anton    2757: 
                   2758: 
                   2759: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
                   2760: @section Exceptions
1.66      anton    2761: @cindex exceptions tutorial
1.48      anton    2762: 
                   2763: @code{throw ( n -- )} causes an exception unless n is zero.
                   2764: 
                   2765: @example
                   2766: 100 throw .s
                   2767: 0 throw .s
                   2768: @end example
                   2769: 
                   2770: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
                   2771: it catches exceptions and pushes the number of the exception on the
                   2772: stack (or 0, if the xt executed without exception).  If there was an
                   2773: exception, the stacks have the same depth as when entering @code{catch}:
                   2774: 
                   2775: @example
                   2776: .s
                   2777: 3 0 ' / catch .s
                   2778: 3 2 ' / catch .s
                   2779: @end example
                   2780: 
                   2781: @assignment
                   2782: Try the same with @code{execute} instead of @code{catch}.
                   2783: @endassignment
                   2784: 
                   2785: @code{Throw} always jumps to the dynamically next enclosing
                   2786: @code{catch}, even if it has to leave several call levels to achieve
                   2787: this:
                   2788: 
                   2789: @example
                   2790: : foo 100 throw ;
                   2791: : foo1 foo ." after foo" ;
1.51      pazsan   2792: : bar ['] foo1 catch ;
1.60      anton    2793: bar .
1.48      anton    2794: @end example
                   2795: 
                   2796: It is often important to restore a value upon leaving a definition, even
                   2797: if the definition is left through an exception.  You can ensure this
                   2798: like this:
                   2799: 
                   2800: @example
                   2801: : ...
                   2802:    save-x
1.51      pazsan   2803:    ['] word-changing-x catch ( ... n )
1.48      anton    2804:    restore-x
                   2805:    ( ... n ) throw ;
                   2806: @end example
                   2807: 
1.55      anton    2808: Gforth provides an alternative syntax in addition to @code{catch}:
1.48      anton    2809: @code{try ... recover ... endtry}.  If the code between @code{try} and
                   2810: @code{recover} has an exception, the stack depths are restored, the
                   2811: exception number is pushed on the stack, and the code between
                   2812: @code{recover} and @code{endtry} is performed.  E.g., the definition for
                   2813: @code{catch} is
                   2814: 
                   2815: @example
                   2816: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
                   2817:   try
                   2818:     execute 0
                   2819:   recover
                   2820:     nip
                   2821:   endtry ;
                   2822: @end example
                   2823: 
                   2824: The equivalent to the restoration code above is
                   2825: 
                   2826: @example
                   2827: : ...
                   2828:   save-x
                   2829:   try
1.92      anton    2830:     word-changing-x 0
                   2831:   recover endtry
1.48      anton    2832:   restore-x
                   2833:   throw ;
                   2834: @end example
                   2835: 
1.92      anton    2836: This works if @code{word-changing-x} does not change the stack depth,
                   2837: otherwise you should add some code between @code{recover} and
                   2838: @code{endtry} to balance the stack.
1.48      anton    2839: 
1.66      anton    2840: Reference: @ref{Exception Handling}.
                   2841: 
1.48      anton    2842: 
                   2843: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
                   2844: @section Defining Words
1.66      anton    2845: @cindex defining words tutorial
                   2846: @cindex does> tutorial
                   2847: @cindex create...does> tutorial
                   2848: 
                   2849: @c before semantics?
1.48      anton    2850: 
                   2851: @code{:}, @code{create}, and @code{variable} are definition words: They
                   2852: define other words.  @code{Constant} is another definition word:
                   2853: 
                   2854: @example
                   2855: 5 constant foo
                   2856: foo .
                   2857: @end example
                   2858: 
                   2859: You can also use the prefixes @code{2} (double-cell) and @code{f}
                   2860: (floating point) with @code{variable} and @code{constant}.
                   2861: 
                   2862: You can also define your own defining words.  E.g.:
                   2863: 
                   2864: @example
                   2865: : variable ( "name" -- )
                   2866:   create 0 , ;
                   2867: @end example
                   2868: 
                   2869: You can also define defining words that create words that do something
                   2870: other than just producing their address:
                   2871: 
                   2872: @example
                   2873: : constant ( n "name" -- )
                   2874:   create ,
                   2875: does> ( -- n )
1.50      anton    2876:   ( addr ) @@ ;
1.48      anton    2877: 
                   2878: 5 constant foo
                   2879: foo .
                   2880: @end example
                   2881: 
                   2882: The definition of @code{constant} above ends at the @code{does>}; i.e.,
                   2883: @code{does>} replaces @code{;}, but it also does something else: It
                   2884: changes the last defined word such that it pushes the address of the
                   2885: body of the word and then performs the code after the @code{does>}
                   2886: whenever it is called.
                   2887: 
                   2888: In the example above, @code{constant} uses @code{,} to store 5 into the
                   2889: body of @code{foo}.  When @code{foo} executes, it pushes the address of
                   2890: the body onto the stack, then (in the code after the @code{does>})
                   2891: fetches the 5 from there.
                   2892: 
                   2893: The stack comment near the @code{does>} reflects the stack effect of the
                   2894: defined word, not the stack effect of the code after the @code{does>}
                   2895: (the difference is that the code expects the address of the body that
                   2896: the stack comment does not show).
                   2897: 
                   2898: You can use these definition words to do factoring in cases that involve
                   2899: (other) definition words.  E.g., a field offset is always added to an
                   2900: address.  Instead of defining
                   2901: 
                   2902: @example
                   2903: 2 cells constant offset-field1
                   2904: @end example
                   2905: 
                   2906: and using this like
                   2907: 
                   2908: @example
                   2909: ( addr ) offset-field1 +
                   2910: @end example
                   2911: 
                   2912: you can define a definition word
                   2913: 
                   2914: @example
                   2915: : simple-field ( n "name" -- )
                   2916:   create ,
                   2917: does> ( n1 -- n1+n )
1.50      anton    2918:   ( addr ) @@ + ;
1.48      anton    2919: @end example
1.21      crook    2920: 
1.48      anton    2921: Definition and use of field offsets now look like this:
1.21      crook    2922: 
1.48      anton    2923: @example
                   2924: 2 cells simple-field field1
1.60      anton    2925: create mystruct 4 cells allot
                   2926: mystruct .s field1 .s drop
1.48      anton    2927: @end example
1.21      crook    2928: 
1.48      anton    2929: If you want to do something with the word without performing the code
                   2930: after the @code{does>}, you can access the body of a @code{create}d word
                   2931: with @code{>body ( xt -- addr )}:
1.21      crook    2932: 
1.48      anton    2933: @example
                   2934: : value ( n "name" -- )
                   2935:   create ,
                   2936: does> ( -- n1 )
1.50      anton    2937:   @@ ;
1.48      anton    2938: : to ( n "name" -- )
                   2939:   ' >body ! ;
1.21      crook    2940: 
1.48      anton    2941: 5 value foo
                   2942: foo .
                   2943: 7 to foo
                   2944: foo .
                   2945: @end example
1.21      crook    2946: 
1.48      anton    2947: @assignment
                   2948: Define @code{defer ( "name" -- )}, which creates a word that stores an
                   2949: XT (at the start the XT of @code{abort}), and upon execution
                   2950: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
                   2951: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
                   2952: recursion is one application of @code{defer}.
                   2953: @endassignment
1.29      crook    2954: 
1.66      anton    2955: Reference: @ref{User-defined Defining Words}.
                   2956: 
                   2957: 
1.48      anton    2958: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
                   2959: @section Arrays and Records
1.66      anton    2960: @cindex arrays tutorial
                   2961: @cindex records tutorial
                   2962: @cindex structs tutorial
1.29      crook    2963: 
1.48      anton    2964: Forth has no standard words for defining data structures such as arrays
                   2965: and records (structs in C terminology), but you can build them yourself
                   2966: based on address arithmetic.  You can also define words for defining
                   2967: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29      crook    2968: 
1.48      anton    2969: One of the first projects a Forth newcomer sets out upon when learning
                   2970: about defining words is an array defining word (possibly for
                   2971: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
                   2972: learn something from it.  However, don't be disappointed when you later
                   2973: learn that you have little use for these words (inappropriate use would
                   2974: be even worse).  I have not yet found a set of useful array words yet;
                   2975: the needs are just too diverse, and named, global arrays (the result of
                   2976: naive use of defining words) are often not flexible enough (e.g.,
1.66      anton    2977: consider how to pass them as parameters).  Another such project is a set
                   2978: of words to help dealing with strings.
1.29      crook    2979: 
1.48      anton    2980: On the other hand, there is a useful set of record words, and it has
                   2981: been defined in @file{compat/struct.fs}; these words are predefined in
                   2982: Gforth.  They are explained in depth elsewhere in this manual (see
                   2983: @pxref{Structures}).  The @code{simple-field} example above is
                   2984: simplified variant of fields in this package.
1.21      crook    2985: 
                   2986: 
1.48      anton    2987: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
                   2988: @section @code{POSTPONE}
1.66      anton    2989: @cindex postpone tutorial
1.21      crook    2990: 
1.48      anton    2991: You can compile the compilation semantics (instead of compiling the
                   2992: interpretation semantics) of a word with @code{POSTPONE}:
1.21      crook    2993: 
1.48      anton    2994: @example
                   2995: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51      pazsan   2996:  POSTPONE + ; immediate
1.48      anton    2997: : foo ( n1 n2 -- n )
                   2998:  MY-+ ;
                   2999: 1 2 foo .
                   3000: see foo
                   3001: @end example
1.21      crook    3002: 
1.48      anton    3003: During the definition of @code{foo} the text interpreter performs the
                   3004: compilation semantics of @code{MY-+}, which performs the compilation
                   3005: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
                   3006: 
                   3007: This example also displays separate stack comments for the compilation
                   3008: semantics and for the stack effect of the compiled code.  For words with
                   3009: default compilation semantics these stack effects are usually not
                   3010: displayed; the stack effect of the compilation semantics is always
                   3011: @code{( -- )} for these words, the stack effect for the compiled code is
                   3012: the stack effect of the interpretation semantics.
                   3013: 
                   3014: Note that the state of the interpreter does not come into play when
                   3015: performing the compilation semantics in this way.  You can also perform
                   3016: it interpretively, e.g.:
                   3017: 
                   3018: @example
                   3019: : foo2 ( n1 n2 -- n )
                   3020:  [ MY-+ ] ;
                   3021: 1 2 foo .
                   3022: see foo
                   3023: @end example
1.21      crook    3024: 
1.48      anton    3025: However, there are some broken Forth systems where this does not always
1.62      crook    3026: work, and therefore this practice was been declared non-standard in
1.48      anton    3027: 1999.
                   3028: @c !! repair.fs
                   3029: 
                   3030: Here is another example for using @code{POSTPONE}:
1.44      crook    3031: 
1.48      anton    3032: @example
                   3033: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
                   3034:  POSTPONE negate POSTPONE + ; immediate compile-only
                   3035: : bar ( n1 n2 -- n )
                   3036:   MY-- ;
                   3037: 2 1 bar .
                   3038: see bar
                   3039: @end example
1.21      crook    3040: 
1.48      anton    3041: You can define @code{ENDIF} in this way:
1.21      crook    3042: 
1.48      anton    3043: @example
                   3044: : ENDIF ( Compilation: orig -- )
                   3045:   POSTPONE then ; immediate
                   3046: @end example
1.21      crook    3047: 
1.48      anton    3048: @assignment
                   3049: Write @code{MY-2DUP} that has compilation semantics equivalent to
                   3050: @code{2dup}, but compiles @code{over over}.
                   3051: @endassignment
1.29      crook    3052: 
1.66      anton    3053: @c !! @xref{Macros} for reference
                   3054: 
                   3055: 
1.48      anton    3056: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
                   3057: @section @code{Literal}
1.66      anton    3058: @cindex literal tutorial
1.29      crook    3059: 
1.48      anton    3060: You cannot @code{POSTPONE} numbers:
1.21      crook    3061: 
1.48      anton    3062: @example
                   3063: : [FOO] POSTPONE 500 ; immediate
1.21      crook    3064: @end example
                   3065: 
1.48      anton    3066: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29      crook    3067: 
1.48      anton    3068: @example
                   3069: : [FOO] ( compilation: --; run-time: -- n )
                   3070:   500 POSTPONE literal ; immediate
1.29      crook    3071: 
1.60      anton    3072: : flip [FOO] ;
1.48      anton    3073: flip .
                   3074: see flip
                   3075: @end example
1.29      crook    3076: 
1.48      anton    3077: @code{LITERAL} consumes a number at compile-time (when it's compilation
                   3078: semantics are executed) and pushes it at run-time (when the code it
                   3079: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
                   3080: number computed at compile time into the current word:
1.29      crook    3081: 
1.48      anton    3082: @example
                   3083: : bar ( -- n )
                   3084:   [ 2 2 + ] literal ;
                   3085: see bar
                   3086: @end example
1.29      crook    3087: 
1.48      anton    3088: @assignment
                   3089: Write @code{]L} which allows writing the example above as @code{: bar (
                   3090: -- n ) [ 2 2 + ]L ;}
                   3091: @endassignment
                   3092: 
1.66      anton    3093: @c !! @xref{Macros} for reference
                   3094: 
1.48      anton    3095: 
                   3096: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
                   3097: @section Advanced macros
1.66      anton    3098: @cindex macros, advanced tutorial
                   3099: @cindex run-time code generation, tutorial
1.48      anton    3100: 
1.66      anton    3101: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
                   3102: Execution Tokens}.  It frequently performs @code{execute}, a relatively
                   3103: expensive operation in some Forth implementations.  You can use
1.48      anton    3104: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
                   3105: and produce a word that contains the word to be performed directly:
                   3106: 
                   3107: @c use ]] ... [[
                   3108: @example
                   3109: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
                   3110: \ at run-time, execute xt ( ... x -- ... ) for each element of the
                   3111: \ array beginning at addr and containing u elements
                   3112:   @{ xt @}
                   3113:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50      anton    3114:     POSTPONE i POSTPONE @@ xt compile,
1.48      anton    3115:   1 cells POSTPONE literal POSTPONE +loop ;
                   3116: 
                   3117: : sum-array ( addr u -- n )
                   3118:  0 rot rot [ ' + compile-map-array ] ;
                   3119: see sum-array
                   3120: a 5 sum-array .
                   3121: @end example
                   3122: 
                   3123: You can use the full power of Forth for generating the code; here's an
                   3124: example where the code is generated in a loop:
                   3125: 
                   3126: @example
                   3127: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
                   3128: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50      anton    3129:   POSTPONE tuck POSTPONE @@
1.48      anton    3130:   POSTPONE literal POSTPONE * POSTPONE +
                   3131:   POSTPONE swap POSTPONE cell+ ;
                   3132: 
                   3133: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51      pazsan   3134: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48      anton    3135:   0 postpone literal postpone swap
                   3136:   [ ' compile-vmul-step compile-map-array ]
                   3137:   postpone drop ;
                   3138: see compile-vmul
                   3139: 
                   3140: : a-vmul ( addr -- n )
1.51      pazsan   3141: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48      anton    3142:  [ a 5 compile-vmul ] ;
                   3143: see a-vmul
                   3144: a a-vmul .
                   3145: @end example
                   3146: 
                   3147: This example uses @code{compile-map-array} to show off, but you could
1.66      anton    3148: also use @code{map-array} instead (try it now!).
1.48      anton    3149: 
                   3150: You can use this technique for efficient multiplication of large
                   3151: matrices.  In matrix multiplication, you multiply every line of one
                   3152: matrix with every column of the other matrix.  You can generate the code
                   3153: for one line once, and use it for every column.  The only downside of
                   3154: this technique is that it is cumbersome to recover the memory consumed
                   3155: by the generated code when you are done (and in more complicated cases
                   3156: it is not possible portably).
                   3157: 
1.66      anton    3158: @c !! @xref{Macros} for reference
                   3159: 
                   3160: 
1.48      anton    3161: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
                   3162: @section Compilation Tokens
1.66      anton    3163: @cindex compilation tokens, tutorial
                   3164: @cindex CT, tutorial
1.48      anton    3165: 
                   3166: This section is Gforth-specific.  You can skip it.
                   3167: 
                   3168: @code{' word compile,} compiles the interpretation semantics.  For words
                   3169: with default compilation semantics this is the same as performing the
                   3170: compilation semantics.  To represent the compilation semantics of other
                   3171: words (e.g., words like @code{if} that have no interpretation
                   3172: semantics), Gforth has the concept of a compilation token (CT,
                   3173: consisting of two cells), and words @code{comp'} and @code{[comp']}.
                   3174: You can perform the compilation semantics represented by a CT with
                   3175: @code{execute}:
1.29      crook    3176: 
1.48      anton    3177: @example
                   3178: : foo2 ( n1 n2 -- n )
                   3179:    [ comp' + execute ] ;
                   3180: see foo
                   3181: @end example
1.29      crook    3182: 
1.48      anton    3183: You can compile the compilation semantics represented by a CT with
                   3184: @code{postpone,}:
1.30      anton    3185: 
1.48      anton    3186: @example
                   3187: : foo3 ( -- )
                   3188:   [ comp' + postpone, ] ;
                   3189: see foo3
                   3190: @end example
1.30      anton    3191: 
1.51      pazsan   3192: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48      anton    3193: @code{comp'} is particularly useful for words that have no
                   3194: interpretation semantics:
1.29      crook    3195: 
1.30      anton    3196: @example
1.48      anton    3197: ' if
1.60      anton    3198: comp' if .s 2drop
1.30      anton    3199: @end example
                   3200: 
1.66      anton    3201: Reference: @ref{Tokens for Words}.
                   3202: 
1.29      crook    3203: 
1.48      anton    3204: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
                   3205: @section Wordlists and Search Order
1.66      anton    3206: @cindex wordlists tutorial
                   3207: @cindex search order, tutorial
1.48      anton    3208: 
                   3209: The dictionary is not just a memory area that allows you to allocate
                   3210: memory with @code{allot}, it also contains the Forth words, arranged in
                   3211: several wordlists.  When searching for a word in a wordlist,
                   3212: conceptually you start searching at the youngest and proceed towards
                   3213: older words (in reality most systems nowadays use hash-tables); i.e., if
                   3214: you define a word with the same name as an older word, the new word
                   3215: shadows the older word.
                   3216: 
                   3217: Which wordlists are searched in which order is determined by the search
                   3218: order.  You can display the search order with @code{order}.  It displays
                   3219: first the search order, starting with the wordlist searched first, then
                   3220: it displays the wordlist that will contain newly defined words.
1.21      crook    3221: 
1.48      anton    3222: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21      crook    3223: 
1.48      anton    3224: @example
                   3225: wordlist constant mywords
                   3226: @end example
1.21      crook    3227: 
1.48      anton    3228: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
                   3229: defined words (the @emph{current} wordlist):
1.21      crook    3230: 
1.48      anton    3231: @example
                   3232: mywords set-current
                   3233: order
                   3234: @end example
1.26      crook    3235: 
1.48      anton    3236: Gforth does not display a name for the wordlist in @code{mywords}
                   3237: because this wordlist was created anonymously with @code{wordlist}.
1.21      crook    3238: 
1.48      anton    3239: You can get the current wordlist with @code{get-current ( -- wid)}.  If
                   3240: you want to put something into a specific wordlist without overall
                   3241: effect on the current wordlist, this typically looks like this:
1.21      crook    3242: 
1.48      anton    3243: @example
                   3244: get-current mywords set-current ( wid )
                   3245: create someword
                   3246: ( wid ) set-current
                   3247: @end example
1.21      crook    3248: 
1.48      anton    3249: You can write the search order with @code{set-order ( wid1 .. widn n --
                   3250: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
                   3251: searched wordlist is topmost.
1.21      crook    3252: 
1.48      anton    3253: @example
                   3254: get-order mywords swap 1+ set-order
                   3255: order
                   3256: @end example
1.21      crook    3257: 
1.48      anton    3258: Yes, the order of wordlists in the output of @code{order} is reversed
                   3259: from stack comments and the output of @code{.s} and thus unintuitive.
1.21      crook    3260: 
1.48      anton    3261: @assignment
                   3262: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
                   3263: wordlist to the search order.  Define @code{previous ( -- )}, which
                   3264: removes the first searched wordlist from the search order.  Experiment
                   3265: with boundary conditions (you will see some crashes or situations that
                   3266: are hard or impossible to leave).
                   3267: @endassignment
1.21      crook    3268: 
1.48      anton    3269: The search order is a powerful foundation for providing features similar
                   3270: to Modula-2 modules and C++ namespaces.  However, trying to modularize
                   3271: programs in this way has disadvantages for debugging and reuse/factoring
                   3272: that overcome the advantages in my experience (I don't do huge projects,
1.55      anton    3273: though).  These disadvantages are not so clear in other
1.82      anton    3274: languages/programming environments, because these languages are not so
1.48      anton    3275: strong in debugging and reuse.
1.21      crook    3276: 
1.66      anton    3277: @c !! example
                   3278: 
                   3279: Reference: @ref{Word Lists}.
1.21      crook    3280: 
1.29      crook    3281: @c ******************************************************************
1.48      anton    3282: @node Introduction, Words, Tutorial, Top
1.29      crook    3283: @comment node-name,     next,           previous, up
                   3284: @chapter An Introduction to ANS Forth
                   3285: @cindex Forth - an introduction
1.21      crook    3286: 
1.83      anton    3287: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
                   3288: that it is slower-paced in its examples, but uses them to dive deep into
                   3289: explaining Forth internals (not covered by the Tutorial).  Apart from
                   3290: that, this chapter covers far less material.  It is suitable for reading
                   3291: without using a computer.
                   3292: 
1.29      crook    3293: The primary purpose of this manual is to document Gforth. However, since
                   3294: Forth is not a widely-known language and there is a lack of up-to-date
                   3295: teaching material, it seems worthwhile to provide some introductory
1.49      anton    3296: material.  For other sources of Forth-related
                   3297: information, see @ref{Forth-related information}.
1.21      crook    3298: 
1.29      crook    3299: The examples in this section should work on any ANS Forth; the
                   3300: output shown was produced using Gforth. Each example attempts to
                   3301: reproduce the exact output that Gforth produces. If you try out the
                   3302: examples (and you should), what you should type is shown @kbd{like this}
                   3303: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    3304: that, where the example shows @key{RET} it means that you should
1.29      crook    3305: press the ``carriage return'' key. Unfortunately, some output formats for
                   3306: this manual cannot show the difference between @kbd{this} and
                   3307: @code{this} which will make trying out the examples harder (but not
                   3308: impossible).
1.21      crook    3309: 
1.29      crook    3310: Forth is an unusual language. It provides an interactive development
                   3311: environment which includes both an interpreter and compiler. Forth
                   3312: programming style encourages you to break a problem down into many
                   3313: @cindex factoring
                   3314: small fragments (@dfn{factoring}), and then to develop and test each
                   3315: fragment interactively. Forth advocates assert that breaking the
                   3316: edit-compile-test cycle used by conventional programming languages can
                   3317: lead to great productivity improvements.
1.21      crook    3318: 
1.29      crook    3319: @menu
1.67      anton    3320: * Introducing the Text Interpreter::  
                   3321: * Stacks and Postfix notation::  
                   3322: * Your first definition::       
                   3323: * How does that work?::         
                   3324: * Forth is written in Forth::   
                   3325: * Review - elements of a Forth system::  
                   3326: * Where to go next::            
                   3327: * Exercises::                   
1.29      crook    3328: @end menu
1.21      crook    3329: 
1.29      crook    3330: @comment ----------------------------------------------
                   3331: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   3332: @section Introducing the Text Interpreter
                   3333: @cindex text interpreter
                   3334: @cindex outer interpreter
1.21      crook    3335: 
1.30      anton    3336: @c IMO this is too detailed and the pace is too slow for
                   3337: @c an introduction.  If you know German, take a look at
                   3338: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   3339: @c to see how I do it - anton 
                   3340: 
1.44      crook    3341: @c nac-> Where I have accepted your comments 100% and modified the text
                   3342: @c accordingly, I have deleted your comments. Elsewhere I have added a
                   3343: @c response like this to attempt to rationalise what I have done. Of
                   3344: @c course, this is a very clumsy mechanism for something that would be
                   3345: @c done far more efficiently over a beer. Please delete any dialogue
                   3346: @c you consider closed.
                   3347: 
1.29      crook    3348: When you invoke the Forth image, you will see a startup banner printed
                   3349: and nothing else (if you have Gforth installed on your system, try
1.30      anton    3350: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    3351: its command line interpreter, which is called the @dfn{Text Interpreter}
                   3352: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.49      anton    3353: about the text interpreter as you read through this chapter, for more
                   3354: detail @pxref{The Text Interpreter}).
1.21      crook    3355: 
1.29      crook    3356: Although it's not obvious, Forth is actually waiting for your
1.30      anton    3357: input. Type a number and press the @key{RET} key:
1.21      crook    3358: 
1.26      crook    3359: @example
1.30      anton    3360: @kbd{45@key{RET}}  ok
1.26      crook    3361: @end example
1.21      crook    3362: 
1.29      crook    3363: Rather than give you a prompt to invite you to input something, the text
                   3364: interpreter prints a status message @i{after} it has processed a line
                   3365: of input. The status message in this case (``@code{ ok}'' followed by
                   3366: carriage-return) indicates that the text interpreter was able to process
                   3367: all of your input successfully. Now type something illegal:
                   3368: 
                   3369: @example
1.30      anton    3370: @kbd{qwer341@key{RET}}
1.29      crook    3371: :1: Undefined word
                   3372: qwer341
                   3373: ^^^^^^^
                   3374: $400D2BA8 Bounce
                   3375: $400DBDA8 no.extensions
                   3376: @end example
1.23      crook    3377: 
1.29      crook    3378: The exact text, other than the ``Undefined word'' may differ slightly on
                   3379: your system, but the effect is the same; when the text interpreter
                   3380: detects an error, it discards any remaining text on a line, resets
1.49      anton    3381: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
                   3382: messages}.
1.23      crook    3383: 
1.29      crook    3384: The text interpreter waits for you to press carriage-return, and then
                   3385: processes your input line. Starting at the beginning of the line, it
                   3386: breaks the line into groups of characters separated by spaces. For each
                   3387: group of characters in turn, it makes two attempts to do something:
1.23      crook    3388: 
1.29      crook    3389: @itemize @bullet
                   3390: @item
1.44      crook    3391: @cindex name dictionary
1.29      crook    3392: It tries to treat it as a command. It does this by searching a @dfn{name
                   3393: dictionary}. If the group of characters matches an entry in the name
                   3394: dictionary, the name dictionary provides the text interpreter with
                   3395: information that allows the text interpreter perform some actions. In
                   3396: Forth jargon, we say that the group
                   3397: @cindex word
                   3398: @cindex definition
                   3399: @cindex execution token
                   3400: @cindex xt
                   3401: of characters names a @dfn{word}, that the dictionary search returns an
                   3402: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   3403: word, and that the text interpreter executes the xt. Often, the terms
                   3404: @dfn{word} and @dfn{definition} are used interchangeably.
                   3405: @item
                   3406: If the text interpreter fails to find a match in the name dictionary, it
                   3407: tries to treat the group of characters as a number in the current number
                   3408: base (when you start up Forth, the current number base is base 10). If
                   3409: the group of characters legitimately represents a number, the text
                   3410: interpreter pushes the number onto a stack (we'll learn more about that
                   3411: in the next section).
                   3412: @end itemize
1.23      crook    3413: 
1.29      crook    3414: If the text interpreter is unable to do either of these things with any
                   3415: group of characters, it discards the group of characters and the rest of
                   3416: the line, then prints an error message. If the text interpreter reaches
                   3417: the end of the line without error, it prints the status message ``@code{ ok}''
                   3418: followed by carriage-return.
1.21      crook    3419: 
1.29      crook    3420: This is the simplest command we can give to the text interpreter:
1.23      crook    3421: 
                   3422: @example
1.30      anton    3423: @key{RET}  ok
1.23      crook    3424: @end example
1.21      crook    3425: 
1.29      crook    3426: The text interpreter did everything we asked it to do (nothing) without
                   3427: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   3428: command:
1.21      crook    3429: 
1.23      crook    3430: @example
1.30      anton    3431: @kbd{12 dup fred dup@key{RET}}
1.29      crook    3432: :1: Undefined word
                   3433: 12 dup fred dup
                   3434:        ^^^^
                   3435: $400D2BA8 Bounce
                   3436: $400DBDA8 no.extensions
1.23      crook    3437: @end example
1.21      crook    3438: 
1.29      crook    3439: When you press the carriage-return key, the text interpreter starts to
                   3440: work its way along the line:
1.21      crook    3441: 
1.29      crook    3442: @itemize @bullet
                   3443: @item
                   3444: When it gets to the space after the @code{2}, it takes the group of
                   3445: characters @code{12} and looks them up in the name
                   3446: dictionary@footnote{We can't tell if it found them or not, but assume
                   3447: for now that it did not}. There is no match for this group of characters
                   3448: in the name dictionary, so it tries to treat them as a number. It is
                   3449: able to do this successfully, so it puts the number, 12, ``on the stack''
                   3450: (whatever that means).
                   3451: @item
                   3452: The text interpreter resumes scanning the line and gets the next group
                   3453: of characters, @code{dup}. It looks it up in the name dictionary and
                   3454: (you'll have to take my word for this) finds it, and executes the word
                   3455: @code{dup} (whatever that means).
                   3456: @item
                   3457: Once again, the text interpreter resumes scanning the line and gets the
                   3458: group of characters @code{fred}. It looks them up in the name
                   3459: dictionary, but can't find them. It tries to treat them as a number, but
                   3460: they don't represent any legal number.
                   3461: @end itemize
1.21      crook    3462: 
1.29      crook    3463: At this point, the text interpreter gives up and prints an error
                   3464: message. The error message shows exactly how far the text interpreter
                   3465: got in processing the line. In particular, it shows that the text
                   3466: interpreter made no attempt to do anything with the final character
                   3467: group, @code{dup}, even though we have good reason to believe that the
                   3468: text interpreter would have no problem looking that word up and
                   3469: executing it a second time.
1.21      crook    3470: 
                   3471: 
1.29      crook    3472: @comment ----------------------------------------------
                   3473: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   3474: @section Stacks, postfix notation and parameter passing
                   3475: @cindex text interpreter
                   3476: @cindex outer interpreter
1.21      crook    3477: 
1.29      crook    3478: In procedural programming languages (like C and Pascal), the
                   3479: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   3480: functions or procedures are called with @dfn{explicit parameters}. For
                   3481: example, in C we might write:
1.21      crook    3482: 
1.23      crook    3483: @example
1.29      crook    3484: total = total + new_volume(length,height,depth);
1.23      crook    3485: @end example
1.21      crook    3486: 
1.23      crook    3487: @noindent
1.29      crook    3488: where new_volume is a function-call to another piece of code, and total,
                   3489: length, height and depth are all variables. length, height and depth are
                   3490: parameters to the function-call.
1.21      crook    3491: 
1.29      crook    3492: In Forth, the equivalent of the function or procedure is the
                   3493: @dfn{definition} and parameters are implicitly passed between
                   3494: definitions using a shared stack that is visible to the
                   3495: programmer. Although Forth does support variables, the existence of the
                   3496: stack means that they are used far less often than in most other
                   3497: programming languages. When the text interpreter encounters a number, it
                   3498: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    3499: actual number is implementation-dependent ...) and the particular stack
1.29      crook    3500: used for any operation is implied unambiguously by the operation being
                   3501: performed. The stack used for all integer operations is called the @dfn{data
                   3502: stack} and, since this is the stack used most commonly, references to
                   3503: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    3504: 
1.29      crook    3505: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    3506: 
1.23      crook    3507: @example
1.30      anton    3508: @kbd{1 2 3@key{RET}}  ok
1.23      crook    3509: @end example
1.21      crook    3510: 
1.29      crook    3511: Then this instructs the text interpreter to placed three numbers on the
                   3512: (data) stack. An analogy for the behaviour of the stack is to take a
                   3513: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   3514: the table. The 3 was the last card onto the pile (``last-in'') and if
                   3515: you take a card off the pile then, unless you're prepared to fiddle a
                   3516: bit, the card that you take off will be the 3 (``first-out''). The
                   3517: number that will be first-out of the stack is called the @dfn{top of
                   3518: stack}, which
                   3519: @cindex TOS definition
                   3520: is often abbreviated to @dfn{TOS}.
1.21      crook    3521: 
1.29      crook    3522: To understand how parameters are passed in Forth, consider the
                   3523: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   3524: be surprised to learn that this definition performs addition. More
                   3525: precisely, it adds two number together and produces a result. Where does
                   3526: it get the two numbers from? It takes the top two numbers off the
                   3527: stack. Where does it place the result? On the stack. You can act-out the
                   3528: behaviour of @code{+} with your playing cards like this:
1.21      crook    3529: 
                   3530: @itemize @bullet
                   3531: @item
1.29      crook    3532: Pick up two cards from the stack on the table
1.21      crook    3533: @item
1.29      crook    3534: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   3535: numbers''
1.21      crook    3536: @item
1.29      crook    3537: Decide that the answer is 5
1.21      crook    3538: @item
1.29      crook    3539: Shuffle the two cards back into the pack and find a 5
1.21      crook    3540: @item
1.29      crook    3541: Put a 5 on the remaining ace that's on the table.
1.21      crook    3542: @end itemize
                   3543: 
1.29      crook    3544: If you don't have a pack of cards handy but you do have Forth running,
                   3545: you can use the definition @code{.s} to show the current state of the stack,
                   3546: without affecting the stack. Type:
1.21      crook    3547: 
                   3548: @example
1.30      anton    3549: @kbd{clearstack 1 2 3@key{RET}} ok
                   3550: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    3551: @end example
                   3552: 
1.29      crook    3553: The text interpreter looks up the word @code{clearstack} and executes
                   3554: it; it tidies up the stack and removes any entries that may have been
                   3555: left on it by earlier examples. The text interpreter pushes each of the
                   3556: three numbers in turn onto the stack. Finally, the text interpreter
                   3557: looks up the word @code{.s} and executes it. The effect of executing
                   3558: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   3559: followed by a list of all the items on the stack; the item on the far
                   3560: right-hand side is the TOS.
1.21      crook    3561: 
1.29      crook    3562: You can now type:
1.21      crook    3563: 
1.29      crook    3564: @example
1.30      anton    3565: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    3566: @end example
1.21      crook    3567: 
1.29      crook    3568: @noindent
                   3569: which is correct; there are now 2 items on the stack and the result of
                   3570: the addition is 5.
1.23      crook    3571: 
1.29      crook    3572: If you're playing with cards, try doing a second addition: pick up the
                   3573: two cards, work out that their sum is 6, shuffle them into the pack,
                   3574: look for a 6 and place that on the table. You now have just one item on
                   3575: the stack. What happens if you try to do a third addition? Pick up the
                   3576: first card, pick up the second card -- ah! There is no second card. This
                   3577: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95      anton    3578: do the same thing with Forth it often reports an error (probably a Stack
1.29      crook    3579: Underflow or an Invalid Memory Address error).
1.23      crook    3580: 
1.29      crook    3581: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   3582: which simply accepts that there is a finite amount of storage space
                   3583: reserved for the stack. To stretch the playing card analogy, if you had
                   3584: enough packs of cards and you piled the cards up on the table, you would
                   3585: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   3586: allows you to set the maximum size of the stacks. In general, the only
                   3587: time that you will get a stack overflow is because a definition has a
                   3588: bug in it and is generating data on the stack uncontrollably.
1.23      crook    3589: 
1.29      crook    3590: There's one final use for the playing card analogy. If you model your
                   3591: stack using a pack of playing cards, the maximum number of items on
                   3592: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   3593: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   3594: possible numbers are positive integer numbers 1 through 13; you can't
                   3595: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   3596: think about some of the cards, you can accommodate different
                   3597: numbers. For example, you could think of the Jack as representing 0,
                   3598: the Queen as representing -1 and the King as representing -2. Your
1.45      crook    3599: @i{range} remains unchanged (you can still only represent a total of 13
1.29      crook    3600: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    3601: 
1.29      crook    3602: In that analogy, the limit was the amount of information that a single
                   3603: stack entry could hold, and Forth has a similar limit. In Forth, the
                   3604: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   3605: implementation dependent and affects the maximum value that a stack
                   3606: entry can hold. A Standard Forth provides a cell size of at least
                   3607: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    3608: 
1.29      crook    3609: Forth does not do any type checking for you, so you are free to
                   3610: manipulate and combine stack items in any way you wish. A convenient way
                   3611: of treating stack items is as 2's complement signed integers, and that
                   3612: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    3613: 
1.29      crook    3614: @example
1.30      anton    3615: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    3616: @end example
1.21      crook    3617: 
1.29      crook    3618: If you use numbers and definitions like @code{+} in order to turn Forth
                   3619: into a great big pocket calculator, you will realise that it's rather
                   3620: different from a normal calculator. Rather than typing 2 + 3 = you had
                   3621: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   3622: result). The terminology used to describe this difference is to say that
                   3623: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   3624: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   3625: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    3626: 
1.29      crook    3627: Whilst postfix notation might look confusing to begin with, it has
                   3628: several important advantages:
1.21      crook    3629: 
1.23      crook    3630: @itemize @bullet
                   3631: @item
1.29      crook    3632: it is unambiguous
1.23      crook    3633: @item
1.29      crook    3634: it is more concise
1.23      crook    3635: @item
1.29      crook    3636: it fits naturally with a stack-based system
1.23      crook    3637: @end itemize
1.21      crook    3638: 
1.29      crook    3639: To examine these claims in more detail, consider these sums:
1.21      crook    3640: 
1.29      crook    3641: @example
                   3642: 6 + 5 * 4 =
                   3643: 4 * 5 + 6 =
                   3644: @end example
1.21      crook    3645: 
1.29      crook    3646: If you're just learning maths or your maths is very rusty, you will
                   3647: probably come up with the answer 44 for the first and 26 for the
                   3648: second. If you are a bit of a whizz at maths you will remember the
                   3649: @i{convention} that multiplication takes precendence over addition, and
                   3650: you'd come up with the answer 26 both times. To explain the answer 26
                   3651: to someone who got the answer 44, you'd probably rewrite the first sum
                   3652: like this:
1.21      crook    3653: 
1.29      crook    3654: @example
                   3655: 6 + (5 * 4) =
                   3656: @end example
1.21      crook    3657: 
1.29      crook    3658: If what you really wanted was to perform the addition before the
                   3659: multiplication, you would have to use parentheses to force it.
1.21      crook    3660: 
1.29      crook    3661: If you did the first two sums on a pocket calculator you would probably
                   3662: get the right answers, unless you were very cautious and entered them using
                   3663: these keystroke sequences:
1.21      crook    3664: 
1.29      crook    3665: 6 + 5 = * 4 =
                   3666: 4 * 5 = + 6 =
1.21      crook    3667: 
1.29      crook    3668: Postfix notation is unambiguous because the order that the operators
                   3669: are applied is always explicit; that also means that parentheses are
                   3670: never required. The operators are @i{active} (the act of quoting the
                   3671: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    3672: 
1.29      crook    3673: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   3674: equivalent ways:
1.26      crook    3675: 
                   3676: @example
1.29      crook    3677: 6 5 4 * +      or:
                   3678: 5 4 * 6 +
1.26      crook    3679: @end example
1.23      crook    3680: 
1.29      crook    3681: An important thing that you should notice about this notation is that
                   3682: the @i{order} of the numbers does not change; if you want to subtract
                   3683: 2 from 10 you type @code{10 2 -}.
1.1       anton    3684: 
1.29      crook    3685: The reason that Forth uses postfix notation is very simple to explain: it
                   3686: makes the implementation extremely simple, and it follows naturally from
                   3687: using the stack as a mechanism for passing parameters. Another way of
                   3688: thinking about this is to realise that all Forth definitions are
                   3689: @i{active}; they execute as they are encountered by the text
                   3690: interpreter. The result of this is that the syntax of Forth is trivially
                   3691: simple.
1.1       anton    3692: 
                   3693: 
                   3694: 
1.29      crook    3695: @comment ----------------------------------------------
                   3696: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   3697: @section Your first Forth definition
                   3698: @cindex first definition
1.1       anton    3699: 
1.29      crook    3700: Until now, the examples we've seen have been trivial; we've just been
                   3701: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   3702: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   3703: again@footnote{That's not quite true. If you press the up-arrow key on
                   3704: your keyboard you should be able to scroll back to any earlier command,
                   3705: edit it and re-enter it.} In this section we'll see how to add new
                   3706: words to Forth's vocabulary.
1.1       anton    3707: 
1.29      crook    3708: The easiest way to create a new word is to use a @dfn{colon
                   3709: definition}. We'll define a few and try them out before worrying too
                   3710: much about how they work. Try typing in these examples; be careful to
                   3711: copy the spaces accurately:
1.1       anton    3712: 
1.29      crook    3713: @example
                   3714: : add-two 2 + . ;
                   3715: : greet ." Hello and welcome" ;
                   3716: : demo 5 add-two ;
                   3717: @end example
1.1       anton    3718: 
1.29      crook    3719: @noindent
                   3720: Now try them out:
1.1       anton    3721: 
1.29      crook    3722: @example
1.30      anton    3723: @kbd{greet@key{RET}} Hello and welcome  ok
                   3724: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   3725: @kbd{4 add-two@key{RET}} 6  ok
                   3726: @kbd{demo@key{RET}} 7  ok
                   3727: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    3728: @end example
1.1       anton    3729: 
1.29      crook    3730: The first new thing that we've introduced here is the pair of words
                   3731: @code{:} and @code{;}. These are used to start and terminate a new
                   3732: definition, respectively. The first word after the @code{:} is the name
                   3733: for the new definition.
1.1       anton    3734: 
1.29      crook    3735: As you can see from the examples, a definition is built up of words that
                   3736: have already been defined; Forth makes no distinction between
                   3737: definitions that existed when you started the system up, and those that
                   3738: you define yourself.
1.1       anton    3739: 
1.29      crook    3740: The examples also introduce the words @code{.} (dot), @code{."}
                   3741: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   3742: the stack and displays it. It's like @code{.s} except that it only
                   3743: displays the top item of the stack and it is destructive; after it has
                   3744: executed, the number is no longer on the stack. There is always one
                   3745: space printed after the number, and no spaces before it. Dot-quote
                   3746: defines a string (a sequence of characters) that will be printed when
                   3747: the word is executed. The string can contain any printable characters
                   3748: except @code{"}. A @code{"} has a special function; it is not a Forth
                   3749: word but it acts as a delimiter (the way that delimiters work is
                   3750: described in the next section). Finally, @code{dup} duplicates the value
                   3751: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    3752: 
1.29      crook    3753: We already know that the text interpreter searches through the
                   3754: dictionary to locate names. If you've followed the examples earlier, you
                   3755: will already have a definition called @code{add-two}. Lets try modifying
                   3756: it by typing in a new definition:
1.1       anton    3757: 
1.29      crook    3758: @example
1.30      anton    3759: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    3760: @end example
1.5       anton    3761: 
1.29      crook    3762: Forth recognised that we were defining a word that already exists, and
                   3763: printed a message to warn us of that fact. Let's try out the new
                   3764: definition:
1.5       anton    3765: 
1.29      crook    3766: @example
1.30      anton    3767: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    3768: @end example
1.1       anton    3769: 
1.29      crook    3770: @noindent
                   3771: All that we've actually done here, though, is to create a new
                   3772: definition, with a particular name. The fact that there was already a
                   3773: definition with the same name did not make any difference to the way
                   3774: that the new definition was created (except that Forth printed a warning
                   3775: message). The old definition of add-two still exists (try @code{demo}
                   3776: again to see that this is true). Any new definition will use the new
                   3777: definition of @code{add-two}, but old definitions continue to use the
                   3778: version that already existed at the time that they were @code{compiled}.
1.1       anton    3779: 
1.29      crook    3780: Before you go on to the next section, try defining and redefining some
                   3781: words of your own.
1.1       anton    3782: 
1.29      crook    3783: @comment ----------------------------------------------
                   3784: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   3785: @section How does that work?
                   3786: @cindex parsing words
1.1       anton    3787: 
1.30      anton    3788: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   3789: 
                   3790: @c Is it a good idea to talk about the interpretation semantics of a
                   3791: @c number? We don't have an xt to go along with it. - anton
                   3792: 
                   3793: @c Now that I have eliminated execution semantics, I wonder if it would not
                   3794: @c be better to keep them (or add run-time semantics), to make it easier to
                   3795: @c explain what compilation semantics usually does. - anton
                   3796: 
1.44      crook    3797: @c nac-> I removed the term ``default compilation sematics'' from the
                   3798: @c introductory chapter. Removing ``execution semantics'' was making
                   3799: @c everything simpler to explain, then I think the use of this term made
                   3800: @c everything more complex again. I replaced it with ``default
                   3801: @c semantics'' (which is used elsewhere in the manual) by which I mean
                   3802: @c ``a definition that has neither the immediate nor the compile-only
1.83      anton    3803: @c flag set''.
                   3804: 
                   3805: @c anton: I have eliminated default semantics (except in one place where it
                   3806: @c means "default interpretation and compilation semantics"), because it
                   3807: @c makes no sense in the presence of combined words.  I reverted to
                   3808: @c "execution semantics" where necessary.
                   3809: 
                   3810: @c nac-> I reworded big chunks of the ``how does that work''
1.44      crook    3811: @c section (and, unusually for me, I think I even made it shorter!).  See
                   3812: @c what you think -- I know I have not addressed your primary concern
                   3813: @c that it is too heavy-going for an introduction. From what I understood
                   3814: @c of your course notes it looks as though they might be a good framework. 
                   3815: @c Things that I've tried to capture here are some things that came as a
                   3816: @c great revelation here when I first understood them. Also, I like the
                   3817: @c fact that a very simple code example shows up almost all of the issues
                   3818: @c that you need to understand to see how Forth works. That's unique and
                   3819: @c worthwhile to emphasise.
                   3820: 
1.83      anton    3821: @c anton: I think it's a good idea to present the details, especially those
                   3822: @c that you found to be a revelation, and probably the tutorial tries to be
                   3823: @c too superficial and does not get some of the things across that make
                   3824: @c Forth special.  I do believe that most of the time these things should
                   3825: @c be discussed at the end of a section or in separate sections instead of
                   3826: @c in the middle of a section (e.g., the stuff you added in "User-defined
                   3827: @c defining words" leads in a completely different direction from the rest
                   3828: @c of the section).
                   3829: 
1.29      crook    3830: Now we're going to take another look at the definition of @code{add-two}
                   3831: from the previous section. From our knowledge of the way that the text
                   3832: interpreter works, we would have expected this result when we tried to
                   3833: define @code{add-two}:
1.21      crook    3834: 
1.29      crook    3835: @example
1.44      crook    3836: @kbd{: add-two 2 + . ;@key{RET}}
1.29      crook    3837:   ^^^^^^^
                   3838: Error: Undefined word
                   3839: @end example
1.28      crook    3840: 
1.29      crook    3841: The reason that this didn't happen is bound up in the way that @code{:}
                   3842: works. The word @code{:} does two special things. The first special
                   3843: thing that it does prevents the text interpreter from ever seeing the
                   3844: characters @code{add-two}. The text interpreter uses a variable called
                   3845: @cindex modifying >IN
1.44      crook    3846: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29      crook    3847: input line. When it encounters the word @code{:} it behaves in exactly
                   3848: the same way as it does for any other word; it looks it up in the name
                   3849: dictionary, finds its xt and executes it. When @code{:} executes, it
                   3850: looks at the input buffer, finds the word @code{add-two} and advances the
                   3851: value of @code{>IN} to point past it. It then does some other stuff
                   3852: associated with creating the new definition (including creating an entry
                   3853: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   3854: completes, control returns to the text interpreter, which is oblivious
                   3855: to the fact that it has been tricked into ignoring part of the input
                   3856: line.
1.21      crook    3857: 
1.29      crook    3858: @cindex parsing words
                   3859: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   3860: prevent the text interpreter from acting on the whole of the input line
                   3861: -- are called @dfn{parsing words}.
1.21      crook    3862: 
1.29      crook    3863: @cindex @code{state} - effect on the text interpreter
                   3864: @cindex text interpreter - effect of state
                   3865: The second special thing that @code{:} does is change the value of a
                   3866: variable called @code{state}, which affects the way that the text
                   3867: interpreter behaves. When Gforth starts up, @code{state} has the value
                   3868: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   3869: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44      crook    3870: the text interpreter is said to be @dfn{compiling}.
                   3871: 
                   3872: In this example, the text interpreter is compiling when it processes the
                   3873: string ``@code{2 + . ;}''. It still breaks the string down into
                   3874: character sequences in the same way. However, instead of pushing the
                   3875: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
                   3876: into the definition of @code{add-two} that will make the number @code{2} get
                   3877: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
                   3878: the behaviours of @code{+} and @code{.} are also compiled into the
                   3879: definition.
                   3880: 
                   3881: One category of words don't get compiled. These so-called @dfn{immediate
                   3882: words} get executed (performed @i{now}) regardless of whether the text
                   3883: interpreter is interpreting or compiling. The word @code{;} is an
                   3884: immediate word. Rather than being compiled into the definition, it
                   3885: executes. Its effect is to terminate the current definition, which
                   3886: includes changing the value of @code{state} back to 0.
                   3887: 
                   3888: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
                   3889: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
                   3890: definition.
1.28      crook    3891: 
1.30      anton    3892: In Forth, every word or number can be described in terms of two
1.29      crook    3893: properties:
1.28      crook    3894: 
                   3895: @itemize @bullet
                   3896: @item
1.29      crook    3897: @cindex interpretation semantics
1.44      crook    3898: Its @dfn{interpretation semantics} describe how it will behave when the
                   3899: text interpreter encounters it in @dfn{interpret} state. The
                   3900: interpretation semantics of a word are represented by an @dfn{execution
                   3901: token}.
1.28      crook    3902: @item
1.29      crook    3903: @cindex compilation semantics
1.44      crook    3904: Its @dfn{compilation semantics} describe how it will behave when the
                   3905: text interpreter encounters it in @dfn{compile} state. The compilation
                   3906: semantics of a word are represented in an implementation-dependent way;
                   3907: Gforth uses a @dfn{compilation token}.
1.29      crook    3908: @end itemize
                   3909: 
                   3910: @noindent
                   3911: Numbers are always treated in a fixed way:
                   3912: 
                   3913: @itemize @bullet
1.28      crook    3914: @item
1.44      crook    3915: When the number is @dfn{interpreted}, its behaviour is to push the
                   3916: number onto the stack.
1.28      crook    3917: @item
1.30      anton    3918: When the number is @dfn{compiled}, a piece of code is appended to the
                   3919: current definition that pushes the number when it runs. (In other words,
                   3920: the compilation semantics of a number are to postpone its interpretation
                   3921: semantics until the run-time of the definition that it is being compiled
                   3922: into.)
1.29      crook    3923: @end itemize
                   3924: 
1.44      crook    3925: Words don't behave in such a regular way, but most have @i{default
                   3926: semantics} which means that they behave like this:
1.29      crook    3927: 
                   3928: @itemize @bullet
1.28      crook    3929: @item
1.30      anton    3930: The @dfn{interpretation semantics} of the word are to do something useful.
                   3931: @item
1.29      crook    3932: The @dfn{compilation semantics} of the word are to append its
1.30      anton    3933: @dfn{interpretation semantics} to the current definition (so that its
                   3934: run-time behaviour is to do something useful).
1.28      crook    3935: @end itemize
                   3936: 
1.30      anton    3937: @cindex immediate words
1.44      crook    3938: The actual behaviour of any particular word can be controlled by using
                   3939: the words @code{immediate} and @code{compile-only} when the word is
                   3940: defined. These words set flags in the name dictionary entry of the most
                   3941: recently defined word, and these flags are retrieved by the text
                   3942: interpreter when it finds the word in the name dictionary.
                   3943: 
                   3944: A word that is marked as @dfn{immediate} has compilation semantics that
                   3945: are identical to its interpretation semantics. In other words, it
                   3946: behaves like this:
1.29      crook    3947: 
                   3948: @itemize @bullet
                   3949: @item
1.30      anton    3950: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    3951: @item
1.30      anton    3952: The @dfn{compilation semantics} of the word are to do something useful
                   3953: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    3954: @end itemize
1.28      crook    3955: 
1.44      crook    3956: Marking a word as @dfn{compile-only} prohibits the text interpreter from
                   3957: performing the interpretation semantics of the word directly; an attempt
                   3958: to do so will generate an error. It is never necessary to use
                   3959: @code{compile-only} (and it is not even part of ANS Forth, though it is
                   3960: provided by many implementations) but it is good etiquette to apply it
                   3961: to a word that will not behave correctly (and might have unexpected
                   3962: side-effects) in interpret state. For example, it is only legal to use
                   3963: the conditional word @code{IF} within a definition. If you forget this
                   3964: and try to use it elsewhere, the fact that (in Gforth) it is marked as
                   3965: @code{compile-only} allows the text interpreter to generate a helpful
                   3966: error message rather than subjecting you to the consequences of your
                   3967: folly.
                   3968: 
1.29      crook    3969: This example shows the difference between an immediate and a
                   3970: non-immediate word:
1.28      crook    3971: 
1.29      crook    3972: @example
                   3973: : show-state state @@ . ;
                   3974: : show-state-now show-state ; immediate
                   3975: : word1 show-state ;
                   3976: : word2 show-state-now ;
1.28      crook    3977: @end example
1.23      crook    3978: 
1.29      crook    3979: The word @code{immediate} after the definition of @code{show-state-now}
                   3980: makes that word an immediate word. These definitions introduce a new
                   3981: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   3982: variable, and leaves it on the stack. Therefore, the behaviour of
                   3983: @code{show-state} is to print a number that represents the current value
                   3984: of @code{state}.
1.28      crook    3985: 
1.29      crook    3986: When you execute @code{word1}, it prints the number 0, indicating that
                   3987: the system is interpreting. When the text interpreter compiled the
                   3988: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    3989: compilation semantics are to append its interpretation semantics to the
1.29      crook    3990: current definition. When you execute @code{word1}, it performs the
1.30      anton    3991: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    3992: (and therefore @code{show-state}) are executed, the system is
                   3993: interpreting.
1.28      crook    3994: 
1.30      anton    3995: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    3996: you should have seen the number -1 printed, followed by ``@code{
                   3997: ok}''. When the text interpreter compiled the definition of
                   3998: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    3999: whose compilation semantics are therefore to perform its interpretation
1.29      crook    4000: semantics. It is executed straight away (even before the text
                   4001: interpreter has moved on to process another group of characters; the
                   4002: @code{;} in this example). The effect of executing it are to display the
                   4003: value of @code{state} @i{at the time that the definition of}
                   4004: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   4005: system is compiling at this time. If you execute @code{word2} it does
                   4006: nothing at all.
1.28      crook    4007: 
1.29      crook    4008: @cindex @code{."}, how it works
                   4009: Before leaving the subject of immediate words, consider the behaviour of
                   4010: @code{."} in the definition of @code{greet}, in the previous
                   4011: section. This word is both a parsing word and an immediate word. Notice
                   4012: that there is a space between @code{."} and the start of the text
                   4013: @code{Hello and welcome}, but that there is no space between the last
                   4014: letter of @code{welcome} and the @code{"} character. The reason for this
                   4015: is that @code{."} is a Forth word; it must have a space after it so that
                   4016: the text interpreter can identify it. The @code{"} is not a Forth word;
                   4017: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   4018: is displayed, there is neither a space before the @code{H} nor after the
                   4019: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   4020: that @code{greet} is defined. When it executes, its behaviour is to
                   4021: search forward in the input line looking for the delimiter. When it
                   4022: finds the delimiter, it updates @code{>IN} to point past the
                   4023: delimiter. It also compiles some magic code into the definition of
                   4024: @code{greet}; the xt of a run-time routine that prints a text string. It
                   4025: compiles the string @code{Hello and welcome} into memory so that it is
                   4026: available to be printed later. When the text interpreter gains control,
                   4027: the next word it finds in the input stream is @code{;} and so it
                   4028: terminates the definition of @code{greet}.
1.28      crook    4029: 
                   4030: 
                   4031: @comment ----------------------------------------------
1.29      crook    4032: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   4033: @section Forth is written in Forth
                   4034: @cindex structure of Forth programs
                   4035: 
                   4036: When you start up a Forth compiler, a large number of definitions
                   4037: already exist. In Forth, you develop a new application using bottom-up
                   4038: programming techniques to create new definitions that are defined in
                   4039: terms of existing definitions. As you create each definition you can
                   4040: test and debug it interactively.
                   4041: 
                   4042: If you have tried out the examples in this section, you will probably
                   4043: have typed them in by hand; when you leave Gforth, your definitions will
                   4044: be lost. You can avoid this by using a text editor to enter Forth source
                   4045: code into a file, and then loading code from the file using
1.49      anton    4046: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29      crook    4047: processed by the text interpreter, just as though you had typed it in by
                   4048: hand@footnote{Actually, there are some subtle differences -- see
                   4049: @ref{The Text Interpreter}.}.
                   4050: 
                   4051: Gforth also supports the traditional Forth alternative to using text
1.49      anton    4052: files for program entry (@pxref{Blocks}).
1.28      crook    4053: 
1.29      crook    4054: In common with many, if not most, Forth compilers, most of Gforth is
                   4055: actually written in Forth. All of the @file{.fs} files in the
                   4056: installation directory@footnote{For example,
1.30      anton    4057: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    4058: study to see examples of Forth programming.
1.28      crook    4059: 
1.29      crook    4060: Gforth maintains a history file that records every line that you type to
                   4061: the text interpreter. This file is preserved between sessions, and is
                   4062: used to provide a command-line recall facility. If you enter long
                   4063: definitions by hand, you can use a text editor to paste them out of the
                   4064: history file into a Forth source file for reuse at a later time
1.49      anton    4065: (for more information @pxref{Command-line editing}).
1.28      crook    4066: 
                   4067: 
                   4068: @comment ----------------------------------------------
1.29      crook    4069: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   4070: @section Review - elements of a Forth system
                   4071: @cindex elements of a Forth system
1.28      crook    4072: 
1.29      crook    4073: To summarise this chapter:
1.28      crook    4074: 
                   4075: @itemize @bullet
                   4076: @item
1.29      crook    4077: Forth programs use @dfn{factoring} to break a problem down into small
                   4078: fragments called @dfn{words} or @dfn{definitions}.
                   4079: @item
                   4080: Forth program development is an interactive process.
                   4081: @item
                   4082: The main command loop that accepts input, and controls both
                   4083: interpretation and compilation, is called the @dfn{text interpreter}
                   4084: (also known as the @dfn{outer interpreter}).
                   4085: @item
                   4086: Forth has a very simple syntax, consisting of words and numbers
                   4087: separated by spaces or carriage-return characters. Any additional syntax
                   4088: is imposed by @dfn{parsing words}.
                   4089: @item
                   4090: Forth uses a stack to pass parameters between words. As a result, it
                   4091: uses postfix notation.
                   4092: @item
                   4093: To use a word that has previously been defined, the text interpreter
                   4094: searches for the word in the @dfn{name dictionary}.
                   4095: @item
1.30      anton    4096: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    4097: @item
1.29      crook    4098: The text interpreter uses the value of @code{state} to select between
                   4099: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   4100: semantics} of a word that it encounters.
1.28      crook    4101: @item
1.30      anton    4102: The relationship between the @dfn{interpretation semantics} and
                   4103: @dfn{compilation semantics} for a word
1.29      crook    4104: depend upon the way in which the word was defined (for example, whether
                   4105: it is an @dfn{immediate} word).
1.28      crook    4106: @item
1.29      crook    4107: Forth definitions can be implemented in Forth (called @dfn{high-level
                   4108: definitions}) or in some other way (usually a lower-level language and
                   4109: as a result often called @dfn{low-level definitions}, @dfn{code
                   4110: definitions} or @dfn{primitives}).
1.28      crook    4111: @item
1.29      crook    4112: Many Forth systems are implemented mainly in Forth.
1.28      crook    4113: @end itemize
                   4114: 
                   4115: 
1.29      crook    4116: @comment ----------------------------------------------
1.48      anton    4117: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29      crook    4118: @section Where To Go Next
                   4119: @cindex where to go next
1.28      crook    4120: 
1.29      crook    4121: Amazing as it may seem, if you have read (and understood) this far, you
                   4122: know almost all the fundamentals about the inner workings of a Forth
                   4123: system. You certainly know enough to be able to read and understand the
                   4124: rest of this manual and the ANS Forth document, to learn more about the
                   4125: facilities that Forth in general and Gforth in particular provide. Even
                   4126: scarier, you know almost enough to implement your own Forth system.
1.30      anton    4127: However, that's not a good idea just yet... better to try writing some
1.29      crook    4128: programs in Gforth.
1.28      crook    4129: 
1.29      crook    4130: Forth has such a rich vocabulary that it can be hard to know where to
                   4131: start in learning it. This section suggests a few sets of words that are
                   4132: enough to write small but useful programs. Use the word index in this
                   4133: document to learn more about each word, then try it out and try to write
                   4134: small definitions using it. Start by experimenting with these words:
1.28      crook    4135: 
                   4136: @itemize @bullet
                   4137: @item
1.29      crook    4138: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   4139: @item
                   4140: Comparison: @code{MIN MAX =}
                   4141: @item
                   4142: Logic: @code{AND OR XOR NOT}
                   4143: @item
                   4144: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    4145: @item
1.29      crook    4146: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    4147: @item
1.29      crook    4148: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    4149: @item
1.29      crook    4150: Defining words: @code{: ; CREATE}
1.28      crook    4151: @item
1.29      crook    4152: Memory allocation words: @code{ALLOT ,}
1.28      crook    4153: @item
1.29      crook    4154: Tools: @code{SEE WORDS .S MARKER}
                   4155: @end itemize
                   4156: 
                   4157: When you have mastered those, go on to:
                   4158: 
                   4159: @itemize @bullet
1.28      crook    4160: @item
1.29      crook    4161: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    4162: @item
1.29      crook    4163: Memory access: @code{@@ !}
1.28      crook    4164: @end itemize
1.23      crook    4165: 
1.29      crook    4166: When you have mastered these, there's nothing for it but to read through
                   4167: the whole of this manual and find out what you've missed.
                   4168: 
                   4169: @comment ----------------------------------------------
1.48      anton    4170: @node Exercises,  , Where to go next, Introduction
1.29      crook    4171: @section Exercises
                   4172: @cindex exercises
                   4173: 
                   4174: TODO: provide a set of programming excercises linked into the stuff done
                   4175: already and into other sections of the manual. Provide solutions to all
                   4176: the exercises in a .fs file in the distribution.
                   4177: 
                   4178: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   4179: 
                   4180: @c excercises:
                   4181: @c 1. take inches and convert to feet and inches.
                   4182: @c 2. take temperature and convert from fahrenheight to celcius;
                   4183: @c    may need to care about symmetric vs floored??
                   4184: @c 3. take input line and do character substitution
                   4185: @c    to encipher or decipher
                   4186: @c 4. as above but work on a file for in and out
                   4187: @c 5. take input line and convert to pig-latin 
                   4188: @c
                   4189: @c thing of sets of things to exercise then come up with
                   4190: @c problems that need those things.
                   4191: 
                   4192: 
1.26      crook    4193: @c ******************************************************************
1.29      crook    4194: @node Words, Error messages, Introduction, Top
1.1       anton    4195: @chapter Forth Words
1.26      crook    4196: @cindex words
1.1       anton    4197: 
                   4198: @menu
                   4199: * Notation::                    
1.65      anton    4200: * Case insensitivity::          
                   4201: * Comments::                    
                   4202: * Boolean Flags::               
1.1       anton    4203: * Arithmetic::                  
                   4204: * Stack Manipulation::          
1.5       anton    4205: * Memory::                      
1.1       anton    4206: * Control Structures::          
                   4207: * Defining Words::              
1.65      anton    4208: * Interpretation and Compilation Semantics::  
1.47      crook    4209: * Tokens for Words::            
1.81      anton    4210: * Compiling words::             
1.65      anton    4211: * The Text Interpreter::        
1.111     anton    4212: * The Input Stream::            
1.65      anton    4213: * Word Lists::                  
                   4214: * Environmental Queries::       
1.12      anton    4215: * Files::                       
                   4216: * Blocks::                      
                   4217: * Other I/O::                   
1.121     anton    4218: * OS command line arguments::   
1.78      anton    4219: * Locals::                      
                   4220: * Structures::                  
                   4221: * Object-oriented Forth::       
1.12      anton    4222: * Programming Tools::           
                   4223: * Assembler and Code Words::    
                   4224: * Threading Words::             
1.65      anton    4225: * Passing Commands to the OS::  
                   4226: * Keeping track of Time::       
                   4227: * Miscellaneous Words::         
1.1       anton    4228: @end menu
                   4229: 
1.65      anton    4230: @node Notation, Case insensitivity, Words, Words
1.1       anton    4231: @section Notation
                   4232: @cindex notation of glossary entries
                   4233: @cindex format of glossary entries
                   4234: @cindex glossary notation format
                   4235: @cindex word glossary entry format
                   4236: 
                   4237: The Forth words are described in this section in the glossary notation
1.67      anton    4238: that has become a de-facto standard for Forth texts:
1.1       anton    4239: 
                   4240: @format
1.29      crook    4241: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    4242: @end format
1.29      crook    4243: @i{Description}
1.1       anton    4244: 
                   4245: @table @var
                   4246: @item word
1.28      crook    4247: The name of the word.
1.1       anton    4248: 
                   4249: @item Stack effect
                   4250: @cindex stack effect
1.29      crook    4251: The stack effect is written in the notation @code{@i{before} --
                   4252: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    4253: stack entries before and after the execution of the word. The rest of
                   4254: the stack is not touched by the word. The top of stack is rightmost,
                   4255: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   4256: uses a separate floating point stack, but a unified stack
1.29      crook    4257: notation. Also, return stack effects are not shown in @i{stack
                   4258: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    4259: the type and/or the function of the item. See below for a discussion of
                   4260: the types.
                   4261: 
                   4262: All words have two stack effects: A compile-time stack effect and a
                   4263: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    4264: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    4265: this standard behaviour, or the word does other unusual things at
                   4266: compile time, both stack effects are shown; otherwise only the run-time
                   4267: stack effect is shown.
                   4268: 
                   4269: @cindex pronounciation of words
                   4270: @item pronunciation
                   4271: How the word is pronounced.
                   4272: 
                   4273: @cindex wordset
1.67      anton    4274: @cindex environment wordset
1.1       anton    4275: @item wordset
1.21      crook    4276: The ANS Forth standard is divided into several word sets. A standard
                   4277: system need not support all of them. Therefore, in theory, the fewer
                   4278: word sets your program uses the more portable it will be. However, we
                   4279: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    4280: all word sets. Words that are not defined in ANS Forth have
1.21      crook    4281: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    4282: describes words that will work in future releases of Gforth;
                   4283: @code{gforth-internal} words are more volatile. Environmental query
                   4284: strings are also displayed like words; you can recognize them by the
1.21      crook    4285: @code{environment} in the word set field.
1.1       anton    4286: 
                   4287: @item Description
                   4288: A description of the behaviour of the word.
                   4289: @end table
                   4290: 
                   4291: @cindex types of stack items
                   4292: @cindex stack item types
                   4293: The type of a stack item is specified by the character(s) the name
                   4294: starts with:
                   4295: 
                   4296: @table @code
                   4297: @item f
                   4298: @cindex @code{f}, stack item type
                   4299: Boolean flags, i.e. @code{false} or @code{true}.
                   4300: @item c
                   4301: @cindex @code{c}, stack item type
                   4302: Char
                   4303: @item w
                   4304: @cindex @code{w}, stack item type
                   4305: Cell, can contain an integer or an address
                   4306: @item n
                   4307: @cindex @code{n}, stack item type
                   4308: signed integer
                   4309: @item u
                   4310: @cindex @code{u}, stack item type
                   4311: unsigned integer
                   4312: @item d
                   4313: @cindex @code{d}, stack item type
                   4314: double sized signed integer
                   4315: @item ud
                   4316: @cindex @code{ud}, stack item type
                   4317: double sized unsigned integer
                   4318: @item r
                   4319: @cindex @code{r}, stack item type
                   4320: Float (on the FP stack)
1.21      crook    4321: @item a-
1.1       anton    4322: @cindex @code{a_}, stack item type
                   4323: Cell-aligned address
1.21      crook    4324: @item c-
1.1       anton    4325: @cindex @code{c_}, stack item type
                   4326: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    4327: @item f-
1.1       anton    4328: @cindex @code{f_}, stack item type
                   4329: Float-aligned address
1.21      crook    4330: @item df-
1.1       anton    4331: @cindex @code{df_}, stack item type
                   4332: Address aligned for IEEE double precision float
1.21      crook    4333: @item sf-
1.1       anton    4334: @cindex @code{sf_}, stack item type
                   4335: Address aligned for IEEE single precision float
                   4336: @item xt
                   4337: @cindex @code{xt}, stack item type
                   4338: Execution token, same size as Cell
                   4339: @item wid
                   4340: @cindex @code{wid}, stack item type
1.21      crook    4341: Word list ID, same size as Cell
1.68      anton    4342: @item ior, wior
                   4343: @cindex ior type description
                   4344: @cindex wior type description
                   4345: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
1.1       anton    4346: @item f83name
                   4347: @cindex @code{f83name}, stack item type
                   4348: Pointer to a name structure
                   4349: @item "
                   4350: @cindex @code{"}, stack item type
1.12      anton    4351: string in the input stream (not on the stack). The terminating character
                   4352: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    4353: quotes.
                   4354: @end table
                   4355: 
1.65      anton    4356: @comment ----------------------------------------------
                   4357: @node Case insensitivity, Comments, Notation, Words
                   4358: @section Case insensitivity
                   4359: @cindex case sensitivity
                   4360: @cindex upper and lower case
                   4361: 
                   4362: Gforth is case-insensitive; you can enter definitions and invoke
                   4363: Standard words using upper, lower or mixed case (however,
                   4364: @pxref{core-idef, Implementation-defined options, Implementation-defined
                   4365: options}).
                   4366: 
                   4367: ANS Forth only @i{requires} implementations to recognise Standard words
                   4368: when they are typed entirely in upper case. Therefore, a Standard
                   4369: program must use upper case for all Standard words. You can use whatever
                   4370: case you like for words that you define, but in a Standard program you
                   4371: have to use the words in the same case that you defined them.
                   4372: 
                   4373: Gforth supports case sensitivity through @code{table}s (case-sensitive
                   4374: wordlists, @pxref{Word Lists}).
                   4375: 
                   4376: Two people have asked how to convert Gforth to be case-sensitive; while
                   4377: we think this is a bad idea, you can change all wordlists into tables
                   4378: like this:
                   4379: 
                   4380: @example
                   4381: ' table-find forth-wordlist wordlist-map @ !
                   4382: @end example
                   4383: 
                   4384: Note that you now have to type the predefined words in the same case
                   4385: that we defined them, which are varying.  You may want to convert them
                   4386: to your favourite case before doing this operation (I won't explain how,
                   4387: because if you are even contemplating doing this, you'd better have
                   4388: enough knowledge of Forth systems to know this already).
                   4389: 
                   4390: @node Comments, Boolean Flags, Case insensitivity, Words
1.21      crook    4391: @section Comments
1.26      crook    4392: @cindex comments
1.21      crook    4393: 
1.29      crook    4394: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   4395: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    4396: 
1.44      crook    4397: 
1.23      crook    4398: doc-(
1.21      crook    4399: doc-\
1.23      crook    4400: doc-\G
1.21      crook    4401: 
1.44      crook    4402: 
1.21      crook    4403: @node Boolean Flags, Arithmetic, Comments, Words
                   4404: @section Boolean Flags
1.26      crook    4405: @cindex Boolean flags
1.21      crook    4406: 
                   4407: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   4408: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    4409: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    4410: a cell that has @i{any} bit set as @code{true}.
1.67      anton    4411: @c on and off to Memory? 
                   4412: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44      crook    4413: 
1.21      crook    4414: doc-true
                   4415: doc-false
1.29      crook    4416: doc-on
                   4417: doc-off
1.21      crook    4418: 
1.44      crook    4419: 
1.21      crook    4420: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    4421: @section Arithmetic
                   4422: @cindex arithmetic words
                   4423: 
                   4424: @cindex division with potentially negative operands
                   4425: Forth arithmetic is not checked, i.e., you will not hear about integer
                   4426: overflow on addition or multiplication, you may hear about division by
                   4427: zero if you are lucky. The operator is written after the operands, but
                   4428: the operands are still in the original order. I.e., the infix @code{2-1}
                   4429: corresponds to @code{2 1 -}. Forth offers a variety of division
                   4430: operators. If you perform division with potentially negative operands,
                   4431: you do not want to use @code{/} or @code{/mod} with its undefined
                   4432: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   4433: former, @pxref{Mixed precision}).
1.26      crook    4434: @comment TODO discuss the different division forms and the std approach
1.1       anton    4435: 
                   4436: @menu
                   4437: * Single precision::            
1.67      anton    4438: * Double precision::            Double-cell integer arithmetic
1.1       anton    4439: * Bitwise operations::          
1.67      anton    4440: * Numeric comparison::          
1.29      crook    4441: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    4442: * Floating Point::              
                   4443: @end menu
                   4444: 
1.67      anton    4445: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1       anton    4446: @subsection Single precision
                   4447: @cindex single precision arithmetic words
                   4448: 
1.67      anton    4449: @c !! cell undefined
                   4450: 
                   4451: By default, numbers in Forth are single-precision integers that are one
1.26      crook    4452: cell in size. They can be signed or unsigned, depending upon how you
1.49      anton    4453: treat them. For the rules used by the text interpreter for recognising
                   4454: single-precision integers see @ref{Number Conversion}.
1.21      crook    4455: 
1.67      anton    4456: These words are all defined for signed operands, but some of them also
                   4457: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
                   4458: @code{*}.
1.44      crook    4459: 
1.1       anton    4460: doc-+
1.21      crook    4461: doc-1+
1.1       anton    4462: doc--
1.21      crook    4463: doc-1-
1.1       anton    4464: doc-*
                   4465: doc-/
                   4466: doc-mod
                   4467: doc-/mod
                   4468: doc-negate
                   4469: doc-abs
                   4470: doc-min
                   4471: doc-max
1.27      crook    4472: doc-floored
1.1       anton    4473: 
1.44      crook    4474: 
1.67      anton    4475: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21      crook    4476: @subsection Double precision
                   4477: @cindex double precision arithmetic words
                   4478: 
1.49      anton    4479: For the rules used by the text interpreter for
                   4480: recognising double-precision integers, see @ref{Number Conversion}.
1.21      crook    4481: 
                   4482: A double precision number is represented by a cell pair, with the most
1.67      anton    4483: significant cell at the TOS. It is trivial to convert an unsigned single
                   4484: to a double: simply push a @code{0} onto the TOS. Since numbers are
                   4485: represented by Gforth using 2's complement arithmetic, converting a
                   4486: signed single to a (signed) double requires sign-extension across the
                   4487: most significant cell. This can be achieved using @code{s>d}. The moral
                   4488: of the story is that you cannot convert a number without knowing whether
                   4489: it represents an unsigned or a signed number.
1.21      crook    4490: 
1.67      anton    4491: These words are all defined for signed operands, but some of them also
                   4492: work for unsigned numbers: @code{d+}, @code{d-}.
1.44      crook    4493: 
1.21      crook    4494: doc-s>d
1.67      anton    4495: doc-d>s
1.21      crook    4496: doc-d+
                   4497: doc-d-
                   4498: doc-dnegate
                   4499: doc-dabs
                   4500: doc-dmin
                   4501: doc-dmax
                   4502: 
1.44      crook    4503: 
1.67      anton    4504: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
                   4505: @subsection Bitwise operations
                   4506: @cindex bitwise operation words
                   4507: 
                   4508: 
                   4509: doc-and
                   4510: doc-or
                   4511: doc-xor
                   4512: doc-invert
                   4513: doc-lshift
                   4514: doc-rshift
                   4515: doc-2*
                   4516: doc-d2*
                   4517: doc-2/
                   4518: doc-d2/
                   4519: 
                   4520: 
                   4521: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21      crook    4522: @subsection Numeric comparison
                   4523: @cindex numeric comparison words
                   4524: 
1.67      anton    4525: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
                   4526: d0= d0<>}) work for for both signed and unsigned numbers.
1.44      crook    4527: 
1.28      crook    4528: doc-<
                   4529: doc-<=
                   4530: doc-<>
                   4531: doc-=
                   4532: doc->
                   4533: doc->=
                   4534: 
1.21      crook    4535: doc-0<
1.23      crook    4536: doc-0<=
1.21      crook    4537: doc-0<>
                   4538: doc-0=
1.23      crook    4539: doc-0>
                   4540: doc-0>=
1.28      crook    4541: 
                   4542: doc-u<
                   4543: doc-u<=
1.44      crook    4544: @c u<> and u= exist but are the same as <> and =
1.31      anton    4545: @c doc-u<>
                   4546: @c doc-u=
1.28      crook    4547: doc-u>
                   4548: doc-u>=
                   4549: 
                   4550: doc-within
                   4551: 
                   4552: doc-d<
                   4553: doc-d<=
                   4554: doc-d<>
                   4555: doc-d=
                   4556: doc-d>
                   4557: doc-d>=
1.23      crook    4558: 
1.21      crook    4559: doc-d0<
1.23      crook    4560: doc-d0<=
                   4561: doc-d0<>
1.21      crook    4562: doc-d0=
1.23      crook    4563: doc-d0>
                   4564: doc-d0>=
                   4565: 
1.21      crook    4566: doc-du<
1.28      crook    4567: doc-du<=
1.44      crook    4568: @c du<> and du= exist but are the same as d<> and d=
1.31      anton    4569: @c doc-du<>
                   4570: @c doc-du=
1.28      crook    4571: doc-du>
                   4572: doc-du>=
1.1       anton    4573: 
1.44      crook    4574: 
1.21      crook    4575: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    4576: @subsection Mixed precision
                   4577: @cindex mixed precision arithmetic words
                   4578: 
1.44      crook    4579: 
1.1       anton    4580: doc-m+
                   4581: doc-*/
                   4582: doc-*/mod
                   4583: doc-m*
                   4584: doc-um*
                   4585: doc-m*/
                   4586: doc-um/mod
                   4587: doc-fm/mod
                   4588: doc-sm/rem
                   4589: 
1.44      crook    4590: 
1.21      crook    4591: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    4592: @subsection Floating Point
                   4593: @cindex floating point arithmetic words
                   4594: 
1.49      anton    4595: For the rules used by the text interpreter for
                   4596: recognising floating-point numbers see @ref{Number Conversion}.
1.1       anton    4597: 
1.67      anton    4598: Gforth has a separate floating point stack, but the documentation uses
                   4599: the unified notation.@footnote{It's easy to generate the separate
                   4600: notation from that by just separating the floating-point numbers out:
                   4601: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
                   4602: r3 )}.}
1.1       anton    4603: 
                   4604: @cindex floating-point arithmetic, pitfalls
                   4605: Floating point numbers have a number of unpleasant surprises for the
                   4606: unwary (e.g., floating point addition is not associative) and even a few
                   4607: for the wary. You should not use them unless you know what you are doing
                   4608: or you don't care that the results you get are totally bogus. If you
                   4609: want to learn about the problems of floating point numbers (and how to
1.66      anton    4610: avoid them), you might start with @cite{David Goldberg,
                   4611: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
                   4612: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
                   4613: Surveys 23(1):5@minus{}48, March 1991}.
1.1       anton    4614: 
1.44      crook    4615: 
1.21      crook    4616: doc-d>f
                   4617: doc-f>d
1.1       anton    4618: doc-f+
                   4619: doc-f-
                   4620: doc-f*
                   4621: doc-f/
                   4622: doc-fnegate
                   4623: doc-fabs
                   4624: doc-fmax
                   4625: doc-fmin
                   4626: doc-floor
                   4627: doc-fround
                   4628: doc-f**
                   4629: doc-fsqrt
                   4630: doc-fexp
                   4631: doc-fexpm1
                   4632: doc-fln
                   4633: doc-flnp1
                   4634: doc-flog
                   4635: doc-falog
1.32      anton    4636: doc-f2*
                   4637: doc-f2/
                   4638: doc-1/f
                   4639: doc-precision
                   4640: doc-set-precision
                   4641: 
                   4642: @cindex angles in trigonometric operations
                   4643: @cindex trigonometric operations
                   4644: Angles in floating point operations are given in radians (a full circle
                   4645: has 2 pi radians).
                   4646: 
1.1       anton    4647: doc-fsin
                   4648: doc-fcos
                   4649: doc-fsincos
                   4650: doc-ftan
                   4651: doc-fasin
                   4652: doc-facos
                   4653: doc-fatan
                   4654: doc-fatan2
                   4655: doc-fsinh
                   4656: doc-fcosh
                   4657: doc-ftanh
                   4658: doc-fasinh
                   4659: doc-facosh
                   4660: doc-fatanh
1.21      crook    4661: doc-pi
1.28      crook    4662: 
1.32      anton    4663: @cindex equality of floats
                   4664: @cindex floating-point comparisons
1.31      anton    4665: One particular problem with floating-point arithmetic is that comparison
                   4666: for equality often fails when you would expect it to succeed.  For this
                   4667: reason approximate equality is often preferred (but you still have to
1.67      anton    4668: know what you are doing).  Also note that IEEE NaNs may compare
1.68      anton    4669: differently from what you might expect.  The comparison words are:
1.31      anton    4670: 
                   4671: doc-f~rel
                   4672: doc-f~abs
1.68      anton    4673: doc-f~
1.31      anton    4674: doc-f=
                   4675: doc-f<>
                   4676: 
                   4677: doc-f<
                   4678: doc-f<=
                   4679: doc-f>
                   4680: doc-f>=
                   4681: 
1.21      crook    4682: doc-f0<
1.28      crook    4683: doc-f0<=
                   4684: doc-f0<>
1.21      crook    4685: doc-f0=
1.28      crook    4686: doc-f0>
                   4687: doc-f0>=
                   4688: 
1.1       anton    4689: 
                   4690: @node Stack Manipulation, Memory, Arithmetic, Words
                   4691: @section Stack Manipulation
                   4692: @cindex stack manipulation words
                   4693: 
                   4694: @cindex floating-point stack in the standard
1.21      crook    4695: Gforth maintains a number of separate stacks:
                   4696: 
1.29      crook    4697: @cindex data stack
                   4698: @cindex parameter stack
1.21      crook    4699: @itemize @bullet
                   4700: @item
1.29      crook    4701: A data stack (also known as the @dfn{parameter stack}) -- for
                   4702: characters, cells, addresses, and double cells.
1.21      crook    4703: 
1.29      crook    4704: @cindex floating-point stack
1.21      crook    4705: @item
1.44      crook    4706: A floating point stack -- for holding floating point (FP) numbers.
1.21      crook    4707: 
1.29      crook    4708: @cindex return stack
1.21      crook    4709: @item
1.44      crook    4710: A return stack -- for holding the return addresses of colon
1.32      anton    4711: definitions and other (non-FP) data.
1.21      crook    4712: 
1.29      crook    4713: @cindex locals stack
1.21      crook    4714: @item
1.44      crook    4715: A locals stack -- for holding local variables.
1.21      crook    4716: @end itemize
                   4717: 
1.1       anton    4718: @menu
                   4719: * Data stack::                  
                   4720: * Floating point stack::        
                   4721: * Return stack::                
                   4722: * Locals stack::                
                   4723: * Stack pointer manipulation::  
                   4724: @end menu
                   4725: 
                   4726: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   4727: @subsection Data stack
                   4728: @cindex data stack manipulation words
                   4729: @cindex stack manipulations words, data stack
                   4730: 
1.44      crook    4731: 
1.1       anton    4732: doc-drop
                   4733: doc-nip
                   4734: doc-dup
                   4735: doc-over
                   4736: doc-tuck
                   4737: doc-swap
1.21      crook    4738: doc-pick
1.1       anton    4739: doc-rot
                   4740: doc--rot
                   4741: doc-?dup
                   4742: doc-roll
                   4743: doc-2drop
                   4744: doc-2nip
                   4745: doc-2dup
                   4746: doc-2over
                   4747: doc-2tuck
                   4748: doc-2swap
                   4749: doc-2rot
                   4750: 
1.44      crook    4751: 
1.1       anton    4752: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   4753: @subsection Floating point stack
                   4754: @cindex floating-point stack manipulation words
                   4755: @cindex stack manipulation words, floating-point stack
                   4756: 
1.32      anton    4757: Whilst every sane Forth has a separate floating-point stack, it is not
                   4758: strictly required; an ANS Forth system could theoretically keep
                   4759: floating-point numbers on the data stack. As an additional difficulty,
                   4760: you don't know how many cells a floating-point number takes. It is
                   4761: reportedly possible to write words in a way that they work also for a
                   4762: unified stack model, but we do not recommend trying it. Instead, just
                   4763: say that your program has an environmental dependency on a separate
                   4764: floating-point stack.
                   4765: 
                   4766: doc-floating-stack
                   4767: 
1.1       anton    4768: doc-fdrop
                   4769: doc-fnip
                   4770: doc-fdup
                   4771: doc-fover
                   4772: doc-ftuck
                   4773: doc-fswap
1.21      crook    4774: doc-fpick
1.1       anton    4775: doc-frot
                   4776: 
1.44      crook    4777: 
1.1       anton    4778: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   4779: @subsection Return stack
                   4780: @cindex return stack manipulation words
                   4781: @cindex stack manipulation words, return stack
                   4782: 
1.32      anton    4783: @cindex return stack and locals
                   4784: @cindex locals and return stack
                   4785: A Forth system is allowed to keep local variables on the
                   4786: return stack. This is reasonable, as local variables usually eliminate
                   4787: the need to use the return stack explicitly. So, if you want to produce
                   4788: a standard compliant program and you are using local variables in a
                   4789: word, forget about return stack manipulations in that word (refer to the
                   4790: standard document for the exact rules).
                   4791: 
1.1       anton    4792: doc->r
                   4793: doc-r>
                   4794: doc-r@
                   4795: doc-rdrop
                   4796: doc-2>r
                   4797: doc-2r>
                   4798: doc-2r@
                   4799: doc-2rdrop
                   4800: 
1.44      crook    4801: 
1.1       anton    4802: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   4803: @subsection Locals stack
                   4804: 
1.78      anton    4805: Gforth uses an extra locals stack.  It is described, along with the
                   4806: reasons for its existence, in @ref{Locals implementation}.
1.21      crook    4807: 
1.1       anton    4808: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   4809: @subsection Stack pointer manipulation
                   4810: @cindex stack pointer manipulation words
                   4811: 
1.44      crook    4812: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21      crook    4813: doc-sp0
1.1       anton    4814: doc-sp@
                   4815: doc-sp!
1.21      crook    4816: doc-fp0
1.1       anton    4817: doc-fp@
                   4818: doc-fp!
1.21      crook    4819: doc-rp0
1.1       anton    4820: doc-rp@
                   4821: doc-rp!
1.21      crook    4822: doc-lp0
1.1       anton    4823: doc-lp@
                   4824: doc-lp!
                   4825: 
1.44      crook    4826: 
1.1       anton    4827: @node Memory, Control Structures, Stack Manipulation, Words
                   4828: @section Memory
1.26      crook    4829: @cindex memory words
1.1       anton    4830: 
1.32      anton    4831: @menu
                   4832: * Memory model::                
                   4833: * Dictionary allocation::       
                   4834: * Heap Allocation::             
                   4835: * Memory Access::               
                   4836: * Address arithmetic::          
                   4837: * Memory Blocks::               
                   4838: @end menu
                   4839: 
1.67      anton    4840: In addition to the standard Forth memory allocation words, there is also
                   4841: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   4842: garbage collector}.
                   4843: 
1.32      anton    4844: @node Memory model, Dictionary allocation, Memory, Memory
                   4845: @subsection ANS Forth and Gforth memory models
                   4846: 
                   4847: @c The ANS Forth description is a mess (e.g., is the heap part of
                   4848: @c the dictionary?), so let's not stick to closely with it.
                   4849: 
1.67      anton    4850: ANS Forth considers a Forth system as consisting of several address
                   4851: spaces, of which only @dfn{data space} is managed and accessible with
                   4852: the memory words.  Memory not necessarily in data space includes the
                   4853: stacks, the code (called code space) and the headers (called name
                   4854: space). In Gforth everything is in data space, but the code for the
                   4855: primitives is usually read-only.
1.32      anton    4856: 
                   4857: Data space is divided into a number of areas: The (data space portion of
                   4858: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
                   4859: refer to the search data structure embodied in word lists and headers,
                   4860: because it is used for looking up names, just as you would in a
                   4861: conventional dictionary.}, the heap, and a number of system-allocated
                   4862: buffers.
                   4863: 
1.68      anton    4864: @cindex address arithmetic restrictions, ANS vs. Gforth
                   4865: @cindex contiguous regions, ANS vs. Gforth
1.32      anton    4866: In ANS Forth data space is also divided into contiguous regions.  You
                   4867: can only use address arithmetic within a contiguous region, not between
                   4868: them.  Usually each allocation gives you one contiguous region, but the
1.33      anton    4869: dictionary allocation words have additional rules (@pxref{Dictionary
1.32      anton    4870: allocation}).
                   4871: 
                   4872: Gforth provides one big address space, and address arithmetic can be
                   4873: performed between any addresses. However, in the dictionary headers or
                   4874: code are interleaved with data, so almost the only contiguous data space
                   4875: regions there are those described by ANS Forth as contiguous; but you
                   4876: can be sure that the dictionary is allocated towards increasing
                   4877: addresses even between contiguous regions.  The memory order of
                   4878: allocations in the heap is platform-dependent (and possibly different
                   4879: from one run to the next).
                   4880: 
1.27      crook    4881: 
1.32      anton    4882: @node Dictionary allocation, Heap Allocation, Memory model, Memory
                   4883: @subsection Dictionary allocation
1.27      crook    4884: @cindex reserving data space
                   4885: @cindex data space - reserving some
                   4886: 
1.32      anton    4887: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
                   4888: you want to deallocate X, you also deallocate everything
                   4889: allocated after X.
                   4890: 
1.68      anton    4891: @cindex contiguous regions in dictionary allocation
1.32      anton    4892: The allocations using the words below are contiguous and grow the region
                   4893: towards increasing addresses.  Other words that allocate dictionary
                   4894: memory of any kind (i.e., defining words including @code{:noname}) end
                   4895: the contiguous region and start a new one.
                   4896: 
                   4897: In ANS Forth only @code{create}d words are guaranteed to produce an
                   4898: address that is the start of the following contiguous region.  In
                   4899: particular, the cell allocated by @code{variable} is not guaranteed to
                   4900: be contiguous with following @code{allot}ed memory.
                   4901: 
                   4902: You can deallocate memory by using @code{allot} with a negative argument
                   4903: (with some restrictions, see @code{allot}). For larger deallocations use
                   4904: @code{marker}.
1.27      crook    4905: 
1.29      crook    4906: 
1.27      crook    4907: doc-here
                   4908: doc-unused
                   4909: doc-allot
                   4910: doc-c,
1.29      crook    4911: doc-f,
1.27      crook    4912: doc-,
                   4913: doc-2,
                   4914: 
1.32      anton    4915: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
                   4916: course you should allocate memory in an aligned way, too. I.e., before
                   4917: allocating allocating a cell, @code{here} must be cell-aligned, etc.
                   4918: The words below align @code{here} if it is not already.  Basically it is
                   4919: only already aligned for a type, if the last allocation was a multiple
                   4920: of the size of this type and if @code{here} was aligned for this type
                   4921: before.
                   4922: 
                   4923: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
                   4924: ANS Forth (@code{maxalign}ed in Gforth).
                   4925: 
                   4926: doc-align
                   4927: doc-falign
                   4928: doc-sfalign
                   4929: doc-dfalign
                   4930: doc-maxalign
                   4931: doc-cfalign
                   4932: 
                   4933: 
                   4934: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
                   4935: @subsection Heap allocation
                   4936: @cindex heap allocation
                   4937: @cindex dynamic allocation of memory
                   4938: @cindex memory-allocation word set
                   4939: 
1.68      anton    4940: @cindex contiguous regions and heap allocation
1.32      anton    4941: Heap allocation supports deallocation of allocated memory in any
                   4942: order. Dictionary allocation is not affected by it (i.e., it does not
                   4943: end a contiguous region). In Gforth, these words are implemented using
                   4944: the standard C library calls malloc(), free() and resize().
                   4945: 
1.68      anton    4946: The memory region produced by one invocation of @code{allocate} or
                   4947: @code{resize} is internally contiguous.  There is no contiguity between
                   4948: such a region and any other region (including others allocated from the
                   4949: heap).
                   4950: 
1.32      anton    4951: doc-allocate
                   4952: doc-free
                   4953: doc-resize
                   4954: 
1.27      crook    4955: 
1.32      anton    4956: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1       anton    4957: @subsection Memory Access
                   4958: @cindex memory access words
                   4959: 
                   4960: doc-@
                   4961: doc-!
                   4962: doc-+!
                   4963: doc-c@
                   4964: doc-c!
                   4965: doc-2@
                   4966: doc-2!
                   4967: doc-f@
                   4968: doc-f!
                   4969: doc-sf@
                   4970: doc-sf!
                   4971: doc-df@
                   4972: doc-df!
                   4973: 
1.68      anton    4974: 
1.32      anton    4975: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   4976: @subsection Address arithmetic
1.1       anton    4977: @cindex address arithmetic words
                   4978: 
1.67      anton    4979: Address arithmetic is the foundation on which you can build data
                   4980: structures like arrays, records (@pxref{Structures}) and objects
                   4981: (@pxref{Object-oriented Forth}).
1.32      anton    4982: 
1.68      anton    4983: @cindex address unit
                   4984: @cindex au (address unit)
1.1       anton    4985: ANS Forth does not specify the sizes of the data types. Instead, it
                   4986: offers a number of words for computing sizes and doing address
1.29      crook    4987: arithmetic. Address arithmetic is performed in terms of address units
                   4988: (aus); on most systems the address unit is one byte. Note that a
                   4989: character may have more than one au, so @code{chars} is no noop (on
1.68      anton    4990: platforms where it is a noop, it compiles to nothing).
1.1       anton    4991: 
1.67      anton    4992: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
                   4993: you have the address of a cell, perform @code{1 cells +}, and you will
                   4994: have the address of the next cell.
                   4995: 
1.68      anton    4996: @cindex contiguous regions and address arithmetic
1.67      anton    4997: In ANS Forth you can perform address arithmetic only within a contiguous
                   4998: region, i.e., if you have an address into one region, you can only add
                   4999: and subtract such that the result is still within the region; you can
                   5000: only subtract or compare addresses from within the same contiguous
                   5001: region.  Reasons: several contiguous regions can be arranged in memory
                   5002: in any way; on segmented systems addresses may have unusual
                   5003: representations, such that address arithmetic only works within a
                   5004: region.  Gforth provides a few more guarantees (linear address space,
                   5005: dictionary grows upwards), but in general I have found it easy to stay
                   5006: within contiguous regions (exception: computing and comparing to the
                   5007: address just beyond the end of an array).
                   5008: 
1.1       anton    5009: @cindex alignment of addresses for types
                   5010: ANS Forth also defines words for aligning addresses for specific
                   5011: types. Many computers require that accesses to specific data types
                   5012: must only occur at specific addresses; e.g., that cells may only be
                   5013: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   5014: accesses, it can usually perform aligned accesses faster. 
                   5015: 
                   5016: For the performance-conscious: alignment operations are usually only
                   5017: necessary during the definition of a data structure, not during the
                   5018: (more frequent) accesses to it.
                   5019: 
                   5020: ANS Forth defines no words for character-aligning addresses. This is not
                   5021: an oversight, but reflects the fact that addresses that are not
                   5022: char-aligned have no use in the standard and therefore will not be
                   5023: created.
                   5024: 
                   5025: @cindex @code{CREATE} and alignment
1.29      crook    5026: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    5027: are cell-aligned; in addition, Gforth guarantees that these addresses
                   5028: are aligned for all purposes.
                   5029: 
1.26      crook    5030: Note that the ANS Forth word @code{char} has nothing to do with address
                   5031: arithmetic.
1.1       anton    5032: 
1.44      crook    5033: 
1.1       anton    5034: doc-chars
                   5035: doc-char+
                   5036: doc-cells
                   5037: doc-cell+
                   5038: doc-cell
                   5039: doc-aligned
                   5040: doc-floats
                   5041: doc-float+
                   5042: doc-float
                   5043: doc-faligned
                   5044: doc-sfloats
                   5045: doc-sfloat+
                   5046: doc-sfaligned
                   5047: doc-dfloats
                   5048: doc-dfloat+
                   5049: doc-dfaligned
                   5050: doc-maxaligned
                   5051: doc-cfaligned
                   5052: doc-address-unit-bits
                   5053: 
1.44      crook    5054: 
1.32      anton    5055: @node Memory Blocks,  , Address arithmetic, Memory
1.1       anton    5056: @subsection Memory Blocks
                   5057: @cindex memory block words
1.27      crook    5058: @cindex character strings - moving and copying
                   5059: 
1.49      anton    5060: Memory blocks often represent character strings; For ways of storing
                   5061: character strings in memory see @ref{String Formats}.  For other
                   5062: string-processing words see @ref{Displaying characters and strings}.
1.1       anton    5063: 
1.67      anton    5064: A few of these words work on address unit blocks.  In that case, you
                   5065: usually have to insert @code{CHARS} before the word when working on
                   5066: character strings.  Most words work on character blocks, and expect a
                   5067: char-aligned address.
                   5068: 
                   5069: When copying characters between overlapping memory regions, use
                   5070: @code{chars move} or choose carefully between @code{cmove} and
                   5071: @code{cmove>}.
1.44      crook    5072: 
1.1       anton    5073: doc-move
                   5074: doc-erase
                   5075: doc-cmove
                   5076: doc-cmove>
                   5077: doc-fill
                   5078: doc-blank
1.21      crook    5079: doc-compare
1.111     anton    5080: doc-str=
                   5081: doc-str<
                   5082: doc-string-prefix?
1.21      crook    5083: doc-search
1.27      crook    5084: doc--trailing
                   5085: doc-/string
1.82      anton    5086: doc-bounds
1.44      crook    5087: 
1.111     anton    5088: 
1.27      crook    5089: @comment TODO examples
                   5090: 
1.1       anton    5091: 
1.26      crook    5092: @node Control Structures, Defining Words, Memory, Words
1.1       anton    5093: @section Control Structures
                   5094: @cindex control structures
                   5095: 
1.33      anton    5096: Control structures in Forth cannot be used interpretively, only in a
                   5097: colon definition@footnote{To be precise, they have no interpretation
                   5098: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
                   5099: not like this limitation, but have not seen a satisfying way around it
                   5100: yet, although many schemes have been proposed.
1.1       anton    5101: 
                   5102: @menu
1.33      anton    5103: * Selection::                   IF ... ELSE ... ENDIF
                   5104: * Simple Loops::                BEGIN ...
1.29      crook    5105: * Counted Loops::               DO
1.67      anton    5106: * Arbitrary control structures::  
                   5107: * Calls and returns::           
1.1       anton    5108: * Exception Handling::          
                   5109: @end menu
                   5110: 
                   5111: @node Selection, Simple Loops, Control Structures, Control Structures
                   5112: @subsection Selection
                   5113: @cindex selection control structures
                   5114: @cindex control structures for selection
                   5115: 
                   5116: @cindex @code{IF} control structure
                   5117: @example
1.29      crook    5118: @i{flag}
1.1       anton    5119: IF
1.29      crook    5120:   @i{code}
1.1       anton    5121: ENDIF
                   5122: @end example
1.21      crook    5123: @noindent
1.33      anton    5124: 
1.44      crook    5125: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
                   5126: with any bit set represents truth) @i{code} is executed.
1.33      anton    5127: 
1.1       anton    5128: @example
1.29      crook    5129: @i{flag}
1.1       anton    5130: IF
1.29      crook    5131:   @i{code1}
1.1       anton    5132: ELSE
1.29      crook    5133:   @i{code2}
1.1       anton    5134: ENDIF
                   5135: @end example
                   5136: 
1.44      crook    5137: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
                   5138: executed.
1.33      anton    5139: 
1.1       anton    5140: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   5141: standard, and @code{ENDIF} is not, although it is quite popular. We
                   5142: recommend using @code{ENDIF}, because it is less confusing for people
                   5143: who also know other languages (and is not prone to reinforcing negative
                   5144: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   5145: system that only supplies @code{THEN} is simple:
                   5146: @example
1.82      anton    5147: : ENDIF   POSTPONE then ; immediate
1.1       anton    5148: @end example
                   5149: 
                   5150: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   5151: (adv.)}  has the following meanings:
                   5152: @quotation
                   5153: ... 2b: following next after in order ... 3d: as a necessary consequence
                   5154: (if you were there, then you saw them).
                   5155: @end quotation
                   5156: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   5157: and many other programming languages has the meaning 3d.]
                   5158: 
1.21      crook    5159: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    5160: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    5161: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    5162: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   5163: @file{compat/control.fs}.
                   5164: 
                   5165: @cindex @code{CASE} control structure
                   5166: @example
1.29      crook    5167: @i{n}
1.1       anton    5168: CASE
1.29      crook    5169:   @i{n1} OF @i{code1} ENDOF
                   5170:   @i{n2} OF @i{code2} ENDOF
1.1       anton    5171:   @dots{}
1.68      anton    5172:   ( n ) @i{default-code} ( n )
1.1       anton    5173: ENDCASE
                   5174: @end example
                   5175: 
1.68      anton    5176: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If no
                   5177: @i{ni} matches, the optional @i{default-code} is executed. The optional
                   5178: default case can be added by simply writing the code after the last
                   5179: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
                   5180: not consume it.
1.1       anton    5181: 
1.69      anton    5182: @progstyle
                   5183: To keep the code understandable, you should ensure that on all paths
                   5184: through a selection construct the stack is changed in the same way
                   5185: (wrt. number and types of stack items consumed and pushed).
                   5186: 
1.1       anton    5187: @node Simple Loops, Counted Loops, Selection, Control Structures
                   5188: @subsection Simple Loops
                   5189: @cindex simple loops
                   5190: @cindex loops without count 
                   5191: 
                   5192: @cindex @code{WHILE} loop
                   5193: @example
                   5194: BEGIN
1.29      crook    5195:   @i{code1}
                   5196:   @i{flag}
1.1       anton    5197: WHILE
1.29      crook    5198:   @i{code2}
1.1       anton    5199: REPEAT
                   5200: @end example
                   5201: 
1.29      crook    5202: @i{code1} is executed and @i{flag} is computed. If it is true,
                   5203: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    5204: false, execution continues after the @code{REPEAT}.
                   5205: 
                   5206: @cindex @code{UNTIL} loop
                   5207: @example
                   5208: BEGIN
1.29      crook    5209:   @i{code}
                   5210:   @i{flag}
1.1       anton    5211: UNTIL
                   5212: @end example
                   5213: 
1.29      crook    5214: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    5215: 
1.69      anton    5216: @progstyle
                   5217: To keep the code understandable, a complete iteration of the loop should
                   5218: not change the number and types of the items on the stacks.
                   5219: 
1.1       anton    5220: @cindex endless loop
                   5221: @cindex loops, endless
                   5222: @example
                   5223: BEGIN
1.29      crook    5224:   @i{code}
1.1       anton    5225: AGAIN
                   5226: @end example
                   5227: 
                   5228: This is an endless loop.
                   5229: 
                   5230: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   5231: @subsection Counted Loops
                   5232: @cindex counted loops
                   5233: @cindex loops, counted
                   5234: @cindex @code{DO} loops
                   5235: 
                   5236: The basic counted loop is:
                   5237: @example
1.29      crook    5238: @i{limit} @i{start}
1.1       anton    5239: ?DO
1.29      crook    5240:   @i{body}
1.1       anton    5241: LOOP
                   5242: @end example
                   5243: 
1.29      crook    5244: This performs one iteration for every integer, starting from @i{start}
                   5245: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    5246: accessed with @code{i}. For example, the loop:
1.1       anton    5247: @example
                   5248: 10 0 ?DO
                   5249:   i .
                   5250: LOOP
                   5251: @end example
1.21      crook    5252: @noindent
                   5253: prints @code{0 1 2 3 4 5 6 7 8 9}
                   5254: 
1.1       anton    5255: The index of the innermost loop can be accessed with @code{i}, the index
                   5256: of the next loop with @code{j}, and the index of the third loop with
                   5257: @code{k}.
                   5258: 
1.44      crook    5259: 
1.1       anton    5260: doc-i
                   5261: doc-j
                   5262: doc-k
                   5263: 
1.44      crook    5264: 
1.1       anton    5265: The loop control data are kept on the return stack, so there are some
1.21      crook    5266: restrictions on mixing return stack accesses and counted loop words. In
                   5267: particuler, if you put values on the return stack outside the loop, you
                   5268: cannot read them inside the loop@footnote{well, not in a way that is
                   5269: portable.}. If you put values on the return stack within a loop, you
                   5270: have to remove them before the end of the loop and before accessing the
                   5271: index of the loop.
1.1       anton    5272: 
                   5273: There are several variations on the counted loop:
                   5274: 
1.21      crook    5275: @itemize @bullet
                   5276: @item
                   5277: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   5278: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   5279: 
                   5280: @example
                   5281: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   5282: @end example
                   5283: prints @code{0 1 2 3}
                   5284: 
1.1       anton    5285: 
1.21      crook    5286: @item
                   5287: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   5288: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   5289: return stack so @code{EXIT} can get to its return address. For example:
                   5290: 
                   5291: @example
                   5292: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   5293: @end example
                   5294: prints @code{0 1 2 3}
                   5295: 
                   5296: 
                   5297: @item
1.29      crook    5298: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    5299: (and @code{LOOP} iterates until they become equal by wrap-around
                   5300: arithmetic). This behaviour is usually not what you want. Therefore,
                   5301: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    5302: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   5303: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    5304: unsigned loop parameters.
                   5305: 
1.21      crook    5306: @item
                   5307: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   5308: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   5309: if you know that the loop is entered in any case. Such knowledge tends
                   5310: to become invalid during maintenance of a program, and then the
                   5311: @code{DO} will make trouble.
                   5312: 
                   5313: @item
1.29      crook    5314: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   5315: index by @i{n} instead of by 1. The loop is terminated when the border
                   5316: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    5317: 
1.21      crook    5318: @example
                   5319: 4 0 +DO  i .  2 +LOOP
                   5320: @end example
                   5321: @noindent
                   5322: prints @code{0 2}
                   5323: 
                   5324: @example
                   5325: 4 1 +DO  i .  2 +LOOP
                   5326: @end example
                   5327: @noindent
                   5328: prints @code{1 3}
1.1       anton    5329: 
1.68      anton    5330: @item
1.1       anton    5331: @cindex negative increment for counted loops
                   5332: @cindex counted loops with negative increment
1.29      crook    5333: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    5334: 
1.21      crook    5335: @example
                   5336: -1 0 ?DO  i .  -1 +LOOP
                   5337: @end example
                   5338: @noindent
                   5339: prints @code{0 -1}
1.1       anton    5340: 
1.21      crook    5341: @example
                   5342: 0 0 ?DO  i .  -1 +LOOP
                   5343: @end example
                   5344: prints nothing.
1.1       anton    5345: 
1.29      crook    5346: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   5347: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   5348: index by @i{u} each iteration. The loop is terminated when the border
                   5349: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    5350: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   5351: 
1.21      crook    5352: @example
                   5353: -2 0 -DO  i .  1 -LOOP
                   5354: @end example
                   5355: @noindent
                   5356: prints @code{0 -1}
1.1       anton    5357: 
1.21      crook    5358: @example
                   5359: -1 0 -DO  i .  1 -LOOP
                   5360: @end example
                   5361: @noindent
                   5362: prints @code{0}
                   5363: 
                   5364: @example
                   5365: 0 0 -DO  i .  1 -LOOP
                   5366: @end example
                   5367: @noindent
                   5368: prints nothing.
1.1       anton    5369: 
1.21      crook    5370: @end itemize
1.1       anton    5371: 
                   5372: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    5373: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   5374: for these words that uses only standard words is provided in
                   5375: @file{compat/loops.fs}.
1.1       anton    5376: 
                   5377: 
                   5378: @cindex @code{FOR} loops
1.26      crook    5379: Another counted loop is:
1.1       anton    5380: @example
1.29      crook    5381: @i{n}
1.1       anton    5382: FOR
1.29      crook    5383:   @i{body}
1.1       anton    5384: NEXT
                   5385: @end example
                   5386: This is the preferred loop of native code compiler writers who are too
1.26      crook    5387: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    5388: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   5389: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    5390: Forth systems may behave differently, even if they support @code{FOR}
                   5391: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    5392: 
                   5393: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   5394: @subsection Arbitrary control structures
                   5395: @cindex control structures, user-defined
                   5396: 
                   5397: @cindex control-flow stack
                   5398: ANS Forth permits and supports using control structures in a non-nested
                   5399: way. Information about incomplete control structures is stored on the
                   5400: control-flow stack. This stack may be implemented on the Forth data
                   5401: stack, and this is what we have done in Gforth.
                   5402: 
                   5403: @cindex @code{orig}, control-flow stack item
                   5404: @cindex @code{dest}, control-flow stack item
                   5405: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   5406: entry represents a backward branch target. A few words are the basis for
                   5407: building any control structure possible (except control structures that
                   5408: need storage, like calls, coroutines, and backtracking).
                   5409: 
1.44      crook    5410: 
1.1       anton    5411: doc-if
                   5412: doc-ahead
                   5413: doc-then
                   5414: doc-begin
                   5415: doc-until
                   5416: doc-again
                   5417: doc-cs-pick
                   5418: doc-cs-roll
                   5419: 
1.44      crook    5420: 
1.21      crook    5421: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   5422: manipulate the control-flow stack in a portable way. Without them, you
                   5423: would need to know how many stack items are occupied by a control-flow
                   5424: entry (many systems use one cell. In Gforth they currently take three,
                   5425: but this may change in the future).
                   5426: 
1.1       anton    5427: Some standard control structure words are built from these words:
                   5428: 
1.44      crook    5429: 
1.1       anton    5430: doc-else
                   5431: doc-while
                   5432: doc-repeat
                   5433: 
1.44      crook    5434: 
                   5435: @noindent
1.1       anton    5436: Gforth adds some more control-structure words:
                   5437: 
1.44      crook    5438: 
1.1       anton    5439: doc-endif
                   5440: doc-?dup-if
                   5441: doc-?dup-0=-if
                   5442: 
1.44      crook    5443: 
                   5444: @noindent
1.1       anton    5445: Counted loop words constitute a separate group of words:
                   5446: 
1.44      crook    5447: 
1.1       anton    5448: doc-?do
                   5449: doc-+do
                   5450: doc-u+do
                   5451: doc--do
                   5452: doc-u-do
                   5453: doc-do
                   5454: doc-for
                   5455: doc-loop
                   5456: doc-+loop
                   5457: doc--loop
                   5458: doc-next
                   5459: doc-leave
                   5460: doc-?leave
                   5461: doc-unloop
                   5462: doc-done
                   5463: 
1.44      crook    5464: 
1.21      crook    5465: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   5466: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    5467: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   5468: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   5469: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   5470: resolved (by using one of the loop-ending words or @code{DONE}).
                   5471: 
1.44      crook    5472: @noindent
1.26      crook    5473: Another group of control structure words are:
1.1       anton    5474: 
1.44      crook    5475: 
1.1       anton    5476: doc-case
                   5477: doc-endcase
                   5478: doc-of
                   5479: doc-endof
                   5480: 
1.44      crook    5481: 
1.21      crook    5482: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   5483: @code{CS-ROLL}.
1.1       anton    5484: 
                   5485: @subsubsection Programming Style
1.47      crook    5486: @cindex control structures programming style
                   5487: @cindex programming style, arbitrary control structures
1.1       anton    5488: 
                   5489: In order to ensure readability we recommend that you do not create
                   5490: arbitrary control structures directly, but define new control structure
                   5491: words for the control structure you want and use these words in your
1.26      crook    5492: program. For example, instead of writing:
1.1       anton    5493: 
                   5494: @example
1.26      crook    5495: BEGIN
1.1       anton    5496:   ...
1.26      crook    5497: IF [ 1 CS-ROLL ]
1.1       anton    5498:   ...
1.26      crook    5499: AGAIN THEN
1.1       anton    5500: @end example
                   5501: 
1.21      crook    5502: @noindent
1.1       anton    5503: we recommend defining control structure words, e.g.,
                   5504: 
                   5505: @example
1.26      crook    5506: : WHILE ( DEST -- ORIG DEST )
                   5507:  POSTPONE IF
                   5508:  1 CS-ROLL ; immediate
                   5509: 
                   5510: : REPEAT ( orig dest -- )
                   5511:  POSTPONE AGAIN
                   5512:  POSTPONE THEN ; immediate
1.1       anton    5513: @end example
                   5514: 
1.21      crook    5515: @noindent
1.1       anton    5516: and then using these to create the control structure:
                   5517: 
                   5518: @example
1.26      crook    5519: BEGIN
1.1       anton    5520:   ...
1.26      crook    5521: WHILE
1.1       anton    5522:   ...
1.26      crook    5523: REPEAT
1.1       anton    5524: @end example
                   5525: 
                   5526: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   5527: @code{WHILE} are predefined, so in this example it would not be
                   5528: necessary to define them.
                   5529: 
                   5530: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   5531: @subsection Calls and returns
                   5532: @cindex calling a definition
                   5533: @cindex returning from a definition
                   5534: 
1.3       anton    5535: @cindex recursive definitions
                   5536: A definition can be called simply be writing the name of the definition
1.26      crook    5537: to be called. Normally a definition is invisible during its own
1.3       anton    5538: definition. If you want to write a directly recursive definition, you
1.26      crook    5539: can use @code{recursive} to make the current definition visible, or
                   5540: @code{recurse} to call the current definition directly.
1.3       anton    5541: 
1.44      crook    5542: 
1.3       anton    5543: doc-recursive
                   5544: doc-recurse
                   5545: 
1.44      crook    5546: 
1.21      crook    5547: @comment TODO add example of the two recursion methods
1.12      anton    5548: @quotation
                   5549: @progstyle
                   5550: I prefer using @code{recursive} to @code{recurse}, because calling the
                   5551: definition by name is more descriptive (if the name is well-chosen) than
                   5552: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   5553: implementation, it is much better to read (and think) ``now sort the
                   5554: partitions'' than to read ``now do a recursive call''.
                   5555: @end quotation
1.3       anton    5556: 
1.29      crook    5557: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    5558: 
                   5559: @example
1.28      crook    5560: Defer foo
1.3       anton    5561: 
                   5562: : bar ( ... -- ... )
                   5563:  ... foo ... ;
                   5564: 
                   5565: :noname ( ... -- ... )
                   5566:  ... bar ... ;
                   5567: IS foo
                   5568: @end example
                   5569: 
1.44      crook    5570: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33      anton    5571: 
1.26      crook    5572: The current definition returns control to the calling definition when
1.33      anton    5573: the end of the definition is reached or @code{EXIT} is encountered.
1.1       anton    5574: 
                   5575: doc-exit
                   5576: doc-;s
                   5577: 
1.44      crook    5578: 
1.1       anton    5579: @node Exception Handling,  , Calls and returns, Control Structures
                   5580: @subsection Exception Handling
1.26      crook    5581: @cindex exceptions
1.1       anton    5582: 
1.68      anton    5583: @c quit is a very bad idea for error handling, 
                   5584: @c because it does not translate into a THROW
                   5585: @c it also does not belong into this chapter
                   5586: 
                   5587: If a word detects an error condition that it cannot handle, it can
                   5588: @code{throw} an exception.  In the simplest case, this will terminate
                   5589: your program, and report an appropriate error.
1.21      crook    5590: 
1.68      anton    5591: doc-throw
1.1       anton    5592: 
1.69      anton    5593: @code{Throw} consumes a cell-sized error number on the stack. There are
                   5594: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
                   5595: Gforth (and most other systems) you can use the iors produced by various
                   5596: words as error numbers (e.g., a typical use of @code{allocate} is
                   5597: @code{allocate throw}).  Gforth also provides the word @code{exception}
                   5598: to define your own error numbers (with decent error reporting); an ANS
                   5599: Forth version of this word (but without the error messages) is available
                   5600: in @code{compat/except.fs}.  And finally, you can use your own error
1.68      anton    5601: numbers (anything outside the range -4095..0), but won't get nice error
                   5602: messages, only numbers.  For example, try:
                   5603: 
                   5604: @example
1.69      anton    5605: -10 throw                    \ ANS defined
                   5606: -267 throw                   \ system defined
                   5607: s" my error" exception throw \ user defined
                   5608: 7 throw                      \ arbitrary number
1.68      anton    5609: @end example
                   5610: 
                   5611: doc---exception-exception
1.1       anton    5612: 
1.69      anton    5613: A common idiom to @code{THROW} a specific error if a flag is true is
                   5614: this:
                   5615: 
                   5616: @example
                   5617: @code{( flag ) 0<> @i{errno} and throw}
                   5618: @end example
                   5619: 
                   5620: Your program can provide exception handlers to catch exceptions.  An
                   5621: exception handler can be used to correct the problem, or to clean up
                   5622: some data structures and just throw the exception to the next exception
                   5623: handler.  Note that @code{throw} jumps to the dynamically innermost
                   5624: exception handler.  The system's exception handler is outermost, and just
                   5625: prints an error and restarts command-line interpretation (or, in batch
                   5626: mode (i.e., while processing the shell command line), leaves Gforth).
1.1       anton    5627: 
1.68      anton    5628: The ANS Forth way to catch exceptions is @code{catch}:
1.1       anton    5629: 
1.68      anton    5630: doc-catch
                   5631: 
                   5632: The most common use of exception handlers is to clean up the state when
                   5633: an error happens.  E.g.,
1.1       anton    5634: 
1.26      crook    5635: @example
1.68      anton    5636: base @ >r hex \ actually the hex should be inside foo, or we h
                   5637: ['] foo catch ( nerror|0 )
                   5638: r> base !
1.69      anton    5639: ( nerror|0 ) throw \ pass it on
1.26      crook    5640: @end example
1.1       anton    5641: 
1.69      anton    5642: A use of @code{catch} for handling the error @code{myerror} might look
                   5643: like this:
1.44      crook    5644: 
1.68      anton    5645: @example
1.69      anton    5646: ['] foo catch
                   5647: CASE
                   5648:   myerror OF ... ( do something about it ) ENDOF
                   5649:   dup throw \ default: pass other errors on, do nothing on non-errors
                   5650: ENDCASE
1.68      anton    5651: @end example
1.44      crook    5652: 
1.68      anton    5653: Having to wrap the code into a separate word is often cumbersome,
                   5654: therefore Gforth provides an alternative syntax:
1.1       anton    5655: 
                   5656: @example
1.69      anton    5657: TRY
1.68      anton    5658:   @i{code1}
1.69      anton    5659: RECOVER     \ optional
1.68      anton    5660:   @i{code2} \ optional
1.69      anton    5661: ENDTRY
1.1       anton    5662: @end example
                   5663: 
1.68      anton    5664: This performs @i{Code1}.  If @i{code1} completes normally, execution
                   5665: continues after the @code{endtry}.  If @i{Code1} throws, the stacks are
                   5666: reset to the state during @code{try}, the throw value is pushed on the
                   5667: data stack, and execution constinues at @i{code2}, and finally falls
1.92      anton    5668: through the @code{endtry} into the following code.
1.26      crook    5669: 
1.68      anton    5670: doc-try
                   5671: doc-recover
                   5672: doc-endtry
1.26      crook    5673: 
1.69      anton    5674: The cleanup example from above in this syntax:
1.26      crook    5675: 
1.68      anton    5676: @example
1.69      anton    5677: base @ >r TRY
1.68      anton    5678:   hex foo \ now the hex is placed correctly
1.69      anton    5679:   0       \ value for throw
1.92      anton    5680: RECOVER ENDTRY
1.68      anton    5681: r> base ! throw
1.1       anton    5682: @end example
                   5683: 
1.69      anton    5684: And here's the error handling example:
1.1       anton    5685: 
1.68      anton    5686: @example
1.69      anton    5687: TRY
1.68      anton    5688:   foo
1.69      anton    5689: RECOVER
                   5690:   CASE
                   5691:     myerror OF ... ( do something about it ) ENDOF
                   5692:     throw \ pass other errors on
                   5693:   ENDCASE
                   5694: ENDTRY
1.68      anton    5695: @end example
1.1       anton    5696: 
1.69      anton    5697: @progstyle
                   5698: As usual, you should ensure that the stack depth is statically known at
                   5699: the end: either after the @code{throw} for passing on errors, or after
                   5700: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
                   5701: selection construct for handling the error).
                   5702: 
1.68      anton    5703: There are two alternatives to @code{throw}: @code{Abort"} is conditional
                   5704: and you can provide an error message.  @code{Abort} just produces an
                   5705: ``Aborted'' error.
1.1       anton    5706: 
1.68      anton    5707: The problem with these words is that exception handlers cannot
                   5708: differentiate between different @code{abort"}s; they just look like
                   5709: @code{-2 throw} to them (the error message cannot be accessed by
                   5710: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
                   5711: exception handlers.
1.44      crook    5712: 
1.68      anton    5713: doc-abort"
1.26      crook    5714: doc-abort
1.29      crook    5715: 
                   5716: 
1.44      crook    5717: 
1.29      crook    5718: @c -------------------------------------------------------------
1.47      crook    5719: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29      crook    5720: @section Defining Words
                   5721: @cindex defining words
                   5722: 
1.47      crook    5723: Defining words are used to extend Forth by creating new entries in the dictionary.
                   5724: 
1.29      crook    5725: @menu
1.67      anton    5726: * CREATE::                      
1.44      crook    5727: * Variables::                   Variables and user variables
1.67      anton    5728: * Constants::                   
1.44      crook    5729: * Values::                      Initialised variables
1.67      anton    5730: * Colon Definitions::           
1.44      crook    5731: * Anonymous Definitions::       Definitions without names
1.69      anton    5732: * Supplying names::             Passing definition names as strings
1.67      anton    5733: * User-defined Defining Words::  
1.44      crook    5734: * Deferred words::              Allow forward references
1.67      anton    5735: * Aliases::                     
1.29      crook    5736: @end menu
                   5737: 
1.44      crook    5738: @node CREATE, Variables, Defining Words, Defining Words
                   5739: @subsection @code{CREATE}
1.29      crook    5740: @cindex simple defining words
                   5741: @cindex defining words, simple
                   5742: 
                   5743: Defining words are used to create new entries in the dictionary. The
                   5744: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   5745: this:
                   5746: 
                   5747: @example
                   5748: CREATE new-word1
                   5749: @end example
                   5750: 
1.69      anton    5751: @code{CREATE} is a parsing word, i.e., it takes an argument from the
                   5752: input stream (@code{new-word1} in our example).  It generates a
                   5753: dictionary entry for @code{new-word1}. When @code{new-word1} is
                   5754: executed, all that it does is leave an address on the stack. The address
                   5755: represents the value of the data space pointer (@code{HERE}) at the time
                   5756: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
                   5757: associating a name with the address of a region of memory.
1.29      crook    5758: 
1.34      anton    5759: doc-create
                   5760: 
1.69      anton    5761: Note that in ANS Forth guarantees only for @code{create} that its body
                   5762: is in dictionary data space (i.e., where @code{here}, @code{allot}
                   5763: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
                   5764: @code{create}d words can be modified with @code{does>}
                   5765: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
                   5766: can only be applied to @code{create}d words.
                   5767: 
1.29      crook    5768: By extending this example to reserve some memory in data space, we end
1.69      anton    5769: up with something like a @i{variable}. Here are two different ways to do
                   5770: it:
1.29      crook    5771: 
                   5772: @example
                   5773: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   5774: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   5775: @end example
                   5776: 
                   5777: The variable can be examined and modified using @code{@@} (``fetch'') and
                   5778: @code{!} (``store'') like this:
                   5779: 
                   5780: @example
                   5781: new-word2 @@ .      \ get address, fetch from it and display
                   5782: 1234 new-word2 !   \ new value, get address, store to it
                   5783: @end example
                   5784: 
1.44      crook    5785: @cindex arrays
                   5786: A similar mechanism can be used to create arrays. For example, an
                   5787: 80-character text input buffer:
1.29      crook    5788: 
                   5789: @example
1.44      crook    5790: CREATE text-buf 80 chars allot
                   5791: 
                   5792: text-buf 0 chars c@@ \ the 1st character (offset 0)
                   5793: text-buf 3 chars c@@ \ the 4th character (offset 3)
                   5794: @end example
1.29      crook    5795: 
1.44      crook    5796: You can build arbitrarily complex data structures by allocating
1.49      anton    5797: appropriate areas of memory. For further discussions of this, and to
1.66      anton    5798: learn about some Gforth tools that make it easier,
1.49      anton    5799: @xref{Structures}.
1.44      crook    5800: 
                   5801: 
                   5802: @node Variables, Constants, CREATE, Defining Words
                   5803: @subsection Variables
                   5804: @cindex variables
                   5805: 
                   5806: The previous section showed how a sequence of commands could be used to
                   5807: generate a variable.  As a final refinement, the whole code sequence can
                   5808: be wrapped up in a defining word (pre-empting the subject of the next
                   5809: section), making it easier to create new variables:
                   5810: 
                   5811: @example
                   5812: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
                   5813: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
                   5814: 
                   5815: myvariableX foo \ variable foo starts off with an unknown value
                   5816: myvariable0 joe \ whilst joe is initialised to 0
1.29      crook    5817: 
                   5818: 45 3 * foo !   \ set foo to 135
                   5819: 1234 joe !     \ set joe to 1234
                   5820: 3 joe +!       \ increment joe by 3.. to 1237
                   5821: @end example
                   5822: 
                   5823: Not surprisingly, there is no need to define @code{myvariable}, since
1.44      crook    5824: Forth already has a definition @code{Variable}. ANS Forth does not
1.69      anton    5825: guarantee that a @code{Variable} is initialised when it is created
                   5826: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
                   5827: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
                   5828: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47      crook    5829: @code{fvariable} for double and floating-point variables, respectively
1.69      anton    5830: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47      crook    5831: store a boolean, you can use @code{on} and @code{off} to toggle its
                   5832: state.
1.29      crook    5833: 
1.34      anton    5834: doc-variable
                   5835: doc-2variable
                   5836: doc-fvariable
                   5837: 
1.29      crook    5838: @cindex user variables
                   5839: @cindex user space
                   5840: The defining word @code{User} behaves in the same way as @code{Variable}.
                   5841: The difference is that it reserves space in @i{user (data) space} rather
                   5842: than normal data space. In a Forth system that has a multi-tasker, each
                   5843: task has its own set of user variables.
                   5844: 
1.34      anton    5845: doc-user
1.67      anton    5846: @c doc-udp
                   5847: @c doc-uallot
1.34      anton    5848: 
1.29      crook    5849: @comment TODO is that stuff about user variables strictly correct? Is it
                   5850: @comment just terminal tasks that have user variables?
                   5851: @comment should document tasker.fs (with some examples) elsewhere
                   5852: @comment in this manual, then expand on user space and user variables.
                   5853: 
1.44      crook    5854: @node Constants, Values, Variables, Defining Words
                   5855: @subsection Constants
                   5856: @cindex constants
                   5857: 
                   5858: @code{Constant} allows you to declare a fixed value and refer to it by
                   5859: name. For example:
1.29      crook    5860: 
                   5861: @example
                   5862: 12 Constant INCHES-PER-FOOT
                   5863: 3E+08 fconstant SPEED-O-LIGHT
                   5864: @end example
                   5865: 
                   5866: A @code{Variable} can be both read and written, so its run-time
                   5867: behaviour is to supply an address through which its current value can be
                   5868: manipulated. In contrast, the value of a @code{Constant} cannot be
                   5869: changed once it has been declared@footnote{Well, often it can be -- but
                   5870: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   5871: on).} so it's not necessary to supply the address -- it is more
                   5872: efficient to return the value of the constant directly. That's exactly
                   5873: what happens; the run-time effect of a constant is to put its value on
1.49      anton    5874: the top of the stack (You can find one
                   5875: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29      crook    5876: 
1.69      anton    5877: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29      crook    5878: double and floating-point constants, respectively.
                   5879: 
1.34      anton    5880: doc-constant
                   5881: doc-2constant
                   5882: doc-fconstant
                   5883: 
                   5884: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44      crook    5885: @c nac-> How could that not be true in an ANS Forth? You can't define a
                   5886: @c constant, use it and then delete the definition of the constant..
1.69      anton    5887: 
                   5888: @c anton->An ANS Forth system can compile a constant to a literal; On
                   5889: @c decompilation you would see only the number, just as if it had been used
                   5890: @c in the first place.  The word will stay, of course, but it will only be
                   5891: @c used by the text interpreter (no run-time duties, except when it is 
                   5892: @c POSTPONEd or somesuch).
                   5893: 
                   5894: @c nac:
1.44      crook    5895: @c I agree that it's rather deep, but IMO it is an important difference
                   5896: @c relative to other programming languages.. often it's annoying: it
                   5897: @c certainly changes my programming style relative to C.
                   5898: 
1.69      anton    5899: @c anton: In what way?
                   5900: 
1.29      crook    5901: Constants in Forth behave differently from their equivalents in other
                   5902: programming languages. In other languages, a constant (such as an EQU in
                   5903: assembler or a #define in C) only exists at compile-time; in the
                   5904: executable program the constant has been translated into an absolute
                   5905: number and, unless you are using a symbolic debugger, it's impossible to
                   5906: know what abstract thing that number represents. In Forth a constant has
1.44      crook    5907: an entry in the header space and remains there after the code that uses
                   5908: it has been defined. In fact, it must remain in the dictionary since it
                   5909: has run-time duties to perform. For example:
1.29      crook    5910: 
                   5911: @example
                   5912: 12 Constant INCHES-PER-FOOT
                   5913: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   5914: @end example
                   5915: 
                   5916: @cindex in-lining of constants
                   5917: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   5918: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   5919: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   5920: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   5921: attempt to optimise constants by in-lining them where they are used. You
                   5922: can force Gforth to in-line a constant like this:
                   5923: 
                   5924: @example
                   5925: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   5926: @end example
                   5927: 
                   5928: If you use @code{see} to decompile @i{this} version of
                   5929: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49      anton    5930: longer present. To understand how this works, read
                   5931: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29      crook    5932: 
                   5933: In-lining constants in this way might improve execution time
                   5934: fractionally, and can ensure that a constant is now only referenced at
                   5935: compile-time. However, the definition of the constant still remains in
                   5936: the dictionary. Some Forth compilers provide a mechanism for controlling
                   5937: a second dictionary for holding transient words such that this second
                   5938: dictionary can be deleted later in order to recover memory
                   5939: space. However, there is no standard way of doing this.
                   5940: 
                   5941: 
1.44      crook    5942: @node Values, Colon Definitions, Constants, Defining Words
                   5943: @subsection Values
                   5944: @cindex values
1.34      anton    5945: 
1.69      anton    5946: A @code{Value} behaves like a @code{Constant}, but it can be changed.
                   5947: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
                   5948: (not in ANS Forth) you can access (and change) a @code{value} also with
                   5949: @code{>body}.
                   5950: 
                   5951: Here are some
                   5952: examples:
1.29      crook    5953: 
                   5954: @example
1.69      anton    5955: 12 Value APPLES     \ Define APPLES with an initial value of 12
                   5956: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
                   5957: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
                   5958: APPLES              \ puts 35 on the top of the stack.
1.29      crook    5959: @end example
                   5960: 
1.44      crook    5961: doc-value
                   5962: doc-to
1.29      crook    5963: 
1.35      anton    5964: 
1.69      anton    5965: 
1.44      crook    5966: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
                   5967: @subsection Colon Definitions
                   5968: @cindex colon definitions
1.35      anton    5969: 
                   5970: @example
1.44      crook    5971: : name ( ... -- ... )
                   5972:     word1 word2 word3 ;
1.29      crook    5973: @end example
                   5974: 
1.44      crook    5975: @noindent
                   5976: Creates a word called @code{name} that, upon execution, executes
                   5977: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29      crook    5978: 
1.49      anton    5979: The explanation above is somewhat superficial. For simple examples of
                   5980: colon definitions see @ref{Your first definition}.  For an in-depth
1.66      anton    5981: discussion of some of the issues involved, @xref{Interpretation and
1.49      anton    5982: Compilation Semantics}.
1.29      crook    5983: 
1.44      crook    5984: doc-:
                   5985: doc-;
1.1       anton    5986: 
1.34      anton    5987: 
1.69      anton    5988: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44      crook    5989: @subsection Anonymous Definitions
                   5990: @cindex colon definitions
                   5991: @cindex defining words without name
1.34      anton    5992: 
1.44      crook    5993: Sometimes you want to define an @dfn{anonymous word}; a word without a
                   5994: name. You can do this with:
1.1       anton    5995: 
1.44      crook    5996: doc-:noname
1.1       anton    5997: 
1.44      crook    5998: This leaves the execution token for the word on the stack after the
                   5999: closing @code{;}. Here's an example in which a deferred word is
                   6000: initialised with an @code{xt} from an anonymous colon definition:
1.1       anton    6001: 
1.29      crook    6002: @example
1.44      crook    6003: Defer deferred
                   6004: :noname ( ... -- ... )
                   6005:   ... ;
                   6006: IS deferred
1.29      crook    6007: @end example
1.26      crook    6008: 
1.44      crook    6009: @noindent
                   6010: Gforth provides an alternative way of doing this, using two separate
                   6011: words:
1.27      crook    6012: 
1.44      crook    6013: doc-noname
                   6014: @cindex execution token of last defined word
1.116     anton    6015: doc-latestxt
1.1       anton    6016: 
1.44      crook    6017: @noindent
                   6018: The previous example can be rewritten using @code{noname} and
1.116     anton    6019: @code{latestxt}:
1.1       anton    6020: 
1.26      crook    6021: @example
1.44      crook    6022: Defer deferred
                   6023: noname : ( ... -- ... )
                   6024:   ... ;
1.116     anton    6025: latestxt IS deferred
1.26      crook    6026: @end example
1.1       anton    6027: 
1.29      crook    6028: @noindent
1.44      crook    6029: @code{noname} works with any defining word, not just @code{:}.
                   6030: 
1.116     anton    6031: @code{latestxt} also works when the last word was not defined as
1.71      anton    6032: @code{noname}.  It does not work for combined words, though.  It also has
                   6033: the useful property that is is valid as soon as the header for a
                   6034: definition has been built. Thus:
1.44      crook    6035: 
                   6036: @example
1.116     anton    6037: latestxt . : foo [ latestxt . ] ; ' foo .
1.44      crook    6038: @end example
1.1       anton    6039: 
1.44      crook    6040: @noindent
                   6041: prints 3 numbers; the last two are the same.
1.26      crook    6042: 
1.69      anton    6043: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
                   6044: @subsection Supplying the name of a defined word
                   6045: @cindex names for defined words
                   6046: @cindex defining words, name given in a string
                   6047: 
                   6048: By default, a defining word takes the name for the defined word from the
                   6049: input stream. Sometimes you want to supply the name from a string. You
                   6050: can do this with:
                   6051: 
                   6052: doc-nextname
                   6053: 
                   6054: For example:
                   6055: 
                   6056: @example
                   6057: s" foo" nextname create
                   6058: @end example
                   6059: 
                   6060: @noindent
                   6061: is equivalent to:
                   6062: 
                   6063: @example
                   6064: create foo
                   6065: @end example
                   6066: 
                   6067: @noindent
                   6068: @code{nextname} works with any defining word.
                   6069: 
1.1       anton    6070: 
1.69      anton    6071: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26      crook    6072: @subsection User-defined Defining Words
                   6073: @cindex user-defined defining words
                   6074: @cindex defining words, user-defined
1.1       anton    6075: 
1.29      crook    6076: You can create a new defining word by wrapping defining-time code around
                   6077: an existing defining word and putting the sequence in a colon
1.69      anton    6078: definition. 
                   6079: 
                   6080: @c anton: This example is very complex and leads in a quite different
                   6081: @c direction from the CREATE-DOES> stuff that follows.  It should probably
                   6082: @c be done elsewhere, or as a subsubsection of this subsection (or as a
                   6083: @c subsection of Defining Words)
                   6084: 
                   6085: For example, suppose that you have a word @code{stats} that
1.29      crook    6086: gathers statistics about colon definitions given the @i{xt} of the
                   6087: definition, and you want every colon definition in your application to
                   6088: make a call to @code{stats}. You can define and use a new version of
                   6089: @code{:} like this:
                   6090: 
                   6091: @example
                   6092: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   6093:   ... ;  \ other code
                   6094: 
1.116     anton    6095: : my: : latestxt postpone literal ['] stats compile, ;
1.29      crook    6096: 
                   6097: my: foo + - ;
                   6098: @end example
                   6099: 
                   6100: When @code{foo} is defined using @code{my:} these steps occur:
                   6101: 
                   6102: @itemize @bullet
                   6103: @item
                   6104: @code{my:} is executed.
                   6105: @item
                   6106: The @code{:} within the definition (the one between @code{my:} and
1.116     anton    6107: @code{latestxt}) is executed, and does just what it always does; it parses
1.29      crook    6108: the input stream for a name, builds a dictionary header for the name
                   6109: @code{foo} and switches @code{state} from interpret to compile.
                   6110: @item
1.116     anton    6111: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29      crook    6112: being defined -- @code{foo} -- onto the stack.
                   6113: @item
                   6114: The code that was produced by @code{postpone literal} is executed; this
                   6115: causes the value on the stack to be compiled as a literal in the code
                   6116: area of @code{foo}.
                   6117: @item
                   6118: The code @code{['] stats} compiles a literal into the definition of
                   6119: @code{my:}. When @code{compile,} is executed, that literal -- the
                   6120: execution token for @code{stats} -- is layed down in the code area of
                   6121: @code{foo} , following the literal@footnote{Strictly speaking, the
                   6122: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   6123: in the code area is implementation-dependent. A threaded implementation
                   6124: might spit out the execution token directly whilst another
                   6125: implementation might spit out a native code sequence.}.
                   6126: @item
                   6127: At this point, the execution of @code{my:} is complete, and control
                   6128: returns to the text interpreter. The text interpreter is in compile
                   6129: state, so subsequent text @code{+ -} is compiled into the definition of
                   6130: @code{foo} and the @code{;} terminates the definition as always.
                   6131: @end itemize
                   6132: 
                   6133: You can use @code{see} to decompile a word that was defined using
                   6134: @code{my:} and see how it is different from a normal @code{:}
                   6135: definition. For example:
                   6136: 
                   6137: @example
                   6138: : bar + - ;  \ like foo but using : rather than my:
                   6139: see bar
                   6140: : bar
                   6141:   + - ;
                   6142: see foo
                   6143: : foo
                   6144:   107645672 stats + - ;
                   6145: 
                   6146: \ use ' stats . to show that 107645672 is the xt for stats
                   6147: @end example
                   6148: 
                   6149: You can use techniques like this to make new defining words in terms of
                   6150: @i{any} existing defining word.
1.1       anton    6151: 
                   6152: 
1.29      crook    6153: @cindex defining defining words
1.26      crook    6154: @cindex @code{CREATE} ... @code{DOES>}
                   6155: If you want the words defined with your defining words to behave
                   6156: differently from words defined with standard defining words, you can
                   6157: write your defining word like this:
1.1       anton    6158: 
                   6159: @example
1.26      crook    6160: : def-word ( "name" -- )
1.29      crook    6161:     CREATE @i{code1}
1.26      crook    6162: DOES> ( ... -- ... )
1.29      crook    6163:     @i{code2} ;
1.26      crook    6164: 
                   6165: def-word name
1.1       anton    6166: @end example
                   6167: 
1.29      crook    6168: @cindex child words
                   6169: This fragment defines a @dfn{defining word} @code{def-word} and then
                   6170: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   6171: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   6172: is not executed at this time. The word @code{name} is sometimes called a
                   6173: @dfn{child} of @code{def-word}.
                   6174: 
                   6175: When you execute @code{name}, the address of the body of @code{name} is
                   6176: put on the data stack and @i{code2} is executed (the address of the body
                   6177: of @code{name} is the address @code{HERE} returns immediately after the
1.69      anton    6178: @code{CREATE}, i.e., the address a @code{create}d word returns by
                   6179: default).
                   6180: 
                   6181: @c anton:
                   6182: @c www.dictionary.com says:
                   6183: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
                   6184: @c several generations of absence, usually caused by the chance
                   6185: @c recombination of genes.  2.An individual or a part that exhibits
                   6186: @c atavism. Also called throwback.  3.The return of a trait or recurrence
                   6187: @c of previous behavior after a period of absence.
                   6188: @c
                   6189: @c Doesn't seem to fit.
1.29      crook    6190: 
1.69      anton    6191: @c @cindex atavism in child words
1.33      anton    6192: You can use @code{def-word} to define a set of child words that behave
1.69      anton    6193: similarly; they all have a common run-time behaviour determined by
                   6194: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
                   6195: body of the child word. The structure of the data is common to all
                   6196: children of @code{def-word}, but the data values are specific -- and
                   6197: private -- to each child word. When a child word is executed, the
                   6198: address of its private data area is passed as a parameter on TOS to be
                   6199: used and manipulated@footnote{It is legitimate both to read and write to
                   6200: this data area.} by @i{code2}.
1.29      crook    6201: 
                   6202: The two fragments of code that make up the defining words act (are
                   6203: executed) at two completely separate times:
1.1       anton    6204: 
1.29      crook    6205: @itemize @bullet
                   6206: @item
                   6207: At @i{define time}, the defining word executes @i{code1} to generate a
                   6208: child word
                   6209: @item
                   6210: At @i{child execution time}, when a child word is invoked, @i{code2}
                   6211: is executed, using parameters (data) that are private and specific to
                   6212: the child word.
                   6213: @end itemize
                   6214: 
1.44      crook    6215: Another way of understanding the behaviour of @code{def-word} and
                   6216: @code{name} is to say that, if you make the following definitions:
1.33      anton    6217: @example
                   6218: : def-word1 ( "name" -- )
                   6219:     CREATE @i{code1} ;
                   6220: 
                   6221: : action1 ( ... -- ... )
                   6222:     @i{code2} ;
                   6223: 
                   6224: def-word1 name1
                   6225: @end example
                   6226: 
1.44      crook    6227: @noindent
                   6228: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    6229: 
1.29      crook    6230: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    6231: 
1.1       anton    6232: @example
1.29      crook    6233: : CONSTANT ( w "name" -- )
                   6234:     CREATE ,
1.26      crook    6235: DOES> ( -- w )
                   6236:     @@ ;
1.1       anton    6237: @end example
                   6238: 
1.29      crook    6239: @comment There is a beautiful description of how this works and what
                   6240: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   6241: @comment commentary on the Counting Fruits problem.
                   6242: 
                   6243: When you create a constant with @code{5 CONSTANT five}, a set of
                   6244: define-time actions take place; first a new word @code{five} is created,
                   6245: then the value 5 is laid down in the body of @code{five} with
1.44      crook    6246: @code{,}. When @code{five} is executed, the address of the body is put on
1.29      crook    6247: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   6248: no code of its own; it simply contains a data field and a pointer to the
                   6249: code that follows @code{DOES>} in its defining word. That makes words
                   6250: created in this way very compact.
                   6251: 
                   6252: The final example in this section is intended to remind you that space
                   6253: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   6254: both read and written by a Standard program@footnote{Exercise: use this
                   6255: example as a starting point for your own implementation of @code{Value}
                   6256: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   6257: @code{[']}.}:
                   6258: 
                   6259: @example
                   6260: : foo ( "name" -- )
                   6261:     CREATE -1 ,
                   6262: DOES> ( -- )
1.33      anton    6263:     @@ . ;
1.29      crook    6264: 
                   6265: foo first-word
                   6266: foo second-word
                   6267: 
                   6268: 123 ' first-word >BODY !
                   6269: @end example
                   6270: 
                   6271: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   6272: have executed it to get the address of its data field. However, since it
                   6273: was defined to have @code{DOES>} actions, its execution semantics are to
                   6274: perform those @code{DOES>} actions. To get the address of its data field
                   6275: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   6276: translate the xt into the address of the data field.  When you execute
                   6277: @code{first-word}, it will display @code{123}. When you execute
                   6278: @code{second-word} it will display @code{-1}.
1.26      crook    6279: 
                   6280: @cindex stack effect of @code{DOES>}-parts
                   6281: @cindex @code{DOES>}-parts, stack effect
1.29      crook    6282: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    6283: the stack effect of the defined words, not the stack effect of the
                   6284: following code (the following code expects the address of the body on
                   6285: the top of stack, which is not reflected in the stack comment). This is
                   6286: the convention that I use and recommend (it clashes a bit with using
                   6287: locals declarations for stack effect specification, though).
1.1       anton    6288: 
1.53      anton    6289: @menu
                   6290: * CREATE..DOES> applications::  
                   6291: * CREATE..DOES> details::       
1.63      anton    6292: * Advanced does> usage example::  
1.91      anton    6293: * @code{Const-does>}::          
1.53      anton    6294: @end menu
                   6295: 
                   6296: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26      crook    6297: @subsubsection Applications of @code{CREATE..DOES>}
                   6298: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    6299: 
1.26      crook    6300: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    6301: 
1.26      crook    6302: @cindex factoring similar colon definitions
                   6303: When you see a sequence of code occurring several times, and you can
                   6304: identify a meaning, you will factor it out as a colon definition. When
                   6305: you see similar colon definitions, you can factor them using
                   6306: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   6307: that look very similar:
1.1       anton    6308: @example
1.26      crook    6309: : ori, ( reg-target reg-source n -- )
                   6310:     0 asm-reg-reg-imm ;
                   6311: : andi, ( reg-target reg-source n -- )
                   6312:     1 asm-reg-reg-imm ;
1.1       anton    6313: @end example
                   6314: 
1.26      crook    6315: @noindent
                   6316: This could be factored with:
                   6317: @example
                   6318: : reg-reg-imm ( op-code -- )
                   6319:     CREATE ,
                   6320: DOES> ( reg-target reg-source n -- )
                   6321:     @@ asm-reg-reg-imm ;
                   6322: 
                   6323: 0 reg-reg-imm ori,
                   6324: 1 reg-reg-imm andi,
                   6325: @end example
1.1       anton    6326: 
1.26      crook    6327: @cindex currying
                   6328: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   6329: supply a part of the parameters for a word (known as @dfn{currying} in
                   6330: the functional language community). E.g., @code{+} needs two
                   6331: parameters. Creating versions of @code{+} with one parameter fixed can
                   6332: be done like this:
1.82      anton    6333: 
1.1       anton    6334: @example
1.82      anton    6335: : curry+ ( n1 "name" -- )
1.26      crook    6336:     CREATE ,
                   6337: DOES> ( n2 -- n1+n2 )
                   6338:     @@ + ;
                   6339: 
                   6340:  3 curry+ 3+
                   6341: -2 curry+ 2-
1.1       anton    6342: @end example
                   6343: 
1.91      anton    6344: 
1.63      anton    6345: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26      crook    6346: @subsubsection The gory details of @code{CREATE..DOES>}
                   6347: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    6348: 
1.26      crook    6349: doc-does>
1.1       anton    6350: 
1.26      crook    6351: @cindex @code{DOES>} in a separate definition
                   6352: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   6353: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    6354: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    6355: @example
                   6356: : does1 
                   6357: DOES> ( ... -- ... )
1.44      crook    6358:     ... ;
                   6359: 
                   6360: : does2
                   6361: DOES> ( ... -- ... )
                   6362:     ... ;
                   6363: 
                   6364: : def-word ( ... -- ... )
                   6365:     create ...
                   6366:     IF
                   6367:        does1
                   6368:     ELSE
                   6369:        does2
                   6370:     ENDIF ;
                   6371: @end example
                   6372: 
                   6373: In this example, the selection of whether to use @code{does1} or
1.69      anton    6374: @code{does2} is made at definition-time; at the time that the child word is
1.44      crook    6375: @code{CREATE}d.
                   6376: 
                   6377: @cindex @code{DOES>} in interpretation state
                   6378: In a standard program you can apply a @code{DOES>}-part only if the last
                   6379: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   6380: will override the behaviour of the last word defined in any case. In a
                   6381: standard program, you can use @code{DOES>} only in a colon
                   6382: definition. In Gforth, you can also use it in interpretation state, in a
                   6383: kind of one-shot mode; for example:
                   6384: @example
                   6385: CREATE name ( ... -- ... )
                   6386:   @i{initialization}
                   6387: DOES>
                   6388:   @i{code} ;
                   6389: @end example
                   6390: 
                   6391: @noindent
                   6392: is equivalent to the standard:
                   6393: @example
                   6394: :noname
                   6395: DOES>
                   6396:     @i{code} ;
                   6397: CREATE name EXECUTE ( ... -- ... )
                   6398:     @i{initialization}
                   6399: @end example
                   6400: 
1.53      anton    6401: doc->body
                   6402: 
1.91      anton    6403: @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words
1.63      anton    6404: @subsubsection Advanced does> usage example
                   6405: 
                   6406: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
                   6407: for disassembling instructions, that follow a very repetetive scheme:
                   6408: 
                   6409: @example
                   6410: :noname @var{disasm-operands} s" @var{inst-name}" type ;
                   6411: @var{entry-num} cells @var{table} + !
                   6412: @end example
                   6413: 
                   6414: Of course, this inspires the idea to factor out the commonalities to
                   6415: allow a definition like
                   6416: 
                   6417: @example
                   6418: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
                   6419: @end example
                   6420: 
                   6421: The parameters @var{disasm-operands} and @var{table} are usually
1.69      anton    6422: correlated.  Moreover, before I wrote the disassembler, there already
                   6423: existed code that defines instructions like this:
1.63      anton    6424: 
                   6425: @example
                   6426: @var{entry-num} @var{inst-format} @var{inst-name}
                   6427: @end example
                   6428: 
                   6429: This code comes from the assembler and resides in
                   6430: @file{arch/mips/insts.fs}.
                   6431: 
                   6432: So I had to define the @var{inst-format} words that performed the scheme
                   6433: above when executed.  At first I chose to use run-time code-generation:
                   6434: 
                   6435: @example
                   6436: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
                   6437:   :noname Postpone @var{disasm-operands}
                   6438:   name Postpone sliteral Postpone type Postpone ;
                   6439:   swap cells @var{table} + ! ;
                   6440: @end example
                   6441: 
                   6442: Note that this supplies the other two parameters of the scheme above.
1.44      crook    6443: 
1.63      anton    6444: An alternative would have been to write this using
                   6445: @code{create}/@code{does>}:
                   6446: 
                   6447: @example
                   6448: : @var{inst-format} ( entry-num "name" -- )
                   6449:   here name string, ( entry-num c-addr ) \ parse and save "name"
                   6450:   noname create , ( entry-num )
1.116     anton    6451:   latestxt swap cells @var{table} + !
1.63      anton    6452: does> ( addr w -- )
                   6453:   \ disassemble instruction w at addr
                   6454:   @@ >r 
                   6455:   @var{disasm-operands}
                   6456:   r> count type ;
                   6457: @end example
                   6458: 
                   6459: Somehow the first solution is simpler, mainly because it's simpler to
                   6460: shift a string from definition-time to use-time with @code{sliteral}
                   6461: than with @code{string,} and friends.
                   6462: 
                   6463: I wrote a lot of words following this scheme and soon thought about
                   6464: factoring out the commonalities among them.  Note that this uses a
                   6465: two-level defining word, i.e., a word that defines ordinary defining
                   6466: words.
                   6467: 
                   6468: This time a solution involving @code{postpone} and friends seemed more
                   6469: difficult (try it as an exercise), so I decided to use a
                   6470: @code{create}/@code{does>} word; since I was already at it, I also used
                   6471: @code{create}/@code{does>} for the lower level (try using
                   6472: @code{postpone} etc. as an exercise), resulting in the following
                   6473: definition:
                   6474: 
                   6475: @example
                   6476: : define-format ( disasm-xt table-xt -- )
                   6477:     \ define an instruction format that uses disasm-xt for
                   6478:     \ disassembling and enters the defined instructions into table
                   6479:     \ table-xt
                   6480:     create 2,
                   6481: does> ( u "inst" -- )
                   6482:     \ defines an anonymous word for disassembling instruction inst,
                   6483:     \ and enters it as u-th entry into table-xt
                   6484:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
                   6485:     noname create 2,      \ define anonymous word
1.116     anton    6486:     execute latestxt swap ! \ enter xt of defined word into table-xt
1.63      anton    6487: does> ( addr w -- )
                   6488:     \ disassemble instruction w at addr
                   6489:     2@@ >r ( addr w disasm-xt R: c-addr )
                   6490:     execute ( R: c-addr ) \ disassemble operands
                   6491:     r> count type ; \ print name 
                   6492: @end example
                   6493: 
                   6494: Note that the tables here (in contrast to above) do the @code{cells +}
                   6495: by themselves (that's why you have to pass an xt).  This word is used in
                   6496: the following way:
                   6497: 
                   6498: @example
                   6499: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
                   6500: @end example
                   6501: 
1.71      anton    6502: As shown above, the defined instruction format is then used like this:
                   6503: 
                   6504: @example
                   6505: @var{entry-num} @var{inst-format} @var{inst-name}
                   6506: @end example
                   6507: 
1.63      anton    6508: In terms of currying, this kind of two-level defining word provides the
                   6509: parameters in three stages: first @var{disasm-operands} and @var{table},
                   6510: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
                   6511: the instruction to be disassembled.  
                   6512: 
                   6513: Of course this did not quite fit all the instruction format names used
                   6514: in @file{insts.fs}, so I had to define a few wrappers that conditioned
                   6515: the parameters into the right form.
                   6516: 
                   6517: If you have trouble following this section, don't worry.  First, this is
                   6518: involved and takes time (and probably some playing around) to
                   6519: understand; second, this is the first two-level
                   6520: @code{create}/@code{does>} word I have written in seventeen years of
                   6521: Forth; and if I did not have @file{insts.fs} to start with, I may well
                   6522: have elected to use just a one-level defining word (with some repeating
                   6523: of parameters when using the defining word). So it is not necessary to
                   6524: understand this, but it may improve your understanding of Forth.
1.44      crook    6525: 
                   6526: 
1.91      anton    6527: @node @code{Const-does>},  , Advanced does> usage example, User-defined Defining Words
                   6528: @subsubsection @code{Const-does>}
                   6529: 
                   6530: A frequent use of @code{create}...@code{does>} is for transferring some
                   6531: values from definition-time to run-time.  Gforth supports this use with
                   6532: 
                   6533: doc-const-does>
                   6534: 
                   6535: A typical use of this word is:
                   6536: 
                   6537: @example
                   6538: : curry+ ( n1 "name" -- )
                   6539: 1 0 CONST-DOES> ( n2 -- n1+n2 )
                   6540:     + ;
                   6541: 
                   6542: 3 curry+ 3+
                   6543: @end example
                   6544: 
                   6545: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
                   6546: definition to run-time.
                   6547: 
                   6548: The advantages of using @code{const-does>} are:
                   6549: 
                   6550: @itemize
                   6551: 
                   6552: @item
                   6553: You don't have to deal with storing and retrieving the values, i.e.,
                   6554: your program becomes more writable and readable.
                   6555: 
                   6556: @item
                   6557: When using @code{does>}, you have to introduce a @code{@@} that cannot
                   6558: be optimized away (because you could change the data using
                   6559: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
                   6560: 
                   6561: @end itemize
                   6562: 
                   6563: An ANS Forth implementation of @code{const-does>} is available in
                   6564: @file{compat/const-does.fs}.
                   6565: 
                   6566: 
1.44      crook    6567: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
                   6568: @subsection Deferred words
                   6569: @cindex deferred words
                   6570: 
                   6571: The defining word @code{Defer} allows you to define a word by name
                   6572: without defining its behaviour; the definition of its behaviour is
                   6573: deferred. Here are two situation where this can be useful:
                   6574: 
                   6575: @itemize @bullet
                   6576: @item
                   6577: Where you want to allow the behaviour of a word to be altered later, and
                   6578: for all precompiled references to the word to change when its behaviour
                   6579: is changed.
                   6580: @item
                   6581: For mutual recursion; @xref{Calls and returns}.
                   6582: @end itemize
                   6583: 
                   6584: In the following example, @code{foo} always invokes the version of
                   6585: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
                   6586: always invokes the version that prints ``@code{Hello}''. There is no way
                   6587: of getting @code{foo} to use the later version without re-ordering the
                   6588: source code and recompiling it.
                   6589: 
                   6590: @example
                   6591: : greet ." Good morning" ;
                   6592: : foo ... greet ... ;
                   6593: : greet ." Hello" ;
                   6594: : bar ... greet ... ;
                   6595: @end example
                   6596: 
                   6597: This problem can be solved by defining @code{greet} as a @code{Defer}red
                   6598: word. The behaviour of a @code{Defer}red word can be defined and
                   6599: redefined at any time by using @code{IS} to associate the xt of a
                   6600: previously-defined word with it. The previous example becomes:
                   6601: 
                   6602: @example
1.69      anton    6603: Defer greet ( -- )
1.44      crook    6604: : foo ... greet ... ;
                   6605: : bar ... greet ... ;
1.69      anton    6606: : greet1 ( -- ) ." Good morning" ;
                   6607: : greet2 ( -- ) ." Hello" ;
1.44      crook    6608: ' greet2 <IS> greet  \ make greet behave like greet2
                   6609: @end example
                   6610: 
1.69      anton    6611: @progstyle
                   6612: You should write a stack comment for every deferred word, and put only
                   6613: XTs into deferred words that conform to this stack effect.  Otherwise
                   6614: it's too difficult to use the deferred word.
                   6615: 
1.44      crook    6616: A deferred word can be used to improve the statistics-gathering example
                   6617: from @ref{User-defined Defining Words}; rather than edit the
                   6618: application's source code to change every @code{:} to a @code{my:}, do
                   6619: this:
                   6620: 
                   6621: @example
                   6622: : real: : ;     \ retain access to the original
                   6623: defer :         \ redefine as a deferred word
1.69      anton    6624: ' my: <IS> :      \ use special version of :
1.44      crook    6625: \
                   6626: \ load application here
                   6627: \
1.69      anton    6628: ' real: <IS> :    \ go back to the original
1.44      crook    6629: @end example
                   6630: 
                   6631: 
                   6632: One thing to note is that @code{<IS>} consumes its name when it is
                   6633: executed.  If you want to specify the name at compile time, use
                   6634: @code{[IS]}:
                   6635: 
                   6636: @example
                   6637: : set-greet ( xt -- )
                   6638:   [IS] greet ;
                   6639: 
                   6640: ' greet1 set-greet
                   6641: @end example
                   6642: 
1.69      anton    6643: A deferred word can only inherit execution semantics from the xt
                   6644: (because that is all that an xt can represent -- for more discussion of
                   6645: this @pxref{Tokens for Words}); by default it will have default
                   6646: interpretation and compilation semantics deriving from this execution
                   6647: semantics.  However, you can change the interpretation and compilation
                   6648: semantics of the deferred word in the usual ways:
1.44      crook    6649: 
                   6650: @example
                   6651: : bar .... ; compile-only
                   6652: Defer fred immediate
                   6653: Defer jim
                   6654: 
                   6655: ' bar <IS> jim  \ jim has default semantics
                   6656: ' bar <IS> fred \ fred is immediate
                   6657: @end example
                   6658: 
                   6659: doc-defer
                   6660: doc-<is>
                   6661: doc-[is]
                   6662: doc-is
                   6663: @comment TODO document these: what's defers [is]
                   6664: doc-what's
                   6665: doc-defers
                   6666: 
                   6667: @c Use @code{words-deferred} to see a list of deferred words.
                   6668: 
                   6669: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
                   6670: are provided in @file{compat/defer.fs}.
                   6671: 
                   6672: 
1.69      anton    6673: @node Aliases,  , Deferred words, Defining Words
1.44      crook    6674: @subsection Aliases
                   6675: @cindex aliases
1.1       anton    6676: 
1.44      crook    6677: The defining word @code{Alias} allows you to define a word by name that
                   6678: has the same behaviour as some other word. Here are two situation where
                   6679: this can be useful:
1.1       anton    6680: 
1.44      crook    6681: @itemize @bullet
                   6682: @item
                   6683: When you want access to a word's definition from a different word list
                   6684: (for an example of this, see the definition of the @code{Root} word list
                   6685: in the Gforth source).
                   6686: @item
                   6687: When you want to create a synonym; a definition that can be known by
                   6688: either of two names (for example, @code{THEN} and @code{ENDIF} are
                   6689: aliases).
                   6690: @end itemize
1.1       anton    6691: 
1.69      anton    6692: Like deferred words, an alias has default compilation and interpretation
                   6693: semantics at the beginning (not the modifications of the other word),
                   6694: but you can change them in the usual ways (@code{immediate},
                   6695: @code{compile-only}). For example:
1.1       anton    6696: 
                   6697: @example
1.44      crook    6698: : foo ... ; immediate
                   6699: 
                   6700: ' foo Alias bar \ bar is not an immediate word
                   6701: ' foo Alias fooby immediate \ fooby is an immediate word
1.1       anton    6702: @end example
                   6703: 
1.44      crook    6704: Words that are aliases have the same xt, different headers in the
                   6705: dictionary, and consequently different name tokens (@pxref{Tokens for
                   6706: Words}) and possibly different immediate flags.  An alias can only have
                   6707: default or immediate compilation semantics; you can define aliases for
                   6708: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1       anton    6709: 
1.44      crook    6710: doc-alias
1.1       anton    6711: 
                   6712: 
1.47      crook    6713: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
                   6714: @section Interpretation and Compilation Semantics
1.26      crook    6715: @cindex semantics, interpretation and compilation
1.1       anton    6716: 
1.71      anton    6717: @c !! state and ' are used without explanation
                   6718: @c example for immediate/compile-only? or is the tutorial enough
                   6719: 
1.26      crook    6720: @cindex interpretation semantics
1.71      anton    6721: The @dfn{interpretation semantics} of a (named) word are what the text
1.26      crook    6722: interpreter does when it encounters the word in interpret state. It also
                   6723: appears in some other contexts, e.g., the execution token returned by
1.71      anton    6724: @code{' @i{word}} identifies the interpretation semantics of @i{word}
                   6725: (in other words, @code{' @i{word} execute} is equivalent to
1.29      crook    6726: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    6727: 
1.26      crook    6728: @cindex compilation semantics
1.71      anton    6729: The @dfn{compilation semantics} of a (named) word are what the text
                   6730: interpreter does when it encounters the word in compile state. It also
                   6731: appears in other contexts, e.g, @code{POSTPONE @i{word}}
                   6732: compiles@footnote{In standard terminology, ``appends to the current
                   6733: definition''.} the compilation semantics of @i{word}.
1.1       anton    6734: 
1.26      crook    6735: @cindex execution semantics
                   6736: The standard also talks about @dfn{execution semantics}. They are used
                   6737: only for defining the interpretation and compilation semantics of many
                   6738: words. By default, the interpretation semantics of a word are to
                   6739: @code{execute} its execution semantics, and the compilation semantics of
                   6740: a word are to @code{compile,} its execution semantics.@footnote{In
                   6741: standard terminology: The default interpretation semantics are its
                   6742: execution semantics; the default compilation semantics are to append its
                   6743: execution semantics to the execution semantics of the current
                   6744: definition.}
                   6745: 
1.71      anton    6746: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
                   6747: the text interpreter, ticked, or @code{postpone}d, so they have no
                   6748: interpretation or compilation semantics.  Their behaviour is represented
                   6749: by their XT (@pxref{Tokens for Words}), and we call it execution
                   6750: semantics, too.
                   6751: 
1.26      crook    6752: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   6753: 
                   6754: @cindex immediate words
                   6755: @cindex compile-only words
                   6756: You can change the semantics of the most-recently defined word:
                   6757: 
1.44      crook    6758: 
1.26      crook    6759: doc-immediate
                   6760: doc-compile-only
                   6761: doc-restrict
                   6762: 
1.82      anton    6763: By convention, words with non-default compilation semantics (e.g.,
                   6764: immediate words) often have names surrounded with brackets (e.g.,
                   6765: @code{[']}, @pxref{Execution token}).
1.44      crook    6766: 
1.26      crook    6767: Note that ticking (@code{'}) a compile-only word gives an error
                   6768: (``Interpreting a compile-only word'').
1.1       anton    6769: 
1.47      crook    6770: @menu
1.67      anton    6771: * Combined words::              
1.47      crook    6772: @end menu
1.44      crook    6773: 
1.71      anton    6774: 
1.48      anton    6775: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44      crook    6776: @subsection Combined Words
                   6777: @cindex combined words
                   6778: 
                   6779: Gforth allows you to define @dfn{combined words} -- words that have an
                   6780: arbitrary combination of interpretation and compilation semantics.
                   6781: 
1.26      crook    6782: doc-interpret/compile:
1.1       anton    6783: 
1.26      crook    6784: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   6785: recommend that you do not define such words, as cute as they may be:
                   6786: they make it hard to get at both parts of the word in some contexts.
                   6787: E.g., assume you want to get an execution token for the compilation
                   6788: part. Instead, define two words, one that embodies the interpretation
                   6789: part, and one that embodies the compilation part.  Once you have done
                   6790: that, you can define a combined word with @code{interpret/compile:} for
                   6791: the convenience of your users.
1.1       anton    6792: 
1.26      crook    6793: You might try to use this feature to provide an optimizing
                   6794: implementation of the default compilation semantics of a word. For
                   6795: example, by defining:
1.1       anton    6796: @example
1.26      crook    6797: :noname
                   6798:    foo bar ;
                   6799: :noname
                   6800:    POSTPONE foo POSTPONE bar ;
1.29      crook    6801: interpret/compile: opti-foobar
1.1       anton    6802: @end example
1.26      crook    6803: 
1.23      crook    6804: @noindent
1.26      crook    6805: as an optimizing version of:
                   6806: 
1.1       anton    6807: @example
1.26      crook    6808: : foobar
                   6809:     foo bar ;
1.1       anton    6810: @end example
                   6811: 
1.26      crook    6812: Unfortunately, this does not work correctly with @code{[compile]},
                   6813: because @code{[compile]} assumes that the compilation semantics of all
                   6814: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    6815: opti-foobar} would compile compilation semantics, whereas
                   6816: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    6817: 
1.26      crook    6818: @cindex state-smart words (are a bad idea)
1.82      anton    6819: @anchor{state-smartness}
1.29      crook    6820: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    6821: by @code{interpret/compile:} (words are state-smart if they check
                   6822: @code{STATE} during execution). E.g., they would try to code
                   6823: @code{foobar} like this:
1.1       anton    6824: 
1.26      crook    6825: @example
                   6826: : foobar
                   6827:   STATE @@
                   6828:   IF ( compilation state )
                   6829:     POSTPONE foo POSTPONE bar
                   6830:   ELSE
                   6831:     foo bar
                   6832:   ENDIF ; immediate
                   6833: @end example
1.1       anton    6834: 
1.26      crook    6835: Although this works if @code{foobar} is only processed by the text
                   6836: interpreter, it does not work in other contexts (like @code{'} or
                   6837: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   6838: for a state-smart word, not for the interpretation semantics of the
                   6839: original @code{foobar}; when you execute this execution token (directly
                   6840: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   6841: state, the result will not be what you expected (i.e., it will not
                   6842: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   6843: write them@footnote{For a more detailed discussion of this topic, see
1.66      anton    6844: M. Anton Ertl,
                   6845: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
                   6846: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1       anton    6847: 
1.26      crook    6848: @cindex defining words with arbitrary semantics combinations
                   6849: It is also possible to write defining words that define words with
                   6850: arbitrary combinations of interpretation and compilation semantics. In
                   6851: general, they look like this:
1.1       anton    6852: 
1.26      crook    6853: @example
                   6854: : def-word
                   6855:     create-interpret/compile
1.29      crook    6856:     @i{code1}
1.26      crook    6857: interpretation>
1.29      crook    6858:     @i{code2}
1.26      crook    6859: <interpretation
                   6860: compilation>
1.29      crook    6861:     @i{code3}
1.26      crook    6862: <compilation ;
                   6863: @end example
1.1       anton    6864: 
1.29      crook    6865: For a @i{word} defined with @code{def-word}, the interpretation
                   6866: semantics are to push the address of the body of @i{word} and perform
                   6867: @i{code2}, and the compilation semantics are to push the address of
                   6868: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    6869: can also be defined like this (except that the defined constants don't
                   6870: behave correctly when @code{[compile]}d):
1.1       anton    6871: 
1.26      crook    6872: @example
                   6873: : constant ( n "name" -- )
                   6874:     create-interpret/compile
                   6875:     ,
                   6876: interpretation> ( -- n )
                   6877:     @@
                   6878: <interpretation
                   6879: compilation> ( compilation. -- ; run-time. -- n )
                   6880:     @@ postpone literal
                   6881: <compilation ;
                   6882: @end example
1.1       anton    6883: 
1.44      crook    6884: 
1.26      crook    6885: doc-create-interpret/compile
                   6886: doc-interpretation>
                   6887: doc-<interpretation
                   6888: doc-compilation>
                   6889: doc-<compilation
1.1       anton    6890: 
1.44      crook    6891: 
1.29      crook    6892: Words defined with @code{interpret/compile:} and
1.26      crook    6893: @code{create-interpret/compile} have an extended header structure that
                   6894: differs from other words; however, unless you try to access them with
                   6895: plain address arithmetic, you should not notice this. Words for
                   6896: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    6897: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   6898: with @code{create-interpret/compile}.
1.1       anton    6899: 
1.44      crook    6900: 
1.47      crook    6901: @c -------------------------------------------------------------
1.81      anton    6902: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47      crook    6903: @section Tokens for Words
                   6904: @cindex tokens for words
                   6905: 
                   6906: This section describes the creation and use of tokens that represent
                   6907: words.
                   6908: 
1.71      anton    6909: @menu
                   6910: * Execution token::             represents execution/interpretation semantics
                   6911: * Compilation token::           represents compilation semantics
                   6912: * Name token::                  represents named words
                   6913: @end menu
1.47      crook    6914: 
1.71      anton    6915: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
                   6916: @subsection Execution token
1.47      crook    6917: 
                   6918: @cindex xt
                   6919: @cindex execution token
1.71      anton    6920: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
                   6921: You can use @code{execute} to invoke this behaviour.
1.47      crook    6922: 
1.71      anton    6923: @cindex tick (')
                   6924: You can use @code{'} to get an execution token that represents the
                   6925: interpretation semantics of a named word:
1.47      crook    6926: 
                   6927: @example
1.97      anton    6928: 5 ' .   ( n xt ) 
                   6929: execute ( )      \ execute the xt (i.e., ".")
1.71      anton    6930: @end example
1.47      crook    6931: 
1.71      anton    6932: doc-'
                   6933: 
                   6934: @code{'} parses at run-time; there is also a word @code{[']} that parses
                   6935: when it is compiled, and compiles the resulting XT:
                   6936: 
                   6937: @example
                   6938: : foo ['] . execute ;
                   6939: 5 foo
                   6940: : bar ' execute ; \ by contrast,
                   6941: 5 bar .           \ ' parses "." when bar executes
                   6942: @end example
                   6943: 
                   6944: doc-[']
                   6945: 
                   6946: If you want the execution token of @i{word}, write @code{['] @i{word}}
                   6947: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
                   6948: @code{'} and @code{[']} behave somewhat unusually by complaining about
                   6949: compile-only words (because these words have no interpretation
                   6950: semantics).  You might get what you want by using @code{COMP' @i{word}
                   6951: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
                   6952: token}).
                   6953: 
1.116     anton    6954: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71      anton    6955: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
                   6956: for the only behaviour the word has (the execution semantics).  For
1.116     anton    6957: named words, @code{latestxt} produces an XT for the same behaviour it
1.71      anton    6958: would produce if the word was defined anonymously.
                   6959: 
                   6960: @example
                   6961: :noname ." hello" ;
                   6962: execute
1.47      crook    6963: @end example
                   6964: 
1.71      anton    6965: An XT occupies one cell and can be manipulated like any other cell.
                   6966: 
1.47      crook    6967: @cindex code field address
                   6968: @cindex CFA
1.71      anton    6969: In ANS Forth the XT is just an abstract data type (i.e., defined by the
                   6970: operations that produce or consume it).  For old hands: In Gforth, the
                   6971: XT is implemented as a code field address (CFA).
                   6972: 
                   6973: doc-execute
                   6974: doc-perform
                   6975: 
                   6976: @node Compilation token, Name token, Execution token, Tokens for Words
                   6977: @subsection Compilation token
1.47      crook    6978: 
                   6979: @cindex compilation token
1.71      anton    6980: @cindex CT (compilation token)
                   6981: Gforth represents the compilation semantics of a named word by a
1.47      crook    6982: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   6983: @i{xt} is an execution token. The compilation semantics represented by
                   6984: the compilation token can be performed with @code{execute}, which
                   6985: consumes the whole compilation token, with an additional stack effect
                   6986: determined by the represented compilation semantics.
                   6987: 
                   6988: At present, the @i{w} part of a compilation token is an execution token,
                   6989: and the @i{xt} part represents either @code{execute} or
                   6990: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   6991: word. If the word has default compilation semantics, the @i{xt} will
                   6992: represent @code{compile,}. Otherwise (e.g., for immediate words), the
                   6993: @i{xt} will represent @code{execute}.}. However, don't rely on that
                   6994: knowledge, unless necessary; future versions of Gforth may introduce
                   6995: unusual compilation tokens (e.g., a compilation token that represents
                   6996: the compilation semantics of a literal).
                   6997: 
1.71      anton    6998: You can perform the compilation semantics represented by the compilation
                   6999: token with @code{execute}.  You can compile the compilation semantics
                   7000: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
                   7001: equivalent to @code{postpone @i{word}}.
                   7002: 
                   7003: doc-[comp']
                   7004: doc-comp'
                   7005: doc-postpone,
                   7006: 
                   7007: @node Name token,  , Compilation token, Tokens for Words
                   7008: @subsection Name token
1.47      crook    7009: 
                   7010: @cindex name token
1.116     anton    7011: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
                   7012: token is an abstract data type that occurs as argument or result of the
                   7013: words below.
                   7014: 
                   7015: @c !! put this elswhere?
1.47      crook    7016: @cindex name field address
                   7017: @cindex NFA
1.116     anton    7018: The closest thing to the nt in older Forth systems is the name field
                   7019: address (NFA), but there are significant differences: in older Forth
                   7020: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
                   7021: LFA, NFA, CFA, PFA) and there were words for getting from one to the
                   7022: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
                   7023: is a link field in the structure identified by the name token, but
                   7024: searching usually uses a hash table external to these structures; the
                   7025: name in Gforth has a cell-wide count-and-flags field, and the nt is not
                   7026: implemented as the address of that count field.
1.47      crook    7027: 
                   7028: doc-find-name
1.116     anton    7029: doc-latest
                   7030: doc->name
1.47      crook    7031: doc-name>int
                   7032: doc-name?int
                   7033: doc-name>comp
                   7034: doc-name>string
1.109     anton    7035: doc-id.
                   7036: doc-.name
                   7037: doc-.id
1.47      crook    7038: 
1.81      anton    7039: @c ----------------------------------------------------------
                   7040: @node Compiling words, The Text Interpreter, Tokens for Words, Words
                   7041: @section Compiling words
                   7042: @cindex compiling words
                   7043: @cindex macros
                   7044: 
                   7045: In contrast to most other languages, Forth has no strict boundary
1.82      anton    7046: between compilation and run-time.  E.g., you can run arbitrary code
                   7047: between defining words (or for computing data used by defining words
                   7048: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
                   7049: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
                   7050: running arbitrary code while compiling a colon definition (exception:
                   7051: you must not allot dictionary space).
                   7052: 
                   7053: @menu
                   7054: * Literals::                    Compiling data values
                   7055: * Macros::                      Compiling words
                   7056: @end menu
                   7057: 
                   7058: @node Literals, Macros, Compiling words, Compiling words
                   7059: @subsection Literals
                   7060: @cindex Literals
                   7061: 
                   7062: The simplest and most frequent example is to compute a literal during
                   7063: compilation.  E.g., the following definition prints an array of strings,
                   7064: one string per line:
                   7065: 
                   7066: @example
                   7067: : .strings ( addr u -- ) \ gforth
                   7068:     2* cells bounds U+DO
                   7069:        cr i 2@@ type
                   7070:     2 cells +LOOP ;  
                   7071: @end example
1.81      anton    7072: 
1.82      anton    7073: With a simple-minded compiler like Gforth's, this computes @code{2
                   7074: cells} on every loop iteration.  You can compute this value once and for
                   7075: all at compile time and compile it into the definition like this:
                   7076: 
                   7077: @example
                   7078: : .strings ( addr u -- ) \ gforth
                   7079:     2* cells bounds U+DO
                   7080:        cr i 2@@ type
                   7081:     [ 2 cells ] literal +LOOP ;  
                   7082: @end example
                   7083: 
                   7084: @code{[} switches the text interpreter to interpret state (you will get
                   7085: an @code{ok} prompt if you type this example interactively and insert a
                   7086: newline between @code{[} and @code{]}), so it performs the
                   7087: interpretation semantics of @code{2 cells}; this computes a number.
                   7088: @code{]} switches the text interpreter back into compile state.  It then
                   7089: performs @code{Literal}'s compilation semantics, which are to compile
                   7090: this number into the current word.  You can decompile the word with
                   7091: @code{see .strings} to see the effect on the compiled code.
1.81      anton    7092: 
1.82      anton    7093: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
                   7094: *} in this way.
1.81      anton    7095: 
1.82      anton    7096: doc-[
                   7097: doc-]
1.81      anton    7098: doc-literal
                   7099: doc-]L
1.82      anton    7100: 
                   7101: There are also words for compiling other data types than single cells as
                   7102: literals:
                   7103: 
1.81      anton    7104: doc-2literal
                   7105: doc-fliteral
1.82      anton    7106: doc-sliteral
                   7107: 
                   7108: @cindex colon-sys, passing data across @code{:}
                   7109: @cindex @code{:}, passing data across
                   7110: You might be tempted to pass data from outside a colon definition to the
                   7111: inside on the data stack.  This does not work, because @code{:} puhes a
                   7112: colon-sys, making stuff below unaccessible.  E.g., this does not work:
                   7113: 
                   7114: @example
                   7115: 5 : foo literal ; \ error: "unstructured"
                   7116: @end example
                   7117: 
                   7118: Instead, you have to pass the value in some other way, e.g., through a
                   7119: variable:
                   7120: 
                   7121: @example
                   7122: variable temp
                   7123: 5 temp !
                   7124: : foo [ temp @@ ] literal ;
                   7125: @end example
                   7126: 
                   7127: 
                   7128: @node Macros,  , Literals, Compiling words
                   7129: @subsection Macros
                   7130: @cindex Macros
                   7131: @cindex compiling compilation semantics
                   7132: 
                   7133: @code{Literal} and friends compile data values into the current
                   7134: definition.  You can also write words that compile other words into the
                   7135: current definition.  E.g.,
                   7136: 
                   7137: @example
                   7138: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
                   7139:   POSTPONE + ;
                   7140: 
                   7141: : foo ( n1 n2 -- n )
                   7142:   [ compile-+ ] ;
                   7143: 1 2 foo .
                   7144: @end example
                   7145: 
                   7146: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
                   7147: What happens in this example?  @code{Postpone} compiles the compilation
                   7148: semantics of @code{+} into @code{compile-+}; later the text interpreter
                   7149: executes @code{compile-+} and thus the compilation semantics of +, which
                   7150: compile (the execution semantics of) @code{+} into
                   7151: @code{foo}.@footnote{A recent RFI answer requires that compiling words
                   7152: should only be executed in compile state, so this example is not
                   7153: guaranteed to work on all standard systems, but on any decent system it
                   7154: will work.}
                   7155: 
                   7156: doc-postpone
                   7157: doc-[compile]
                   7158: 
                   7159: Compiling words like @code{compile-+} are usually immediate (or similar)
                   7160: so you do not have to switch to interpret state to execute them;
                   7161: mopifying the last example accordingly produces:
                   7162: 
                   7163: @example
                   7164: : [compile-+] ( compilation: --; interpretation: -- )
                   7165:   \ compiled code: ( n1 n2 -- n )
                   7166:   POSTPONE + ; immediate
                   7167: 
                   7168: : foo ( n1 n2 -- n )
                   7169:   [compile-+] ;
                   7170: 1 2 foo .
                   7171: @end example
                   7172: 
                   7173: Immediate compiling words are similar to macros in other languages (in
                   7174: particular, Lisp).  The important differences to macros in, e.g., C are:
                   7175: 
                   7176: @itemize @bullet
                   7177: 
                   7178: @item
                   7179: You use the same language for defining and processing macros, not a
                   7180: separate preprocessing language and processor.
                   7181: 
                   7182: @item
                   7183: Consequently, the full power of Forth is available in macro definitions.
                   7184: E.g., you can perform arbitrarily complex computations, or generate
                   7185: different code conditionally or in a loop (e.g., @pxref{Advanced macros
                   7186: Tutorial}).  This power is very useful when writing a parser generators
                   7187: or other code-generating software.
                   7188: 
                   7189: @item
                   7190: Macros defined using @code{postpone} etc. deal with the language at a
                   7191: higher level than strings; name binding happens at macro definition
                   7192: time, so you can avoid the pitfalls of name collisions that can happen
                   7193: in C macros.  Of course, Forth is a liberal language and also allows to
                   7194: shoot yourself in the foot with text-interpreted macros like
                   7195: 
                   7196: @example
                   7197: : [compile-+] s" +" evaluate ; immediate
                   7198: @end example
                   7199: 
                   7200: Apart from binding the name at macro use time, using @code{evaluate}
                   7201: also makes your definition @code{state}-smart (@pxref{state-smartness}).
                   7202: @end itemize
                   7203: 
                   7204: You may want the macro to compile a number into a word.  The word to do
                   7205: it is @code{literal}, but you have to @code{postpone} it, so its
                   7206: compilation semantics take effect when the macro is executed, not when
                   7207: it is compiled:
                   7208: 
                   7209: @example
                   7210: : [compile-5] ( -- ) \ compiled code: ( -- n )
                   7211:   5 POSTPONE literal ; immediate
                   7212: 
                   7213: : foo [compile-5] ;
                   7214: foo .
                   7215: @end example
                   7216: 
                   7217: You may want to pass parameters to a macro, that the macro should
                   7218: compile into the current definition.  If the parameter is a number, then
                   7219: you can use @code{postpone literal} (similar for other values).
                   7220: 
                   7221: If you want to pass a word that is to be compiled, the usual way is to
                   7222: pass an execution token and @code{compile,} it:
                   7223: 
                   7224: @example
                   7225: : twice1 ( xt -- ) \ compiled code: ... -- ...
                   7226:   dup compile, compile, ;
                   7227: 
                   7228: : 2+ ( n1 -- n2 )
                   7229:   [ ' 1+ twice1 ] ;
                   7230: @end example
                   7231: 
                   7232: doc-compile,
                   7233: 
                   7234: An alternative available in Gforth, that allows you to pass compile-only
                   7235: words as parameters is to use the compilation token (@pxref{Compilation
                   7236: token}).  The same example in this technique:
                   7237: 
                   7238: @example
                   7239: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
                   7240:   2dup 2>r execute 2r> execute ;
                   7241: 
                   7242: : 2+ ( n1 -- n2 )
                   7243:   [ comp' 1+ twice ] ;
                   7244: @end example
                   7245: 
                   7246: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
                   7247: works even if the executed compilation semantics has an effect on the
                   7248: data stack.
                   7249: 
                   7250: You can also define complete definitions with these words; this provides
                   7251: an alternative to using @code{does>} (@pxref{User-defined Defining
                   7252: Words}).  E.g., instead of
                   7253: 
                   7254: @example
                   7255: : curry+ ( n1 "name" -- )
                   7256:     CREATE ,
                   7257: DOES> ( n2 -- n1+n2 )
                   7258:     @@ + ;
                   7259: @end example
                   7260: 
                   7261: you could define
                   7262: 
                   7263: @example
                   7264: : curry+ ( n1 "name" -- )
                   7265:   \ name execution: ( n2 -- n1+n2 )
                   7266:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81      anton    7267: 
1.82      anton    7268: -3 curry+ 3-
                   7269: see 3-
                   7270: @end example
1.81      anton    7271: 
1.82      anton    7272: The sequence @code{>r : r>} is necessary, because @code{:} puts a
                   7273: colon-sys on the data stack that makes everything below it unaccessible.
1.81      anton    7274: 
1.82      anton    7275: This way of writing defining words is sometimes more, sometimes less
                   7276: convenient than using @code{does>} (@pxref{Advanced does> usage
                   7277: example}).  One advantage of this method is that it can be optimized
                   7278: better, because the compiler knows that the value compiled with
                   7279: @code{literal} is fixed, whereas the data associated with a
                   7280: @code{create}d word can be changed.
1.47      crook    7281: 
1.26      crook    7282: @c ----------------------------------------------------------
1.111     anton    7283: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26      crook    7284: @section  The Text Interpreter
                   7285: @cindex interpreter - outer
                   7286: @cindex text interpreter
                   7287: @cindex outer interpreter
1.1       anton    7288: 
1.34      anton    7289: @c Should we really describe all these ugly details?  IMO the text
                   7290: @c interpreter should be much cleaner, but that may not be possible within
                   7291: @c ANS Forth. - anton
1.44      crook    7292: @c nac-> I wanted to explain how it works to show how you can exploit
                   7293: @c it in your own programs. When I was writing a cross-compiler, figuring out
                   7294: @c some of these gory details was very helpful to me. None of the textbooks
                   7295: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
                   7296: @c seems to positively avoid going into too much detail for some of
                   7297: @c the internals.
1.34      anton    7298: 
1.71      anton    7299: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
                   7300: @c it is; for the ugly details, I would prefer another place.  I wonder
                   7301: @c whether we should have a chapter before "Words" that describes some
                   7302: @c basic concepts referred to in words, and a chapter after "Words" that
                   7303: @c describes implementation details.
                   7304: 
1.29      crook    7305: The text interpreter@footnote{This is an expanded version of the
                   7306: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34      anton    7307: that processes input from the current input device. It is also called
                   7308: the outer interpreter, in contrast to the inner interpreter
                   7309: (@pxref{Engine}) which executes the compiled Forth code on interpretive
                   7310: implementations.
1.27      crook    7311: 
1.29      crook    7312: @cindex interpret state
                   7313: @cindex compile state
                   7314: The text interpreter operates in one of two states: @dfn{interpret
                   7315: state} and @dfn{compile state}. The current state is defined by the
1.71      anton    7316: aptly-named variable @code{state}.
1.29      crook    7317: 
                   7318: This section starts by describing how the text interpreter behaves when
                   7319: it is in interpret state, processing input from the user input device --
                   7320: the keyboard. This is the mode that a Forth system is in after it starts
                   7321: up.
                   7322: 
                   7323: @cindex input buffer
                   7324: @cindex terminal input buffer
                   7325: The text interpreter works from an area of memory called the @dfn{input
                   7326: buffer}@footnote{When the text interpreter is processing input from the
                   7327: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   7328: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   7329: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    7330: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    7331: leading spaces (called @dfn{delimiters}) then parses a string (a
                   7332: sequence of non-space characters) until it reaches either a space
                   7333: character or the end of the buffer. Having parsed a string, it makes two
                   7334: attempts to process it:
1.27      crook    7335: 
1.29      crook    7336: @cindex dictionary
1.27      crook    7337: @itemize @bullet
                   7338: @item
1.29      crook    7339: It looks for the string in a @dfn{dictionary} of definitions. If the
                   7340: string is found, the string names a @dfn{definition} (also known as a
                   7341: @dfn{word}) and the dictionary search returns information that allows
                   7342: the text interpreter to perform the word's @dfn{interpretation
                   7343: semantics}. In most cases, this simply means that the word will be
                   7344: executed.
1.27      crook    7345: @item
                   7346: If the string is not found in the dictionary, the text interpreter
1.29      crook    7347: attempts to treat it as a number, using the rules described in
                   7348: @ref{Number Conversion}. If the string represents a legal number in the
                   7349: current radix, the number is pushed onto a parameter stack (the data
                   7350: stack for integers, the floating-point stack for floating-point
                   7351: numbers).
                   7352: @end itemize
                   7353: 
                   7354: If both attempts fail, or if the word is found in the dictionary but has
                   7355: no interpretation semantics@footnote{This happens if the word was
                   7356: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   7357: remainder of the input buffer, issues an error message and waits for
                   7358: more input. If one of the attempts succeeds, the text interpreter
                   7359: repeats the parsing process until the whole of the input buffer has been
                   7360: processed, at which point it prints the status message ``@code{ ok}''
                   7361: and waits for more input.
                   7362: 
1.71      anton    7363: @c anton: this should be in the input stream subsection (or below it)
                   7364: 
1.29      crook    7365: @cindex parse area
                   7366: The text interpreter keeps track of its position in the input buffer by
                   7367: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   7368: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   7369: of the input buffer. The region from offset @code{>IN @@} to the end of
                   7370: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   7371: the text interpreter processes the contents of the input buffer by
                   7372: parsing strings from the parse area until the parse area is empty.}.
                   7373: This example shows how @code{>IN} changes as the text interpreter parses
                   7374: the input buffer:
                   7375: 
                   7376: @example
                   7377: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   7378:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   7379: 
                   7380: 1 2 3 remaining + remaining . 
                   7381: 
                   7382: : foo 1 2 3 remaining SWAP remaining ;
                   7383: @end example
                   7384: 
                   7385: @noindent
                   7386: The result is:
                   7387: 
                   7388: @example
                   7389: ->+ remaining .<-
                   7390: ->.<-5  ok
                   7391: 
                   7392: ->SWAP remaining ;-<
                   7393: ->;<-  ok
                   7394: @end example
                   7395: 
                   7396: @cindex parsing words
                   7397: The value of @code{>IN} can also be modified by a word in the input
                   7398: buffer that is executed by the text interpreter.  This means that a word
                   7399: can ``trick'' the text interpreter into either skipping a section of the
                   7400: input buffer@footnote{This is how parsing words work.} or into parsing a
                   7401: section twice. For example:
1.27      crook    7402: 
1.29      crook    7403: @example
1.71      anton    7404: : lat ." <<foo>>" ;
                   7405: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29      crook    7406: @end example
                   7407: 
                   7408: @noindent
                   7409: When @code{flat} is executed, this output is produced@footnote{Exercise
                   7410: for the reader: what would happen if the @code{3} were replaced with
                   7411: @code{4}?}:
                   7412: 
                   7413: @example
1.71      anton    7414: <<bar>><<foo>>
1.29      crook    7415: @end example
                   7416: 
1.71      anton    7417: This technique can be used to work around some of the interoperability
                   7418: problems of parsing words.  Of course, it's better to avoid parsing
                   7419: words where possible.
                   7420: 
1.29      crook    7421: @noindent
                   7422: Two important notes about the behaviour of the text interpreter:
1.27      crook    7423: 
                   7424: @itemize @bullet
                   7425: @item
                   7426: It processes each input string to completion before parsing additional
1.29      crook    7427: characters from the input buffer.
                   7428: @item
                   7429: It treats the input buffer as a read-only region (and so must your code).
                   7430: @end itemize
                   7431: 
                   7432: @noindent
                   7433: When the text interpreter is in compile state, its behaviour changes in
                   7434: these ways:
                   7435: 
                   7436: @itemize @bullet
                   7437: @item
                   7438: If a parsed string is found in the dictionary, the text interpreter will
                   7439: perform the word's @dfn{compilation semantics}. In most cases, this
                   7440: simply means that the execution semantics of the word will be appended
                   7441: to the current definition.
1.27      crook    7442: @item
1.29      crook    7443: When a number is encountered, it is compiled into the current definition
                   7444: (as a literal) rather than being pushed onto a parameter stack.
                   7445: @item
                   7446: If an error occurs, @code{state} is modified to put the text interpreter
                   7447: back into interpret state.
                   7448: @item
                   7449: Each time a line is entered from the keyboard, Gforth prints
                   7450: ``@code{ compiled}'' rather than `` @code{ok}''.
                   7451: @end itemize
                   7452: 
                   7453: @cindex text interpreter - input sources
                   7454: When the text interpreter is using an input device other than the
                   7455: keyboard, its behaviour changes in these ways:
                   7456: 
                   7457: @itemize @bullet
                   7458: @item
                   7459: When the parse area is empty, the text interpreter attempts to refill
                   7460: the input buffer from the input source. When the input source is
1.71      anton    7461: exhausted, the input source is set back to the previous input source.
1.29      crook    7462: @item
                   7463: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   7464: time the parse area is emptied.
                   7465: @item
                   7466: If an error occurs, the input source is set back to the user input
                   7467: device.
1.27      crook    7468: @end itemize
1.21      crook    7469: 
1.49      anton    7470: You can read about this in more detail in @ref{Input Sources}.
1.44      crook    7471: 
1.26      crook    7472: doc->in
1.27      crook    7473: doc-source
                   7474: 
1.26      crook    7475: doc-tib
                   7476: doc-#tib
1.1       anton    7477: 
1.44      crook    7478: 
1.26      crook    7479: @menu
1.67      anton    7480: * Input Sources::               
                   7481: * Number Conversion::           
                   7482: * Interpret/Compile states::    
                   7483: * Interpreter Directives::      
1.26      crook    7484: @end menu
1.1       anton    7485: 
1.29      crook    7486: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   7487: @subsection Input Sources
                   7488: @cindex input sources
                   7489: @cindex text interpreter - input sources
                   7490: 
1.44      crook    7491: By default, the text interpreter processes input from the user input
1.29      crook    7492: device (the keyboard) when Forth starts up. The text interpreter can
                   7493: process input from any of these sources:
                   7494: 
                   7495: @itemize @bullet
                   7496: @item
                   7497: The user input device -- the keyboard.
                   7498: @item
                   7499: A file, using the words described in @ref{Forth source files}.
                   7500: @item
                   7501: A block, using the words described in @ref{Blocks}.
                   7502: @item
                   7503: A text string, using @code{evaluate}.
                   7504: @end itemize
                   7505: 
                   7506: A program can identify the current input device from the values of
                   7507: @code{source-id} and @code{blk}.
                   7508: 
1.44      crook    7509: 
1.29      crook    7510: doc-source-id
                   7511: doc-blk
                   7512: 
                   7513: doc-save-input
                   7514: doc-restore-input
                   7515: 
                   7516: doc-evaluate
1.111     anton    7517: doc-query
1.1       anton    7518: 
1.29      crook    7519: 
1.44      crook    7520: 
1.29      crook    7521: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    7522: @subsection Number Conversion
                   7523: @cindex number conversion
                   7524: @cindex double-cell numbers, input format
                   7525: @cindex input format for double-cell numbers
                   7526: @cindex single-cell numbers, input format
                   7527: @cindex input format for single-cell numbers
                   7528: @cindex floating-point numbers, input format
                   7529: @cindex input format for floating-point numbers
1.1       anton    7530: 
1.29      crook    7531: This section describes the rules that the text interpreter uses when it
                   7532: tries to convert a string into a number.
1.1       anton    7533: 
1.26      crook    7534: Let <digit> represent any character that is a legal digit in the current
1.29      crook    7535: number base@footnote{For example, 0-9 when the number base is decimal or
                   7536: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    7537: 
1.26      crook    7538: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    7539: 
1.29      crook    7540: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   7541: in the braces (@i{a} or @i{b} or neither).
1.1       anton    7542: 
1.26      crook    7543: Let * represent any number of instances of the previous character
                   7544: (including none).
1.1       anton    7545: 
1.26      crook    7546: Let any other character represent itself.
1.1       anton    7547: 
1.29      crook    7548: @noindent
1.26      crook    7549: Now, the conversion rules are:
1.21      crook    7550: 
1.26      crook    7551: @itemize @bullet
                   7552: @item
                   7553: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    7554: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    7555: @item
                   7556: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    7557: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    7558: arithmetic. Examples are -45 -5681 -0
                   7559: @item
                   7560: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    7561: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   7562: (all three of these represent the same number).
1.26      crook    7563: @item
                   7564: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    7565: double-precision (double-cell-sized) negative integer, and is
1.26      crook    7566: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    7567: -34.65 (all three of these represent the same number).
1.26      crook    7568: @item
1.29      crook    7569: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   7570: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35      anton    7571: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    7572: number) +12.E-4
1.26      crook    7573: @end itemize
1.1       anton    7574: 
1.26      crook    7575: By default, the number base used for integer number conversion is given
1.35      anton    7576: by the contents of the variable @code{base}.  Note that a lot of
                   7577: confusion can result from unexpected values of @code{base}.  If you
                   7578: change @code{base} anywhere, make sure to save the old value and restore
                   7579: it afterwards.  In general I recommend keeping @code{base} decimal, and
                   7580: using the prefixes described below for the popular non-decimal bases.
1.1       anton    7581: 
1.29      crook    7582: doc-dpl
1.26      crook    7583: doc-base
                   7584: doc-hex
                   7585: doc-decimal
1.1       anton    7586: 
1.44      crook    7587: 
1.26      crook    7588: @cindex '-prefix for character strings
                   7589: @cindex &-prefix for decimal numbers
                   7590: @cindex %-prefix for binary numbers
                   7591: @cindex $-prefix for hexadecimal numbers
1.35      anton    7592: Gforth allows you to override the value of @code{base} by using a
1.29      crook    7593: prefix@footnote{Some Forth implementations provide a similar scheme by
                   7594: implementing @code{$} etc. as parsing words that process the subsequent
                   7595: number in the input stream and push it onto the stack. For example, see
                   7596: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   7597: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   7598: is required between the prefix and the number.} before the first digit
                   7599: of an (integer) number. Four prefixes are supported:
1.1       anton    7600: 
1.26      crook    7601: @itemize @bullet
                   7602: @item
1.35      anton    7603: @code{&} -- decimal
1.26      crook    7604: @item
1.35      anton    7605: @code{%} -- binary
1.26      crook    7606: @item
1.35      anton    7607: @code{$} -- hexadecimal
1.26      crook    7608: @item
1.35      anton    7609: @code{'} -- base @code{max-char+1}
1.26      crook    7610: @end itemize
1.1       anton    7611: 
1.26      crook    7612: Here are some examples, with the equivalent decimal number shown after
                   7613: in braces:
1.1       anton    7614: 
1.26      crook    7615: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
                   7616: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
                   7617: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
                   7618: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    7619: 
1.26      crook    7620: @cindex number conversion - traps for the unwary
1.29      crook    7621: @noindent
1.26      crook    7622: Number conversion has a number of traps for the unwary:
1.1       anton    7623: 
1.26      crook    7624: @itemize @bullet
                   7625: @item
                   7626: You cannot determine the current number base using the code sequence
1.35      anton    7627: @code{base @@ .} -- the number base is always 10 in the current number
                   7628: base. Instead, use something like @code{base @@ dec.}
1.26      crook    7629: @item
                   7630: If the number base is set to a value greater than 14 (for example,
                   7631: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   7632: it to be intepreted as either a single-precision integer or a
                   7633: floating-point number (Gforth treats it as an integer). The ambiguity
                   7634: can be resolved by explicitly stating the sign of the mantissa and/or
                   7635: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   7636: ambiguity arises; either representation will be treated as a
                   7637: floating-point number.
                   7638: @item
1.29      crook    7639: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    7640: It is used to specify file types.
                   7641: @item
1.72      anton    7642: ANS Forth requires the @code{.} of a double-precision number to be the
                   7643: final character in the string.  Gforth allows the @code{.} to be
                   7644: anywhere after the first digit.
1.26      crook    7645: @item
                   7646: The number conversion process does not check for overflow.
                   7647: @item
1.72      anton    7648: In an ANS Forth program @code{base} is required to be decimal when
                   7649: converting floating-point numbers.  In Gforth, number conversion to
                   7650: floating-point numbers always uses base &10, irrespective of the value
                   7651: of @code{base}.
1.26      crook    7652: @end itemize
1.1       anton    7653: 
1.49      anton    7654: You can read numbers into your programs with the words described in
                   7655: @ref{Input}.
1.1       anton    7656: 
1.82      anton    7657: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26      crook    7658: @subsection Interpret/Compile states
                   7659: @cindex Interpret/Compile states
1.1       anton    7660: 
1.29      crook    7661: A standard program is not permitted to change @code{state}
                   7662: explicitly. However, it can change @code{state} implicitly, using the
                   7663: words @code{[} and @code{]}. When @code{[} is executed it switches
                   7664: @code{state} to interpret state, and therefore the text interpreter
                   7665: starts interpreting. When @code{]} is executed it switches @code{state}
                   7666: to compile state and therefore the text interpreter starts
1.44      crook    7667: compiling. The most common usage for these words is for switching into
                   7668: interpret state and back from within a colon definition; this technique
1.49      anton    7669: can be used to compile a literal (for an example, @pxref{Literals}) or
                   7670: for conditional compilation (for an example, @pxref{Interpreter
                   7671: Directives}).
1.44      crook    7672: 
1.35      anton    7673: 
                   7674: @c This is a bad example: It's non-standard, and it's not necessary.
                   7675: @c However, I can't think of a good example for switching into compile
                   7676: @c state when there is no current word (@code{state}-smart words are not a
                   7677: @c good reason).  So maybe we should use an example for switching into
                   7678: @c interpret @code{state} in a colon def. - anton
1.44      crook    7679: @c nac-> I agree. I started out by putting in the example, then realised
                   7680: @c that it was non-ANS, so wrote more words around it. I hope this
                   7681: @c re-written version is acceptable to you. I do want to keep the example
                   7682: @c as it is helpful for showing what is and what is not portable, particularly
                   7683: @c where it outlaws a style in common use.
                   7684: 
1.72      anton    7685: @c anton: it's more important to show what's portable.  After we have done
1.83      anton    7686: @c that, we can also show what's not.  In any case, I have written a
                   7687: @c section Compiling Words which also deals with [ ].
1.35      anton    7688: 
1.95      anton    7689: @c  !! The following example does not work in Gforth 0.5.9 or later.
1.29      crook    7690: 
1.95      anton    7691: @c  @code{[} and @code{]} also give you the ability to switch into compile
                   7692: @c  state and back, but we cannot think of any useful Standard application
                   7693: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
                   7694: 
                   7695: @c  @example
                   7696: @c  : AA ." this is A" ;
                   7697: @c  : BB ." this is B" ;
                   7698: @c  : CC ." this is C" ;
                   7699: 
                   7700: @c  create table ] aa bb cc [
                   7701: 
                   7702: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   7703: @c    cells table + @@ execute ;
                   7704: @c  @end example
                   7705: 
                   7706: @c  This example builds a jump table; @code{0 go} will display ``@code{this
                   7707: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
                   7708: @c  defining @code{table} like this:
                   7709: 
                   7710: @c  @example
                   7711: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
                   7712: @c  @end example
                   7713: 
                   7714: @c  The problem with this code is that the definition of @code{table} is not
                   7715: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
                   7716: @c  @i{may} work on systems where code space and data space co-incide, the
                   7717: @c  Standard only allows data space to be assigned for a @code{CREATE}d
                   7718: @c  word. In addition, the Standard only allows @code{@@} to access data
                   7719: @c  space, whilst this example is using it to access code space. The only
                   7720: @c  portable, Standard way to build this table is to build it in data space,
                   7721: @c  like this:
                   7722: 
                   7723: @c  @example
                   7724: @c  create table ' aa , ' bb , ' cc ,
                   7725: @c  @end example
1.29      crook    7726: 
1.95      anton    7727: @c  doc-state
1.44      crook    7728: 
1.29      crook    7729: 
1.82      anton    7730: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
1.26      crook    7731: @subsection Interpreter Directives
                   7732: @cindex interpreter directives
1.72      anton    7733: @cindex conditional compilation
1.1       anton    7734: 
1.29      crook    7735: These words are usually used in interpret state; typically to control
                   7736: which parts of a source file are processed by the text
1.26      crook    7737: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   7738: supplements these with a rich set of immediate control structure words
                   7739: to compensate for the fact that the non-immediate versions can only be
1.29      crook    7740: used in compile state (@pxref{Control Structures}). Typical usages:
                   7741: 
                   7742: @example
1.72      anton    7743: FALSE Constant HAVE-ASSEMBLER
1.29      crook    7744: .
                   7745: .
1.72      anton    7746: HAVE-ASSEMBLER [IF]
1.29      crook    7747: : ASSEMBLER-FEATURE
                   7748:   ...
                   7749: ;
                   7750: [ENDIF]
                   7751: .
                   7752: .
                   7753: : SEE
                   7754:   ... \ general-purpose SEE code
1.72      anton    7755:   [ HAVE-ASSEMBLER [IF] ]
1.29      crook    7756:   ... \ assembler-specific SEE code
                   7757:   [ [ENDIF] ]
                   7758: ;
                   7759: @end example
1.1       anton    7760: 
1.44      crook    7761: 
1.26      crook    7762: doc-[IF]
                   7763: doc-[ELSE]
                   7764: doc-[THEN]
                   7765: doc-[ENDIF]
1.1       anton    7766: 
1.26      crook    7767: doc-[IFDEF]
                   7768: doc-[IFUNDEF]
1.1       anton    7769: 
1.26      crook    7770: doc-[?DO]
                   7771: doc-[DO]
                   7772: doc-[FOR]
                   7773: doc-[LOOP]
                   7774: doc-[+LOOP]
                   7775: doc-[NEXT]
1.1       anton    7776: 
1.26      crook    7777: doc-[BEGIN]
                   7778: doc-[UNTIL]
                   7779: doc-[AGAIN]
                   7780: doc-[WHILE]
                   7781: doc-[REPEAT]
1.1       anton    7782: 
1.27      crook    7783: 
1.26      crook    7784: @c -------------------------------------------------------------
1.111     anton    7785: @node The Input Stream, Word Lists, The Text Interpreter, Words
                   7786: @section The Input Stream
                   7787: @cindex input stream
                   7788: 
                   7789: @c !! integrate this better with the "Text Interpreter" section
                   7790: The text interpreter reads from the input stream, which can come from
                   7791: several sources (@pxref{Input Sources}).  Some words, in particular
                   7792: defining words, but also words like @code{'}, read parameters from the
                   7793: input stream instead of from the stack.
                   7794: 
                   7795: Such words are called parsing words, because they parse the input
                   7796: stream.  Parsing words are hard to use in other words, because it is
                   7797: hard to pass program-generated parameters through the input stream.
                   7798: They also usually have an unintuitive combination of interpretation and
                   7799: compilation semantics when implemented naively, leading to various
                   7800: approaches that try to produce a more intuitive behaviour
                   7801: (@pxref{Combined words}).
                   7802: 
                   7803: It should be obvious by now that parsing words are a bad idea.  If you
                   7804: want to implement a parsing word for convenience, also provide a factor
                   7805: of the word that does not parse, but takes the parameters on the stack.
                   7806: To implement the parsing word on top if it, you can use the following
                   7807: words:
                   7808: 
                   7809: @c anton: these belong in the input stream section
                   7810: doc-parse
                   7811: doc-parse-word
                   7812: doc-name
                   7813: doc-word
                   7814: doc-\"-parse
                   7815: doc-refill
                   7816: 
                   7817: Conversely, if you have the bad luck (or lack of foresight) to have to
                   7818: deal with parsing words without having such factors, how do you pass a
                   7819: string that is not in the input stream to it?
                   7820: 
                   7821: doc-execute-parsing
                   7822: 
                   7823: If you want to run a parsing word on a file, the following word should
                   7824: help:
                   7825: 
                   7826: doc-execute-parsing-file
                   7827: 
                   7828: @c -------------------------------------------------------------
                   7829: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26      crook    7830: @section Word Lists
                   7831: @cindex word lists
1.32      anton    7832: @cindex header space
1.1       anton    7833: 
1.36      anton    7834: A wordlist is a list of named words; you can add new words and look up
                   7835: words by name (and you can remove words in a restricted way with
                   7836: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
                   7837: 
                   7838: @cindex search order stack
                   7839: The text interpreter searches the wordlists present in the search order
                   7840: (a stack of wordlists), from the top to the bottom.  Within each
                   7841: wordlist, the search starts conceptually at the newest word; i.e., if
                   7842: two words in a wordlist have the same name, the newer word is found.
1.1       anton    7843: 
1.26      crook    7844: @cindex compilation word list
1.36      anton    7845: New words are added to the @dfn{compilation wordlist} (aka current
                   7846: wordlist).
1.1       anton    7847: 
1.36      anton    7848: @cindex wid
                   7849: A word list is identified by a cell-sized word list identifier (@i{wid})
                   7850: in much the same way as a file is identified by a file handle. The
                   7851: numerical value of the wid has no (portable) meaning, and might change
                   7852: from session to session.
1.1       anton    7853: 
1.29      crook    7854: The ANS Forth ``Search order'' word set is intended to provide a set of
                   7855: low-level tools that allow various different schemes to be
1.74      anton    7856: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26      crook    7857: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
1.45      crook    7858: Forth.
1.1       anton    7859: 
1.27      crook    7860: @comment TODO: locals section refers to here, saying that every word list (aka
                   7861: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78      anton    7862: @c anton: but better in a separate subsection on wordlist internals
1.1       anton    7863: 
1.45      crook    7864: @comment TODO: document markers, reveal, tables, mappedwordlist
                   7865: 
                   7866: @comment the gforthman- prefix is used to pick out the true definition of a
1.27      crook    7867: @comment word from the source files, rather than some alias.
1.44      crook    7868: 
1.26      crook    7869: doc-forth-wordlist
                   7870: doc-definitions
                   7871: doc-get-current
                   7872: doc-set-current
                   7873: doc-get-order
1.45      crook    7874: doc---gforthman-set-order
1.26      crook    7875: doc-wordlist
1.30      anton    7876: doc-table
1.79      anton    7877: doc->order
1.36      anton    7878: doc-previous
1.26      crook    7879: doc-also
1.45      crook    7880: doc---gforthman-forth
1.26      crook    7881: doc-only
1.45      crook    7882: doc---gforthman-order
1.15      anton    7883: 
1.26      crook    7884: doc-find
                   7885: doc-search-wordlist
1.15      anton    7886: 
1.26      crook    7887: doc-words
                   7888: doc-vlist
1.44      crook    7889: @c doc-words-deferred
1.1       anton    7890: 
1.74      anton    7891: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26      crook    7892: doc-root
                   7893: doc-vocabulary
                   7894: doc-seal
                   7895: doc-vocs
                   7896: doc-current
                   7897: doc-context
1.1       anton    7898: 
1.44      crook    7899: 
1.26      crook    7900: @menu
1.75      anton    7901: * Vocabularies::                
1.67      anton    7902: * Why use word lists?::         
1.75      anton    7903: * Word list example::           
1.26      crook    7904: @end menu
                   7905: 
1.75      anton    7906: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
                   7907: @subsection Vocabularies
                   7908: @cindex Vocabularies, detailed explanation
                   7909: 
                   7910: Here is an example of creating and using a new wordlist using ANS
                   7911: Forth words:
                   7912: 
                   7913: @example
                   7914: wordlist constant my-new-words-wordlist
                   7915: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
                   7916: 
                   7917: \ add it to the search order
                   7918: also my-new-words
                   7919: 
                   7920: \ alternatively, add it to the search order and make it
                   7921: \ the compilation word list
                   7922: also my-new-words definitions
                   7923: \ type "order" to see the problem
                   7924: @end example
                   7925: 
                   7926: The problem with this example is that @code{order} has no way to
                   7927: associate the name @code{my-new-words} with the wid of the word list (in
                   7928: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   7929: that has no associated name). There is no Standard way of associating a
                   7930: name with a wid.
                   7931: 
                   7932: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   7933: associates a name with a wid:
                   7934: 
                   7935: @example
                   7936: vocabulary my-new-words
                   7937: 
                   7938: \ add it to the search order
                   7939: also my-new-words
                   7940: 
                   7941: \ alternatively, add it to the search order and make it
                   7942: \ the compilation word list
                   7943: my-new-words definitions
                   7944: \ type "order" to see that the problem is solved
                   7945: @end example
                   7946: 
                   7947: 
                   7948: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26      crook    7949: @subsection Why use word lists?
                   7950: @cindex word lists - why use them?
                   7951: 
1.74      anton    7952: Here are some reasons why people use wordlists:
1.26      crook    7953: 
                   7954: @itemize @bullet
1.74      anton    7955: 
                   7956: @c anton: Gforth's hashing implementation makes the search speed
                   7957: @c independent from the number of words.  But it is linear with the number
                   7958: @c of wordlists that have to be searched, so in effect using more wordlists
                   7959: @c actually slows down compilation.
                   7960: 
                   7961: @c @item
                   7962: @c To improve compilation speed by reducing the number of header space
                   7963: @c entries that must be searched. This is achieved by creating a new
                   7964: @c word list that contains all of the definitions that are used in the
                   7965: @c definition of a Forth system but which would not usually be used by
                   7966: @c programs running on that system. That word list would be on the search
                   7967: @c list when the Forth system was compiled but would be removed from the
                   7968: @c search list for normal operation. This can be a useful technique for
                   7969: @c low-performance systems (for example, 8-bit processors in embedded
                   7970: @c systems) but is unlikely to be necessary in high-performance desktop
                   7971: @c systems.
                   7972: 
1.26      crook    7973: @item
                   7974: To prevent a set of words from being used outside the context in which
                   7975: they are valid. Two classic examples of this are an integrated editor
                   7976: (all of the edit commands are defined in a separate word list; the
                   7977: search order is set to the editor word list when the editor is invoked;
                   7978: the old search order is restored when the editor is terminated) and an
                   7979: integrated assembler (the op-codes for the machine are defined in a
                   7980: separate word list which is used when a @code{CODE} word is defined).
1.74      anton    7981: 
                   7982: @item
                   7983: To organize the words of an application or library into a user-visible
                   7984: set (in @code{forth-wordlist} or some other common wordlist) and a set
                   7985: of helper words used just for the implementation (hidden in a separate
1.75      anton    7986: wordlist).  This keeps @code{words}' output smaller, separates
                   7987: implementation and interface, and reduces the chance of name conflicts
                   7988: within the common wordlist.
1.74      anton    7989: 
1.26      crook    7990: @item
                   7991: To prevent a name-space clash between multiple definitions with the same
                   7992: name. For example, when building a cross-compiler you might have a word
                   7993: @code{IF} that generates conditional code for your target system. By
                   7994: placing this definition in a different word list you can control whether
                   7995: the host system's @code{IF} or the target system's @code{IF} get used in
                   7996: any particular context by controlling the order of the word lists on the
                   7997: search order stack.
1.74      anton    7998: 
1.26      crook    7999: @end itemize
1.1       anton    8000: 
1.74      anton    8001: The downsides of using wordlists are:
                   8002: 
                   8003: @itemize
                   8004: 
                   8005: @item
                   8006: Debugging becomes more cumbersome.
                   8007: 
                   8008: @item
                   8009: Name conflicts worked around with wordlists are still there, and you
                   8010: have to arrange the search order carefully to get the desired results;
                   8011: if you forget to do that, you get hard-to-find errors (as in any case
                   8012: where you read the code differently from the compiler; @code{see} can
1.75      anton    8013: help seeing which of several possible words the name resolves to in such
                   8014: cases).  @code{See} displays just the name of the words, not what
                   8015: wordlist they belong to, so it might be misleading.  Using unique names
                   8016: is a better approach to avoid name conflicts.
1.74      anton    8017: 
                   8018: @item
                   8019: You have to explicitly undo any changes to the search order.  In many
                   8020: cases it would be more convenient if this happened implicitly.  Gforth
                   8021: currently does not provide such a feature, but it may do so in the
                   8022: future.
                   8023: @end itemize
                   8024: 
                   8025: 
1.75      anton    8026: @node Word list example,  , Why use word lists?, Word Lists
                   8027: @subsection Word list example
                   8028: @cindex word lists - example
1.1       anton    8029: 
1.74      anton    8030: The following example is from the
                   8031: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   8032: garbage collector} and uses wordlists to separate public words from
                   8033: helper words:
                   8034: 
                   8035: @example
                   8036: get-current ( wid )
                   8037: vocabulary garbage-collector also garbage-collector definitions
                   8038: ... \ define helper words
                   8039: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
                   8040: ... \ define the public (i.e., API) words
                   8041:     \ they can refer to the helper words
                   8042: previous \ restore original search order (helper words become invisible)
                   8043: @end example
                   8044: 
1.26      crook    8045: @c -------------------------------------------------------------
                   8046: @node Environmental Queries, Files, Word Lists, Words
                   8047: @section Environmental Queries
                   8048: @cindex environmental queries
1.21      crook    8049: 
1.26      crook    8050: ANS Forth introduced the idea of ``environmental queries'' as a way
                   8051: for a program running on a system to determine certain characteristics of the system.
                   8052: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    8053: 
1.32      anton    8054: The Standard requires that the header space used for environmental queries
                   8055: be distinct from the header space used for definitions.
1.21      crook    8056: 
1.26      crook    8057: Typically, environmental queries are supported by creating a set of
1.29      crook    8058: definitions in a word list that is @i{only} used during environmental
1.26      crook    8059: queries; that is what Gforth does. There is no Standard way of adding
                   8060: definitions to the set of recognised environmental queries, but any
                   8061: implementation that supports the loading of optional word sets must have
                   8062: some mechanism for doing this (after loading the word set, the
                   8063: associated environmental query string must return @code{true}). In
                   8064: Gforth, the word list used to honour environmental queries can be
                   8065: manipulated just like any other word list.
1.21      crook    8066: 
1.44      crook    8067: 
1.26      crook    8068: doc-environment?
                   8069: doc-environment-wordlist
1.21      crook    8070: 
1.26      crook    8071: doc-gforth
                   8072: doc-os-class
1.21      crook    8073: 
1.44      crook    8074: 
1.26      crook    8075: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   8076: returning two items on the stack, querying it using @code{environment?}
                   8077: will return an additional item; the @code{true} flag that shows that the
                   8078: string was recognised.
1.21      crook    8079: 
1.26      crook    8080: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    8081: 
1.26      crook    8082: Here are some examples of using environmental queries:
1.21      crook    8083: 
1.26      crook    8084: @example
                   8085: s" address-unit-bits" environment? 0=
                   8086: [IF]
                   8087:      cr .( environmental attribute address-units-bits unknown... ) cr
1.75      anton    8088: [ELSE]
                   8089:      drop \ ensure balanced stack effect
1.26      crook    8090: [THEN]
1.21      crook    8091: 
1.75      anton    8092: \ this might occur in the prelude of a standard program that uses THROW
                   8093: s" exception" environment? [IF]
                   8094:    0= [IF]
                   8095:       : throw abort" exception thrown" ;
                   8096:    [THEN]
                   8097: [ELSE] \ we don't know, so make sure
                   8098:    : throw abort" exception thrown" ;
                   8099: [THEN]
1.21      crook    8100: 
1.26      crook    8101: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   8102:                         [ELSE] .( Not Gforth..) [THEN]
1.75      anton    8103: 
                   8104: \ a program using v*
                   8105: s" gforth" environment? [IF]
                   8106:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
                   8107:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8108:      >r swap 2swap swap 0e r> 0 ?DO
                   8109:        dup f@ over + 2swap dup f@ f* f+ over + 2swap
                   8110:      LOOP
                   8111:      2drop 2drop ; 
                   8112:   [THEN]
                   8113: [ELSE] \ 
                   8114:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8115:   ...
                   8116: [THEN]
1.26      crook    8117: @end example
1.21      crook    8118: 
1.26      crook    8119: Here is an example of adding a definition to the environment word list:
1.21      crook    8120: 
1.26      crook    8121: @example
                   8122: get-current environment-wordlist set-current
                   8123: true constant block
                   8124: true constant block-ext
                   8125: set-current
                   8126: @end example
1.21      crook    8127: 
1.26      crook    8128: You can see what definitions are in the environment word list like this:
1.21      crook    8129: 
1.26      crook    8130: @example
1.79      anton    8131: environment-wordlist >order words previous
1.26      crook    8132: @end example
1.21      crook    8133: 
                   8134: 
1.26      crook    8135: @c -------------------------------------------------------------
                   8136: @node Files, Blocks, Environmental Queries, Words
                   8137: @section Files
1.28      crook    8138: @cindex files
                   8139: @cindex I/O - file-handling
1.21      crook    8140: 
1.26      crook    8141: Gforth provides facilities for accessing files that are stored in the
                   8142: host operating system's file-system. Files that are processed by Gforth
                   8143: can be divided into two categories:
1.21      crook    8144: 
1.23      crook    8145: @itemize @bullet
                   8146: @item
1.29      crook    8147: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    8148: @item
1.29      crook    8149: Files that are processed by some other program (@dfn{general files}).
1.26      crook    8150: @end itemize
                   8151: 
                   8152: @menu
1.48      anton    8153: * Forth source files::          
                   8154: * General files::               
                   8155: * Search Paths::                
1.26      crook    8156: @end menu
                   8157: 
                   8158: @c -------------------------------------------------------------
                   8159: @node Forth source files, General files, Files, Files
                   8160: @subsection Forth source files
                   8161: @cindex including files
                   8162: @cindex Forth source files
1.21      crook    8163: 
1.26      crook    8164: The simplest way to interpret the contents of a file is to use one of
                   8165: these two formats:
1.21      crook    8166: 
1.26      crook    8167: @example
                   8168: include mysource.fs
                   8169: s" mysource.fs" included
                   8170: @end example
1.21      crook    8171: 
1.75      anton    8172: You usually want to include a file only if it is not included already
1.26      crook    8173: (by, say, another source file). In that case, you can use one of these
1.45      crook    8174: three formats:
1.21      crook    8175: 
1.26      crook    8176: @example
                   8177: require mysource.fs
                   8178: needs mysource.fs
                   8179: s" mysource.fs" required
                   8180: @end example
1.21      crook    8181: 
1.26      crook    8182: @cindex stack effect of included files
                   8183: @cindex including files, stack effect
1.45      crook    8184: It is good practice to write your source files such that interpreting them
                   8185: does not change the stack. Source files designed in this way can be used with
1.26      crook    8186: @code{required} and friends without complications. For example:
1.21      crook    8187: 
1.26      crook    8188: @example
1.75      anton    8189: 1024 require foo.fs drop
1.26      crook    8190: @end example
1.21      crook    8191: 
1.75      anton    8192: Here you want to pass the argument 1024 (e.g., a buffer size) to
                   8193: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
                   8194: ), which allows its use with @code{require}.  Of course with such
                   8195: parameters to required files, you have to ensure that the first
                   8196: @code{require} fits for all uses (i.e., @code{require} it early in the
                   8197: master load file).
1.44      crook    8198: 
1.26      crook    8199: doc-include-file
                   8200: doc-included
1.28      crook    8201: doc-included?
1.26      crook    8202: doc-include
                   8203: doc-required
                   8204: doc-require
                   8205: doc-needs
1.75      anton    8206: @c doc-init-included-files @c internal
                   8207: doc-sourcefilename
                   8208: doc-sourceline#
1.44      crook    8209: 
1.26      crook    8210: A definition in ANS Forth for @code{required} is provided in
                   8211: @file{compat/required.fs}.
1.21      crook    8212: 
1.26      crook    8213: @c -------------------------------------------------------------
                   8214: @node General files, Search Paths, Forth source files, Files
                   8215: @subsection General files
                   8216: @cindex general files
                   8217: @cindex file-handling
1.21      crook    8218: 
1.75      anton    8219: Files are opened/created by name and type. The following file access
                   8220: methods (FAMs) are recognised:
1.44      crook    8221: 
1.75      anton    8222: @cindex fam (file access method)
1.26      crook    8223: doc-r/o
                   8224: doc-r/w
                   8225: doc-w/o
                   8226: doc-bin
1.1       anton    8227: 
1.44      crook    8228: 
1.26      crook    8229: When a file is opened/created, it returns a file identifier,
1.29      crook    8230: @i{wfileid} that is used for all other file commands. All file
                   8231: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    8232: successful operation and an implementation-defined non-zero value in the
                   8233: case of an error.
1.21      crook    8234: 
1.44      crook    8235: 
1.26      crook    8236: doc-open-file
                   8237: doc-create-file
1.21      crook    8238: 
1.26      crook    8239: doc-close-file
                   8240: doc-delete-file
                   8241: doc-rename-file
                   8242: doc-read-file
                   8243: doc-read-line
                   8244: doc-write-file
                   8245: doc-write-line
                   8246: doc-emit-file
                   8247: doc-flush-file
1.21      crook    8248: 
1.26      crook    8249: doc-file-status
                   8250: doc-file-position
                   8251: doc-reposition-file
                   8252: doc-file-size
                   8253: doc-resize-file
1.21      crook    8254: 
1.93      anton    8255: doc-slurp-file
                   8256: doc-slurp-fid
1.112     anton    8257: doc-stdin
                   8258: doc-stdout
                   8259: doc-stderr
1.44      crook    8260: 
1.26      crook    8261: @c ---------------------------------------------------------
1.48      anton    8262: @node Search Paths,  , General files, Files
1.26      crook    8263: @subsection Search Paths
                   8264: @cindex path for @code{included}
                   8265: @cindex file search path
                   8266: @cindex @code{include} search path
                   8267: @cindex search path for files
1.21      crook    8268: 
1.26      crook    8269: If you specify an absolute filename (i.e., a filename starting with
                   8270: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   8271: @samp{C:...})) for @code{included} and friends, that file is included
                   8272: just as you would expect.
1.21      crook    8273: 
1.75      anton    8274: If the filename starts with @file{./}, this refers to the directory that
                   8275: the present file was @code{included} from.  This allows files to include
                   8276: other files relative to their own position (irrespective of the current
                   8277: working directory or the absolute position).  This feature is essential
                   8278: for libraries consisting of several files, where a file may include
                   8279: other files from the library.  It corresponds to @code{#include "..."}
                   8280: in C. If the current input source is not a file, @file{.} refers to the
                   8281: directory of the innermost file being included, or, if there is no file
                   8282: being included, to the current working directory.
                   8283: 
                   8284: For relative filenames (not starting with @file{./}), Gforth uses a
                   8285: search path similar to Forth's search order (@pxref{Word Lists}). It
                   8286: tries to find the given filename in the directories present in the path,
                   8287: and includes the first one it finds. There are separate search paths for
                   8288: Forth source files and general files.  If the search path contains the
                   8289: directory @file{.}, this refers to the directory of the current file, or
                   8290: the working directory, as if the file had been specified with @file{./}.
1.21      crook    8291: 
1.26      crook    8292: Use @file{~+} to refer to the current working directory (as in the
                   8293: @code{bash}).
1.1       anton    8294: 
1.75      anton    8295: @c anton: fold the following subsubsections into this subsection?
1.1       anton    8296: 
1.48      anton    8297: @menu
1.75      anton    8298: * Source Search Paths::         
1.48      anton    8299: * General Search Paths::        
                   8300: @end menu
                   8301: 
1.26      crook    8302: @c ---------------------------------------------------------
1.75      anton    8303: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
                   8304: @subsubsection Source Search Paths
                   8305: @cindex search path control, source files
1.5       anton    8306: 
1.26      crook    8307: The search path is initialized when you start Gforth (@pxref{Invoking
1.75      anton    8308: Gforth}). You can display it and change it using @code{fpath} in
                   8309: combination with the general path handling words.
1.5       anton    8310: 
1.75      anton    8311: doc-fpath
                   8312: @c the functionality of the following words is easily available through
                   8313: @c   fpath and the general path words.  The may go away.
                   8314: @c doc-.fpath
                   8315: @c doc-fpath+
                   8316: @c doc-fpath=
                   8317: @c doc-open-fpath-file
1.44      crook    8318: 
                   8319: @noindent
1.26      crook    8320: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    8321: 
1.26      crook    8322: @example
1.75      anton    8323: fpath path= /usr/lib/forth/|./
1.26      crook    8324: require timer.fs
                   8325: @end example
1.5       anton    8326: 
1.75      anton    8327: 
1.26      crook    8328: @c ---------------------------------------------------------
1.75      anton    8329: @node General Search Paths,  , Source Search Paths, Search Paths
1.26      crook    8330: @subsubsection General Search Paths
1.75      anton    8331: @cindex search path control, source files
1.5       anton    8332: 
1.26      crook    8333: Your application may need to search files in several directories, like
                   8334: @code{included} does. To facilitate this, Gforth allows you to define
                   8335: and use your own search paths, by providing generic equivalents of the
                   8336: Forth search path words:
1.5       anton    8337: 
1.75      anton    8338: doc-open-path-file
                   8339: doc-path-allot
                   8340: doc-clear-path
                   8341: doc-also-path
1.26      crook    8342: doc-.path
                   8343: doc-path+
                   8344: doc-path=
1.5       anton    8345: 
1.75      anton    8346: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44      crook    8347: 
1.75      anton    8348: Here's an example of creating an empty search path:
                   8349: @c
1.26      crook    8350: @example
1.75      anton    8351: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26      crook    8352: @end example
1.5       anton    8353: 
1.26      crook    8354: @c -------------------------------------------------------------
                   8355: @node Blocks, Other I/O, Files, Words
                   8356: @section Blocks
1.28      crook    8357: @cindex I/O - blocks
                   8358: @cindex blocks
                   8359: 
                   8360: When you run Gforth on a modern desk-top computer, it runs under the
                   8361: control of an operating system which provides certain services.  One of
                   8362: these services is @var{file services}, which allows Forth source code
                   8363: and data to be stored in files and read into Gforth (@pxref{Files}).
                   8364: 
                   8365: Traditionally, Forth has been an important programming language on
                   8366: systems where it has interfaced directly to the underlying hardware with
                   8367: no intervening operating system. Forth provides a mechanism, called
1.29      crook    8368: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    8369: 
                   8370: A block is a 1024-byte data area, which can be used to hold data or
                   8371: Forth source code. No structure is imposed on the contents of the
                   8372: block. A block is identified by its number; blocks are numbered
                   8373: contiguously from 1 to an implementation-defined maximum.
                   8374: 
                   8375: A typical system that used blocks but no operating system might use a
                   8376: single floppy-disk drive for mass storage, with the disks formatted to
                   8377: provide 256-byte sectors. Blocks would be implemented by assigning the
                   8378: first four sectors of the disk to block 1, the second four sectors to
                   8379: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   8380: would not contain any file system information, just the set of blocks.
                   8381: 
1.29      crook    8382: @cindex blocks file
1.28      crook    8383: On systems that do provide file services, blocks are typically
1.29      crook    8384: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    8385: file}.  The size of the blocks file will be an exact multiple of 1024
                   8386: bytes, corresponding to the number of blocks it contains. This is the
                   8387: mechanism that Gforth uses.
                   8388: 
1.29      crook    8389: @cindex @file{blocks.fb}
1.75      anton    8390: Only one blocks file can be open at a time. If you use block words without
1.28      crook    8391: having specified a blocks file, Gforth defaults to the blocks file
                   8392: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75      anton    8393: locate a blocks file (@pxref{Source Search Paths}).
1.28      crook    8394: 
1.29      crook    8395: @cindex block buffers
1.28      crook    8396: When you read and write blocks under program control, Gforth uses a
1.29      crook    8397: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    8398: not used when you use @code{load} to interpret the contents of a block.
                   8399: 
1.75      anton    8400: The behaviour of the block buffers is analagous to that of a cache.
                   8401: Each block buffer has three states:
1.28      crook    8402: 
                   8403: @itemize @bullet
                   8404: @item
                   8405: Unassigned
                   8406: @item
                   8407: Assigned-clean
                   8408: @item
                   8409: Assigned-dirty
                   8410: @end itemize
                   8411: 
1.29      crook    8412: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    8413: block, the block (specified by its block number) must be assigned to a
                   8414: block buffer.
                   8415: 
                   8416: The assignment of a block to a block buffer is performed by @code{block}
                   8417: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   8418: contents of a block. Use @code{buffer} when you don't care about the
                   8419: existing contents of the block@footnote{The ANS Forth definition of
1.35      anton    8420: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28      crook    8421: with the particular block is already stored in a block buffer due to an
                   8422: earlier @code{block} command, @code{buffer} will return that block
                   8423: buffer and the existing contents of the block will be
                   8424: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    8425: block buffer for the block.}.
1.28      crook    8426: 
1.47      crook    8427: Once a block has been assigned to a block buffer using @code{block} or
1.75      anton    8428: @code{buffer}, that block buffer becomes the @i{current block
                   8429: buffer}. Data may only be manipulated (read or written) within the
                   8430: current block buffer.
1.47      crook    8431: 
                   8432: When the contents of the current block buffer has been modified it is
1.48      anton    8433: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75      anton    8434: either abandon the changes (by doing nothing) or mark the block as
                   8435: changed (assigned-dirty), using @code{update}. Using @code{update} does
                   8436: not change the blocks file; it simply changes a block buffer's state to
                   8437: @i{assigned-dirty}.  The block will be written implicitly when it's
                   8438: buffer is needed for another block, or explicitly by @code{flush} or
                   8439: @code{save-buffers}.
                   8440: 
                   8441: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
                   8442: blocks file on disk. Leaving Gforth with @code{bye} also performs a
                   8443: @code{flush}.
1.28      crook    8444: 
1.29      crook    8445: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    8446: algorithm to assign a block buffer to a block. That means that any
                   8447: particular block can only be assigned to one specific block buffer,
1.29      crook    8448: called (for the particular operation) the @i{victim buffer}. If the
1.47      crook    8449: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
                   8450: the new block immediately. If it is @i{assigned-dirty} its current
                   8451: contents are written back to the blocks file on disk before it is
1.28      crook    8452: allocated to the new block.
                   8453: 
                   8454: Although no structure is imposed on the contents of a block, it is
                   8455: traditional to display the contents as 16 lines each of 64 characters.  A
                   8456: block provides a single, continuous stream of input (for example, it
                   8457: acts as a single parse area) -- there are no end-of-line characters
                   8458: within a block, and no end-of-file character at the end of a
                   8459: block. There are two consequences of this:
1.26      crook    8460: 
1.28      crook    8461: @itemize @bullet
                   8462: @item
                   8463: The last character of one line wraps straight into the first character
                   8464: of the following line
                   8465: @item
                   8466: The word @code{\} -- comment to end of line -- requires special
                   8467: treatment; in the context of a block it causes all characters until the
                   8468: end of the current 64-character ``line'' to be ignored.
                   8469: @end itemize
                   8470: 
                   8471: In Gforth, when you use @code{block} with a non-existent block number,
1.45      crook    8472: the current blocks file will be extended to the appropriate size and the
1.28      crook    8473: block buffer will be initialised with spaces.
                   8474: 
1.47      crook    8475: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
                   8476: for details) but doesn't encourage the use of blocks; the mechanism is
                   8477: only provided for backward compatibility -- ANS Forth requires blocks to
                   8478: be available when files are.
1.28      crook    8479: 
                   8480: Common techniques that are used when working with blocks include:
                   8481: 
                   8482: @itemize @bullet
                   8483: @item
                   8484: A screen editor that allows you to edit blocks without leaving the Forth
                   8485: environment.
                   8486: @item
                   8487: Shadow screens; where every code block has an associated block
                   8488: containing comments (for example: code in odd block numbers, comments in
                   8489: even block numbers). Typically, the block editor provides a convenient
                   8490: mechanism to toggle between code and comments.
                   8491: @item
                   8492: Load blocks; a single block (typically block 1) contains a number of
                   8493: @code{thru} commands which @code{load} the whole of the application.
                   8494: @end itemize
1.26      crook    8495: 
1.29      crook    8496: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   8497: integrated into a Forth programming environment.
1.26      crook    8498: 
                   8499: @comment TODO what about errors on open-blocks?
1.44      crook    8500: 
1.26      crook    8501: doc-open-blocks
                   8502: doc-use
1.75      anton    8503: doc-block-offset
1.26      crook    8504: doc-get-block-fid
                   8505: doc-block-position
1.28      crook    8506: 
1.75      anton    8507: doc-list
1.28      crook    8508: doc-scr
                   8509: 
1.45      crook    8510: doc---gforthman-block
1.28      crook    8511: doc-buffer
                   8512: 
1.75      anton    8513: doc-empty-buffers
                   8514: doc-empty-buffer
1.26      crook    8515: doc-update
1.28      crook    8516: doc-updated?
1.26      crook    8517: doc-save-buffers
1.75      anton    8518: doc-save-buffer
1.26      crook    8519: doc-flush
1.28      crook    8520: 
1.26      crook    8521: doc-load
                   8522: doc-thru
                   8523: doc-+load
                   8524: doc-+thru
1.45      crook    8525: doc---gforthman--->
1.26      crook    8526: doc-block-included
                   8527: 
1.44      crook    8528: 
1.26      crook    8529: @c -------------------------------------------------------------
1.78      anton    8530: @node Other I/O, Locals, Blocks, Words
1.26      crook    8531: @section Other I/O
1.28      crook    8532: @cindex I/O - keyboard and display
1.26      crook    8533: 
                   8534: @menu
                   8535: * Simple numeric output::       Predefined formats
                   8536: * Formatted numeric output::    Formatted (pictured) output
                   8537: * String Formats::              How Forth stores strings in memory
1.67      anton    8538: * Displaying characters and strings::  Other stuff
1.26      crook    8539: * Input::                       Input
1.112     anton    8540: * Pipes::                       How to create your own pipes
1.26      crook    8541: @end menu
                   8542: 
                   8543: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   8544: @subsection Simple numeric output
1.28      crook    8545: @cindex numeric output - simple/free-format
1.5       anton    8546: 
1.26      crook    8547: The simplest output functions are those that display numbers from the
                   8548: data or floating-point stacks. Floating-point output is always displayed
                   8549: using base 10. Numbers displayed from the data stack use the value stored
                   8550: in @code{base}.
1.5       anton    8551: 
1.44      crook    8552: 
1.26      crook    8553: doc-.
                   8554: doc-dec.
                   8555: doc-hex.
                   8556: doc-u.
                   8557: doc-.r
                   8558: doc-u.r
                   8559: doc-d.
                   8560: doc-ud.
                   8561: doc-d.r
                   8562: doc-ud.r
                   8563: doc-f.
                   8564: doc-fe.
                   8565: doc-fs.
1.111     anton    8566: doc-f.rdp
1.44      crook    8567: 
1.26      crook    8568: Examples of printing the number 1234.5678E23 in the different floating-point output
                   8569: formats are shown below:
1.5       anton    8570: 
                   8571: @example
1.26      crook    8572: f. 123456779999999000000000000.
                   8573: fe. 123.456779999999E24
                   8574: fs. 1.23456779999999E26
1.5       anton    8575: @end example
                   8576: 
                   8577: 
1.26      crook    8578: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   8579: @subsection Formatted numeric output
1.28      crook    8580: @cindex formatted numeric output
1.26      crook    8581: @cindex pictured numeric output
1.28      crook    8582: @cindex numeric output - formatted
1.26      crook    8583: 
1.29      crook    8584: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    8585: output} for formatted printing of integers.  In this technique, digits
                   8586: are extracted from the number (using the current output radix defined by
                   8587: @code{base}), converted to ASCII codes and appended to a string that is
                   8588: built in a scratch-pad area of memory (@pxref{core-idef,
                   8589: Implementation-defined options, Implementation-defined
                   8590: options}). Arbitrary characters can be appended to the string during the
                   8591: extraction process. The completed string is specified by an address
                   8592: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   8593: under program control.
1.5       anton    8594: 
1.75      anton    8595: All of the integer output words described in the previous section
                   8596: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
                   8597: numeric output.
1.5       anton    8598: 
1.47      crook    8599: Three important things to remember about pictured numeric output:
1.5       anton    8600: 
1.26      crook    8601: @itemize @bullet
                   8602: @item
1.28      crook    8603: It always operates on double-precision numbers; to display a
1.49      anton    8604: single-precision number, convert it first (for ways of doing this
                   8605: @pxref{Double precision}).
1.26      crook    8606: @item
1.28      crook    8607: It always treats the double-precision number as though it were
                   8608: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    8609: @item
                   8610: The string is built up from right to left; least significant digit first.
                   8611: @end itemize
1.5       anton    8612: 
1.44      crook    8613: 
1.26      crook    8614: doc-<#
1.47      crook    8615: doc-<<#
1.26      crook    8616: doc-#
                   8617: doc-#s
                   8618: doc-hold
                   8619: doc-sign
                   8620: doc-#>
1.47      crook    8621: doc-#>>
1.5       anton    8622: 
1.26      crook    8623: doc-represent
1.111     anton    8624: doc-f>str-rdp
                   8625: doc-f>buf-rdp
1.5       anton    8626: 
1.44      crook    8627: 
                   8628: @noindent
1.26      crook    8629: Here are some examples of using pictured numeric output:
1.5       anton    8630: 
                   8631: @example
1.26      crook    8632: : my-u. ( u -- )
                   8633:   \ Simplest use of pns.. behaves like Standard u. 
                   8634:   0              \ convert to unsigned double
1.75      anton    8635:   <<#            \ start conversion
1.26      crook    8636:   #s             \ convert all digits
                   8637:   #>             \ complete conversion
1.75      anton    8638:   TYPE SPACE     \ display, with trailing space
                   8639:   #>> ;          \ release hold area
1.5       anton    8640: 
1.26      crook    8641: : cents-only ( u -- )
                   8642:   0              \ convert to unsigned double
1.75      anton    8643:   <<#            \ start conversion
1.26      crook    8644:   # #            \ convert two least-significant digits
                   8645:   #>             \ complete conversion, discard other digits
1.75      anton    8646:   TYPE SPACE     \ display, with trailing space
                   8647:   #>> ;          \ release hold area
1.5       anton    8648: 
1.26      crook    8649: : dollars-and-cents ( u -- )
                   8650:   0              \ convert to unsigned double
1.75      anton    8651:   <<#            \ start conversion
1.26      crook    8652:   # #            \ convert two least-significant digits
                   8653:   [char] . hold  \ insert decimal point
                   8654:   #s             \ convert remaining digits
                   8655:   [char] $ hold  \ append currency symbol
                   8656:   #>             \ complete conversion
1.75      anton    8657:   TYPE SPACE     \ display, with trailing space
                   8658:   #>> ;          \ release hold area
1.5       anton    8659: 
1.26      crook    8660: : my-. ( n -- )
                   8661:   \ handling negatives.. behaves like Standard .
                   8662:   s>d            \ convert to signed double
                   8663:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    8664:   <<#            \ start conversion
1.26      crook    8665:   #s             \ convert all digits
                   8666:   rot sign       \ get at sign byte, append "-" if needed
                   8667:   #>             \ complete conversion
1.75      anton    8668:   TYPE SPACE     \ display, with trailing space
                   8669:   #>> ;          \ release hold area
1.5       anton    8670: 
1.26      crook    8671: : account. ( n -- )
1.75      anton    8672:   \ accountants don't like minus signs, they use parentheses
1.26      crook    8673:   \ for negative numbers
                   8674:   s>d            \ convert to signed double
                   8675:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    8676:   <<#            \ start conversion
1.26      crook    8677:   2 pick         \ get copy of sign byte
                   8678:   0< IF [char] ) hold THEN \ right-most character of output
                   8679:   #s             \ convert all digits
                   8680:   rot            \ get at sign byte
                   8681:   0< IF [char] ( hold THEN
                   8682:   #>             \ complete conversion
1.75      anton    8683:   TYPE SPACE     \ display, with trailing space
                   8684:   #>> ;          \ release hold area
                   8685: 
1.5       anton    8686: @end example
                   8687: 
1.26      crook    8688: Here are some examples of using these words:
1.5       anton    8689: 
                   8690: @example
1.26      crook    8691: 1 my-u. 1
                   8692: hex -1 my-u. decimal FFFFFFFF
                   8693: 1 cents-only 01
                   8694: 1234 cents-only 34
                   8695: 2 dollars-and-cents $0.02
                   8696: 1234 dollars-and-cents $12.34
                   8697: 123 my-. 123
                   8698: -123 my. -123
                   8699: 123 account. 123
                   8700: -456 account. (456)
1.5       anton    8701: @end example
                   8702: 
                   8703: 
1.26      crook    8704: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   8705: @subsection String Formats
1.27      crook    8706: @cindex strings - see character strings
                   8707: @cindex character strings - formats
1.28      crook    8708: @cindex I/O - see character strings
1.75      anton    8709: @cindex counted strings
                   8710: 
                   8711: @c anton: this does not really belong here; maybe the memory section,
                   8712: @c  or the principles chapter
1.26      crook    8713: 
1.27      crook    8714: Forth commonly uses two different methods for representing character
                   8715: strings:
1.26      crook    8716: 
                   8717: @itemize @bullet
                   8718: @item
                   8719: @cindex address of counted string
1.45      crook    8720: @cindex counted string
1.29      crook    8721: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   8722: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   8723: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    8724: memory.
                   8725: @item
1.29      crook    8726: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   8727: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    8728: first byte of the string.
                   8729: @end itemize
                   8730: 
                   8731: ANS Forth encourages the use of the second format when representing
1.75      anton    8732: strings.
1.26      crook    8733: 
1.44      crook    8734: 
1.26      crook    8735: doc-count
                   8736: 
1.44      crook    8737: 
1.49      anton    8738: For words that move, copy and search for strings see @ref{Memory
                   8739: Blocks}. For words that display characters and strings see
                   8740: @ref{Displaying characters and strings}.
1.26      crook    8741: 
                   8742: @node Displaying characters and strings, Input, String Formats, Other I/O
                   8743: @subsection Displaying characters and strings
1.27      crook    8744: @cindex characters - compiling and displaying
                   8745: @cindex character strings - compiling and displaying
1.26      crook    8746: 
                   8747: This section starts with a glossary of Forth words and ends with a set
                   8748: of examples.
                   8749: 
1.44      crook    8750: 
1.26      crook    8751: doc-bl
                   8752: doc-space
                   8753: doc-spaces
                   8754: doc-emit
                   8755: doc-toupper
                   8756: doc-."
                   8757: doc-.(
1.98      anton    8758: doc-.\"
1.26      crook    8759: doc-type
1.44      crook    8760: doc-typewhite
1.26      crook    8761: doc-cr
1.27      crook    8762: @cindex cursor control
1.26      crook    8763: doc-at-xy
                   8764: doc-page
                   8765: doc-s"
1.98      anton    8766: doc-s\"
1.26      crook    8767: doc-c"
                   8768: doc-char
                   8769: doc-[char]
                   8770: 
1.44      crook    8771: 
                   8772: @noindent
1.26      crook    8773: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    8774: 
                   8775: @example
1.26      crook    8776: .( text-1)
                   8777: : my-word
                   8778:   ." text-2" cr
                   8779:   .( text-3)
                   8780: ;
                   8781: 
                   8782: ." text-4"
                   8783: 
                   8784: : my-char
                   8785:   [char] ALPHABET emit
                   8786:   char emit
                   8787: ;
1.5       anton    8788: @end example
                   8789: 
1.26      crook    8790: When you load this code into Gforth, the following output is generated:
1.5       anton    8791: 
1.26      crook    8792: @example
1.30      anton    8793: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    8794: @end example
1.5       anton    8795: 
1.26      crook    8796: @itemize @bullet
                   8797: @item
                   8798: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   8799: is an immediate word; it behaves in the same way whether it is used inside
                   8800: or outside a colon definition.
                   8801: @item
                   8802: Message @code{text-4} is displayed because of Gforth's added interpretation
                   8803: semantics for @code{."}.
                   8804: @item
1.29      crook    8805: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    8806: performs the compilation semantics for @code{."} within the definition of
                   8807: @code{my-word}.
                   8808: @end itemize
1.5       anton    8809: 
1.26      crook    8810: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    8811: 
1.26      crook    8812: @example
1.30      anton    8813: @kbd{my-word @key{RET}} text-2
1.26      crook    8814:  ok
1.30      anton    8815: @kbd{my-char fred @key{RET}} Af ok
                   8816: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    8817: @end example
1.5       anton    8818: 
                   8819: @itemize @bullet
                   8820: @item
1.26      crook    8821: Message @code{text-2} is displayed because of the run-time behaviour of
                   8822: @code{."}.
                   8823: @item
                   8824: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   8825: on the stack at run-time. @code{emit} always displays the character
                   8826: when @code{my-char} is executed.
                   8827: @item
                   8828: @code{char} parses a string at run-time and the second @code{emit} displays
                   8829: the first character of the string.
1.5       anton    8830: @item
1.26      crook    8831: If you type @code{see my-char} you can see that @code{[char]} discarded
                   8832: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   8833: definition of @code{my-char}.
1.5       anton    8834: @end itemize
                   8835: 
                   8836: 
                   8837: 
1.112     anton    8838: @node Input, Pipes, Displaying characters and strings, Other I/O
1.26      crook    8839: @subsection Input
                   8840: @cindex input
1.28      crook    8841: @cindex I/O - see input
                   8842: @cindex parsing a string
1.5       anton    8843: 
1.49      anton    8844: For ways of storing character strings in memory see @ref{String Formats}.
1.5       anton    8845: 
1.27      crook    8846: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29      crook    8847: @comment then index them
1.27      crook    8848: 
1.44      crook    8849: 
1.27      crook    8850: doc-key
                   8851: doc-key?
1.45      crook    8852: doc-ekey
                   8853: doc-ekey?
                   8854: doc-ekey>char
1.26      crook    8855: doc->number
                   8856: doc->float
                   8857: doc-accept
1.109     anton    8858: doc-edit-line
1.27      crook    8859: doc-pad
                   8860: @comment obsolescent words..
                   8861: doc-convert
1.26      crook    8862: doc-expect
1.27      crook    8863: doc-span
1.5       anton    8864: 
                   8865: 
1.112     anton    8866: @node Pipes,  , Input, Other I/O
                   8867: @subsection Pipes
                   8868: @cindex pipes, creating your own
                   8869: 
                   8870: In addition to using Gforth in pipes created by other processes
                   8871: (@pxref{Gforth in pipes}), you can create your own pipe with
                   8872: @code{open-pipe}, and read from or write to it.
                   8873: 
                   8874: doc-open-pipe
                   8875: doc-close-pipe
                   8876: 
                   8877: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
                   8878: you don't catch this exception, Gforth will catch it and exit, usually
                   8879: silently (@pxref{Gforth in pipes}).  Since you probably do not want
                   8880: this, you should wrap a @code{catch} or @code{try} block around the code
                   8881: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
                   8882: problem yourself, and then return to regular processing.
                   8883: 
                   8884: doc-broken-pipe-error
                   8885: 
                   8886: 
1.121     anton    8887: @node OS command line arguments, Locals, Other I/O, Words
                   8888: @section OS command line arguments
                   8889: @cindex OS command line arguments
                   8890: @cindex command line arguments, OS
                   8891: @cindex arguments, OS command line
                   8892: 
                   8893: The usual way to pass arguments to Gforth programs on the command line
                   8894: is via the @option{-e} option, e.g.
                   8895: 
                   8896: @example
                   8897: gforth -e "123 456" foo.fs -e bye
                   8898: @end example
                   8899: 
                   8900: However, you may want to interpret the command-line arguments directly.
                   8901: In that case, you can access the (image-specific) command-line arguments
1.123   ! anton    8902: through @code{next-arg}:
1.121     anton    8903: 
1.123   ! anton    8904: doc-next-arg
1.121     anton    8905: 
1.123   ! anton    8906: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121     anton    8907: 
                   8908: @example
                   8909: : echo ( -- )
1.122     anton    8910:     begin
1.123   ! anton    8911:        next-arg 2dup 0 0 d<> while
        !          8912:            type space
        !          8913:     repeat
        !          8914:     2drop ;
1.121     anton    8915: 
                   8916: echo cr bye
                   8917: @end example
                   8918: 
                   8919: This can be invoked with
                   8920: 
                   8921: @example
                   8922: gforth echo.fs hello world
                   8923: @end example
1.123   ! anton    8924: 
        !          8925: and it will print
        !          8926: 
        !          8927: @example
        !          8928: hello world
        !          8929: @end example
        !          8930: 
        !          8931: The next lower level of dealing with the OS command line are the
        !          8932: following words:
        !          8933: 
        !          8934: doc-arg
        !          8935: doc-shift-args
        !          8936: 
        !          8937: Finally, at the lowest level Gforth provides the following words:
        !          8938: 
        !          8939: doc-argc
        !          8940: doc-argv
1.121     anton    8941: 
1.78      anton    8942: @c -------------------------------------------------------------
                   8943: @node Locals, Structures, Other I/O, Words
                   8944: @section Locals
                   8945: @cindex locals
                   8946: 
                   8947: Local variables can make Forth programming more enjoyable and Forth
                   8948: programs easier to read. Unfortunately, the locals of ANS Forth are
                   8949: laden with restrictions. Therefore, we provide not only the ANS Forth
                   8950: locals wordset, but also our own, more powerful locals wordset (we
                   8951: implemented the ANS Forth locals wordset through our locals wordset).
1.44      crook    8952: 
1.78      anton    8953: The ideas in this section have also been published in M. Anton Ertl,
                   8954: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
                   8955: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12      anton    8956: 
                   8957: @menu
1.78      anton    8958: * Gforth locals::               
                   8959: * ANS Forth locals::            
1.5       anton    8960: @end menu
                   8961: 
1.78      anton    8962: @node Gforth locals, ANS Forth locals, Locals, Locals
                   8963: @subsection Gforth locals
                   8964: @cindex Gforth locals
                   8965: @cindex locals, Gforth style
1.5       anton    8966: 
1.78      anton    8967: Locals can be defined with
1.44      crook    8968: 
1.78      anton    8969: @example
                   8970: @{ local1 local2 ... -- comment @}
                   8971: @end example
                   8972: or
                   8973: @example
                   8974: @{ local1 local2 ... @}
                   8975: @end example
1.5       anton    8976: 
1.78      anton    8977: E.g.,
                   8978: @example
                   8979: : max @{ n1 n2 -- n3 @}
                   8980:  n1 n2 > if
                   8981:    n1
                   8982:  else
                   8983:    n2
                   8984:  endif ;
                   8985: @end example
1.44      crook    8986: 
1.78      anton    8987: The similarity of locals definitions with stack comments is intended. A
                   8988: locals definition often replaces the stack comment of a word. The order
                   8989: of the locals corresponds to the order in a stack comment and everything
                   8990: after the @code{--} is really a comment.
1.77      anton    8991: 
1.78      anton    8992: This similarity has one disadvantage: It is too easy to confuse locals
                   8993: declarations with stack comments, causing bugs and making them hard to
                   8994: find. However, this problem can be avoided by appropriate coding
                   8995: conventions: Do not use both notations in the same program. If you do,
                   8996: they should be distinguished using additional means, e.g. by position.
1.77      anton    8997: 
1.78      anton    8998: @cindex types of locals
                   8999: @cindex locals types
                   9000: The name of the local may be preceded by a type specifier, e.g.,
                   9001: @code{F:} for a floating point value:
1.5       anton    9002: 
1.78      anton    9003: @example
                   9004: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   9005: \ complex multiplication
                   9006:  Ar Br f* Ai Bi f* f-
                   9007:  Ar Bi f* Ai Br f* f+ ;
                   9008: @end example
1.44      crook    9009: 
1.78      anton    9010: @cindex flavours of locals
                   9011: @cindex locals flavours
                   9012: @cindex value-flavoured locals
                   9013: @cindex variable-flavoured locals
                   9014: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   9015: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   9016: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   9017: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   9018: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   9019: produces its address (which becomes invalid when the variable's scope is
                   9020: left). E.g., the standard word @code{emit} can be defined in terms of
                   9021: @code{type} like this:
1.5       anton    9022: 
1.78      anton    9023: @example
                   9024: : emit @{ C^ char* -- @}
                   9025:     char* 1 type ;
                   9026: @end example
1.5       anton    9027: 
1.78      anton    9028: @cindex default type of locals
                   9029: @cindex locals, default type
                   9030: A local without type specifier is a @code{W:} local. Both flavours of
                   9031: locals are initialized with values from the data or FP stack.
1.44      crook    9032: 
1.78      anton    9033: Currently there is no way to define locals with user-defined data
                   9034: structures, but we are working on it.
1.5       anton    9035: 
1.78      anton    9036: Gforth allows defining locals everywhere in a colon definition. This
                   9037: poses the following questions:
1.5       anton    9038: 
1.78      anton    9039: @menu
                   9040: * Where are locals visible by name?::  
                   9041: * How long do locals live?::    
                   9042: * Locals programming style::    
                   9043: * Locals implementation::       
                   9044: @end menu
1.44      crook    9045: 
1.78      anton    9046: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   9047: @subsubsection Where are locals visible by name?
                   9048: @cindex locals visibility
                   9049: @cindex visibility of locals
                   9050: @cindex scope of locals
1.5       anton    9051: 
1.78      anton    9052: Basically, the answer is that locals are visible where you would expect
                   9053: it in block-structured languages, and sometimes a little longer. If you
                   9054: want to restrict the scope of a local, enclose its definition in
                   9055: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    9056: 
                   9057: 
1.78      anton    9058: doc-scope
                   9059: doc-endscope
1.5       anton    9060: 
                   9061: 
1.78      anton    9062: These words behave like control structure words, so you can use them
                   9063: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   9064: arbitrary ways.
1.77      anton    9065: 
1.78      anton    9066: If you want a more exact answer to the visibility question, here's the
                   9067: basic principle: A local is visible in all places that can only be
                   9068: reached through the definition of the local@footnote{In compiler
                   9069: construction terminology, all places dominated by the definition of the
                   9070: local.}. In other words, it is not visible in places that can be reached
                   9071: without going through the definition of the local. E.g., locals defined
                   9072: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   9073: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   9074: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77      anton    9075: 
1.78      anton    9076: The reasoning behind this solution is: We want to have the locals
                   9077: visible as long as it is meaningful. The user can always make the
                   9078: visibility shorter by using explicit scoping. In a place that can
                   9079: only be reached through the definition of a local, the meaning of a
                   9080: local name is clear. In other places it is not: How is the local
                   9081: initialized at the control flow path that does not contain the
                   9082: definition? Which local is meant, if the same name is defined twice in
                   9083: two independent control flow paths?
1.77      anton    9084: 
1.78      anton    9085: This should be enough detail for nearly all users, so you can skip the
                   9086: rest of this section. If you really must know all the gory details and
                   9087: options, read on.
1.77      anton    9088: 
1.78      anton    9089: In order to implement this rule, the compiler has to know which places
                   9090: are unreachable. It knows this automatically after @code{AHEAD},
                   9091: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   9092: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   9093: compiler that the control flow never reaches that place. If
                   9094: @code{UNREACHABLE} is not used where it could, the only consequence is
                   9095: that the visibility of some locals is more limited than the rule above
                   9096: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   9097: lie to the compiler), buggy code will be produced.
1.77      anton    9098: 
1.5       anton    9099: 
1.78      anton    9100: doc-unreachable
1.5       anton    9101: 
1.23      crook    9102: 
1.78      anton    9103: Another problem with this rule is that at @code{BEGIN}, the compiler
                   9104: does not know which locals will be visible on the incoming
                   9105: back-edge. All problems discussed in the following are due to this
                   9106: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   9107: loops as examples; the discussion also applies to @code{?DO} and other
                   9108: loops). Perhaps the most insidious example is:
1.26      crook    9109: @example
1.78      anton    9110: AHEAD
                   9111: BEGIN
                   9112:   x
                   9113: [ 1 CS-ROLL ] THEN
                   9114:   @{ x @}
                   9115:   ...
                   9116: UNTIL
1.26      crook    9117: @end example
1.23      crook    9118: 
1.78      anton    9119: This should be legal according to the visibility rule. The use of
                   9120: @code{x} can only be reached through the definition; but that appears
                   9121: textually below the use.
                   9122: 
                   9123: From this example it is clear that the visibility rules cannot be fully
                   9124: implemented without major headaches. Our implementation treats common
                   9125: cases as advertised and the exceptions are treated in a safe way: The
                   9126: compiler makes a reasonable guess about the locals visible after a
                   9127: @code{BEGIN}; if it is too pessimistic, the
                   9128: user will get a spurious error about the local not being defined; if the
                   9129: compiler is too optimistic, it will notice this later and issue a
                   9130: warning. In the case above the compiler would complain about @code{x}
                   9131: being undefined at its use. You can see from the obscure examples in
                   9132: this section that it takes quite unusual control structures to get the
                   9133: compiler into trouble, and even then it will often do fine.
1.23      crook    9134: 
1.78      anton    9135: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   9136: is that all locals visible before the @code{BEGIN} will also be
                   9137: visible after the @code{BEGIN}. This guess is valid for all loops that
                   9138: are entered only through the @code{BEGIN}, in particular, for normal
                   9139: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   9140: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   9141: compiler. When the branch to the @code{BEGIN} is finally generated by
                   9142: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   9143: warns the user if it was too optimistic:
1.26      crook    9144: @example
1.78      anton    9145: IF
                   9146:   @{ x @}
                   9147: BEGIN
                   9148:   \ x ? 
                   9149: [ 1 cs-roll ] THEN
                   9150:   ...
                   9151: UNTIL
1.26      crook    9152: @end example
1.23      crook    9153: 
1.78      anton    9154: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   9155: optimistically assumes that it lives until the @code{THEN}. It notices
                   9156: this difference when it compiles the @code{UNTIL} and issues a
                   9157: warning. The user can avoid the warning, and make sure that @code{x}
                   9158: is not used in the wrong area by using explicit scoping:
                   9159: @example
                   9160: IF
                   9161:   SCOPE
                   9162:   @{ x @}
                   9163:   ENDSCOPE
                   9164: BEGIN
                   9165: [ 1 cs-roll ] THEN
                   9166:   ...
                   9167: UNTIL
                   9168: @end example
1.23      crook    9169: 
1.78      anton    9170: Since the guess is optimistic, there will be no spurious error messages
                   9171: about undefined locals.
1.44      crook    9172: 
1.78      anton    9173: If the @code{BEGIN} is not reachable from above (e.g., after
                   9174: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   9175: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   9176: defined later. Therefore, the compiler assumes that no locals are
                   9177: visible after the @code{BEGIN}. However, the user can use
                   9178: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   9179: visible at the BEGIN as at the point where the top control-flow stack
                   9180: item was created.
1.23      crook    9181: 
1.44      crook    9182: 
1.78      anton    9183: doc-assume-live
1.26      crook    9184: 
1.23      crook    9185: 
1.78      anton    9186: @noindent
                   9187: E.g.,
                   9188: @example
                   9189: @{ x @}
                   9190: AHEAD
                   9191: ASSUME-LIVE
                   9192: BEGIN
                   9193:   x
                   9194: [ 1 CS-ROLL ] THEN
                   9195:   ...
                   9196: UNTIL
                   9197: @end example
1.44      crook    9198: 
1.78      anton    9199: Other cases where the locals are defined before the @code{BEGIN} can be
                   9200: handled by inserting an appropriate @code{CS-ROLL} before the
                   9201: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   9202: behind the @code{ASSUME-LIVE}).
1.23      crook    9203: 
1.78      anton    9204: Cases where locals are defined after the @code{BEGIN} (but should be
                   9205: visible immediately after the @code{BEGIN}) can only be handled by
                   9206: rearranging the loop. E.g., the ``most insidious'' example above can be
                   9207: arranged into:
                   9208: @example
                   9209: BEGIN
                   9210:   @{ x @}
                   9211:   ... 0=
                   9212: WHILE
                   9213:   x
                   9214: REPEAT
                   9215: @end example
1.44      crook    9216: 
1.78      anton    9217: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
                   9218: @subsubsection How long do locals live?
                   9219: @cindex locals lifetime
                   9220: @cindex lifetime of locals
1.23      crook    9221: 
1.78      anton    9222: The right answer for the lifetime question would be: A local lives at
                   9223: least as long as it can be accessed. For a value-flavoured local this
                   9224: means: until the end of its visibility. However, a variable-flavoured
                   9225: local could be accessed through its address far beyond its visibility
                   9226: scope. Ultimately, this would mean that such locals would have to be
                   9227: garbage collected. Since this entails un-Forth-like implementation
                   9228: complexities, I adopted the same cowardly solution as some other
                   9229: languages (e.g., C): The local lives only as long as it is visible;
                   9230: afterwards its address is invalid (and programs that access it
                   9231: afterwards are erroneous).
1.23      crook    9232: 
1.78      anton    9233: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
                   9234: @subsubsection Locals programming style
                   9235: @cindex locals programming style
                   9236: @cindex programming style, locals
1.23      crook    9237: 
1.78      anton    9238: The freedom to define locals anywhere has the potential to change
                   9239: programming styles dramatically. In particular, the need to use the
                   9240: return stack for intermediate storage vanishes. Moreover, all stack
                   9241: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   9242: determined arguments) can be eliminated: If the stack items are in the
                   9243: wrong order, just write a locals definition for all of them; then
                   9244: write the items in the order you want.
1.23      crook    9245: 
1.78      anton    9246: This seems a little far-fetched and eliminating stack manipulations is
                   9247: unlikely to become a conscious programming objective. Still, the number
                   9248: of stack manipulations will be reduced dramatically if local variables
                   9249: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
                   9250: a traditional implementation of @code{max}).
1.23      crook    9251: 
1.78      anton    9252: This shows one potential benefit of locals: making Forth programs more
                   9253: readable. Of course, this benefit will only be realized if the
                   9254: programmers continue to honour the principle of factoring instead of
                   9255: using the added latitude to make the words longer.
1.23      crook    9256: 
1.78      anton    9257: @cindex single-assignment style for locals
                   9258: Using @code{TO} can and should be avoided.  Without @code{TO},
                   9259: every value-flavoured local has only a single assignment and many
                   9260: advantages of functional languages apply to Forth. I.e., programs are
                   9261: easier to analyse, to optimize and to read: It is clear from the
                   9262: definition what the local stands for, it does not turn into something
                   9263: different later.
1.23      crook    9264: 
1.78      anton    9265: E.g., a definition using @code{TO} might look like this:
                   9266: @example
                   9267: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9268:  u1 u2 min 0
                   9269:  ?do
                   9270:    addr1 c@@ addr2 c@@ -
                   9271:    ?dup-if
                   9272:      unloop exit
                   9273:    then
                   9274:    addr1 char+ TO addr1
                   9275:    addr2 char+ TO addr2
                   9276:  loop
                   9277:  u1 u2 - ;
1.26      crook    9278: @end example
1.78      anton    9279: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   9280: every loop iteration. @code{strcmp} is a typical example of the
                   9281: readability problems of using @code{TO}. When you start reading
                   9282: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   9283: string. Only near the end of the loop you realize that it is something
                   9284: else.
1.23      crook    9285: 
1.78      anton    9286: This can be avoided by defining two locals at the start of the loop that
                   9287: are initialized with the right value for the current iteration.
                   9288: @example
                   9289: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9290:  addr1 addr2
                   9291:  u1 u2 min 0 
                   9292:  ?do @{ s1 s2 @}
                   9293:    s1 c@@ s2 c@@ -
                   9294:    ?dup-if
                   9295:      unloop exit
                   9296:    then
                   9297:    s1 char+ s2 char+
                   9298:  loop
                   9299:  2drop
                   9300:  u1 u2 - ;
                   9301: @end example
                   9302: Here it is clear from the start that @code{s1} has a different value
                   9303: in every loop iteration.
1.23      crook    9304: 
1.78      anton    9305: @node Locals implementation,  , Locals programming style, Gforth locals
                   9306: @subsubsection Locals implementation
                   9307: @cindex locals implementation
                   9308: @cindex implementation of locals
1.23      crook    9309: 
1.78      anton    9310: @cindex locals stack
                   9311: Gforth uses an extra locals stack. The most compelling reason for
                   9312: this is that the return stack is not float-aligned; using an extra stack
                   9313: also eliminates the problems and restrictions of using the return stack
                   9314: as locals stack. Like the other stacks, the locals stack grows toward
                   9315: lower addresses. A few primitives allow an efficient implementation:
                   9316: 
                   9317: 
                   9318: doc-@local#
                   9319: doc-f@local#
                   9320: doc-laddr#
                   9321: doc-lp+!#
                   9322: doc-lp!
                   9323: doc->l
                   9324: doc-f>l
                   9325: 
                   9326: 
                   9327: In addition to these primitives, some specializations of these
                   9328: primitives for commonly occurring inline arguments are provided for
                   9329: efficiency reasons, e.g., @code{@@local0} as specialization of
                   9330: @code{@@local#} for the inline argument 0. The following compiling words
                   9331: compile the right specialized version, or the general version, as
                   9332: appropriate:
1.23      crook    9333: 
1.5       anton    9334: 
1.107     dvdkhlng 9335: @c doc-compile-@local
                   9336: @c doc-compile-f@local
1.78      anton    9337: doc-compile-lp+!
1.5       anton    9338: 
                   9339: 
1.78      anton    9340: Combinations of conditional branches and @code{lp+!#} like
                   9341: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   9342: is taken) are provided for efficiency and correctness in loops.
1.5       anton    9343: 
1.78      anton    9344: A special area in the dictionary space is reserved for keeping the
                   9345: local variable names. @code{@{} switches the dictionary pointer to this
                   9346: area and @code{@}} switches it back and generates the locals
                   9347: initializing code. @code{W:} etc.@ are normal defining words. This
                   9348: special area is cleared at the start of every colon definition.
1.5       anton    9349: 
1.78      anton    9350: @cindex word list for defining locals
                   9351: A special feature of Gforth's dictionary is used to implement the
                   9352: definition of locals without type specifiers: every word list (aka
                   9353: vocabulary) has its own methods for searching
                   9354: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   9355: with a special search method: When it is searched for a word, it
                   9356: actually creates that word using @code{W:}. @code{@{} changes the search
                   9357: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   9358: and then the word list for defining locals without type specifiers.
1.5       anton    9359: 
1.78      anton    9360: The lifetime rules support a stack discipline within a colon
                   9361: definition: The lifetime of a local is either nested with other locals
                   9362: lifetimes or it does not overlap them.
1.23      crook    9363: 
1.78      anton    9364: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   9365: pointer manipulation is generated. Between control structure words
                   9366: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   9367: is the simplest of the other three control flow words. It has to
                   9368: restore the locals stack depth of the corresponding @code{BEGIN}
                   9369: before branching. The code looks like this:
                   9370: @format
                   9371: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   9372: @code{branch} <begin>
                   9373: @end format
1.26      crook    9374: 
1.78      anton    9375: @code{UNTIL} is a little more complicated: If it branches back, it
                   9376: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   9377: the locals stack must not be changed. The compiler generates the
                   9378: following code:
                   9379: @format
                   9380: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   9381: @end format
                   9382: The locals stack pointer is only adjusted if the branch is taken.
1.44      crook    9383: 
1.78      anton    9384: @code{THEN} can produce somewhat inefficient code:
                   9385: @format
                   9386: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   9387: <orig target>:
                   9388: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   9389: @end format
                   9390: The second @code{lp+!#} adjusts the locals stack pointer from the
                   9391: level at the @i{orig} point to the level after the @code{THEN}. The
                   9392: first @code{lp+!#} adjusts the locals stack pointer from the current
                   9393: level to the level at the orig point, so the complete effect is an
                   9394: adjustment from the current level to the right level after the
                   9395: @code{THEN}.
1.26      crook    9396: 
1.78      anton    9397: @cindex locals information on the control-flow stack
                   9398: @cindex control-flow stack items, locals information
                   9399: In a conventional Forth implementation a dest control-flow stack entry
                   9400: is just the target address and an orig entry is just the address to be
                   9401: patched. Our locals implementation adds a word list to every orig or dest
                   9402: item. It is the list of locals visible (or assumed visible) at the point
                   9403: described by the entry. Our implementation also adds a tag to identify
                   9404: the kind of entry, in particular to differentiate between live and dead
                   9405: (reachable and unreachable) orig entries.
1.26      crook    9406: 
1.78      anton    9407: A few unusual operations have to be performed on locals word lists:
1.44      crook    9408: 
1.5       anton    9409: 
1.78      anton    9410: doc-common-list
                   9411: doc-sub-list?
                   9412: doc-list-size
1.52      anton    9413: 
                   9414: 
1.78      anton    9415: Several features of our locals word list implementation make these
                   9416: operations easy to implement: The locals word lists are organised as
                   9417: linked lists; the tails of these lists are shared, if the lists
                   9418: contain some of the same locals; and the address of a name is greater
                   9419: than the address of the names behind it in the list.
1.5       anton    9420: 
1.78      anton    9421: Another important implementation detail is the variable
                   9422: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   9423: determine if they can be reached directly or only through the branch
                   9424: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   9425: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   9426: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5       anton    9427: 
1.78      anton    9428: Counted loops are similar to other loops in most respects, but
                   9429: @code{LEAVE} requires special attention: It performs basically the same
                   9430: service as @code{AHEAD}, but it does not create a control-flow stack
                   9431: entry. Therefore the information has to be stored elsewhere;
                   9432: traditionally, the information was stored in the target fields of the
                   9433: branches created by the @code{LEAVE}s, by organizing these fields into a
                   9434: linked list. Unfortunately, this clever trick does not provide enough
                   9435: space for storing our extended control flow information. Therefore, we
                   9436: introduce another stack, the leave stack. It contains the control-flow
                   9437: stack entries for all unresolved @code{LEAVE}s.
1.44      crook    9438: 
1.78      anton    9439: Local names are kept until the end of the colon definition, even if
                   9440: they are no longer visible in any control-flow path. In a few cases
                   9441: this may lead to increased space needs for the locals name area, but
                   9442: usually less than reclaiming this space would cost in code size.
1.5       anton    9443: 
1.44      crook    9444: 
1.78      anton    9445: @node ANS Forth locals,  , Gforth locals, Locals
                   9446: @subsection ANS Forth locals
                   9447: @cindex locals, ANS Forth style
1.5       anton    9448: 
1.78      anton    9449: The ANS Forth locals wordset does not define a syntax for locals, but
                   9450: words that make it possible to define various syntaxes. One of the
                   9451: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   9452: wordset, i.e.:
1.29      crook    9453: 
                   9454: @example
1.78      anton    9455: @{ local1 local2 ... -- comment @}
                   9456: @end example
                   9457: @noindent
                   9458: or
                   9459: @example
                   9460: @{ local1 local2 ... @}
1.29      crook    9461: @end example
                   9462: 
1.78      anton    9463: The order of the locals corresponds to the order in a stack comment. The
                   9464: restrictions are:
1.5       anton    9465: 
1.78      anton    9466: @itemize @bullet
                   9467: @item
                   9468: Locals can only be cell-sized values (no type specifiers are allowed).
                   9469: @item
                   9470: Locals can be defined only outside control structures.
                   9471: @item
                   9472: Locals can interfere with explicit usage of the return stack. For the
                   9473: exact (and long) rules, see the standard. If you don't use return stack
                   9474: accessing words in a definition using locals, you will be all right. The
                   9475: purpose of this rule is to make locals implementation on the return
                   9476: stack easier.
                   9477: @item
                   9478: The whole definition must be in one line.
                   9479: @end itemize
1.5       anton    9480: 
1.78      anton    9481: Locals defined in ANS Forth behave like @code{VALUE}s
                   9482: (@pxref{Values}). I.e., they are initialized from the stack. Using their
                   9483: name produces their value. Their value can be changed using @code{TO}.
1.77      anton    9484: 
1.78      anton    9485: Since the syntax above is supported by Gforth directly, you need not do
                   9486: anything to use it. If you want to port a program using this syntax to
                   9487: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   9488: syntax on the other system.
1.5       anton    9489: 
1.78      anton    9490: Note that a syntax shown in the standard, section A.13 looks
                   9491: similar, but is quite different in having the order of locals
                   9492: reversed. Beware!
1.5       anton    9493: 
1.78      anton    9494: The ANS Forth locals wordset itself consists of one word:
1.5       anton    9495: 
1.78      anton    9496: doc-(local)
1.5       anton    9497: 
1.78      anton    9498: The ANS Forth locals extension wordset defines a syntax using
                   9499: @code{locals|}, but it is so awful that we strongly recommend not to use
                   9500: it. We have implemented this syntax to make porting to Gforth easy, but
                   9501: do not document it here. The problem with this syntax is that the locals
                   9502: are defined in an order reversed with respect to the standard stack
                   9503: comment notation, making programs harder to read, and easier to misread
                   9504: and miswrite. The only merit of this syntax is that it is easy to
                   9505: implement using the ANS Forth locals wordset.
1.53      anton    9506: 
                   9507: 
1.78      anton    9508: @c ----------------------------------------------------------
                   9509: @node Structures, Object-oriented Forth, Locals, Words
                   9510: @section  Structures
                   9511: @cindex structures
                   9512: @cindex records
1.53      anton    9513: 
1.78      anton    9514: This section presents the structure package that comes with Gforth. A
                   9515: version of the package implemented in ANS Forth is available in
                   9516: @file{compat/struct.fs}. This package was inspired by a posting on
                   9517: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   9518: possibly John Hayes). A version of this section has been published in
                   9519: M. Anton Ertl,
                   9520: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
                   9521: Another Forth Structures Package}, Forth Dimensions 19(3), pages
                   9522: 13--16. Marcel Hendrix provided helpful comments.
1.53      anton    9523: 
1.78      anton    9524: @menu
                   9525: * Why explicit structure support?::  
                   9526: * Structure Usage::             
                   9527: * Structure Naming Convention::  
                   9528: * Structure Implementation::    
                   9529: * Structure Glossary::          
                   9530: @end menu
1.55      anton    9531: 
1.78      anton    9532: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   9533: @subsection Why explicit structure support?
1.53      anton    9534: 
1.78      anton    9535: @cindex address arithmetic for structures
                   9536: @cindex structures using address arithmetic
                   9537: If we want to use a structure containing several fields, we could simply
                   9538: reserve memory for it, and access the fields using address arithmetic
                   9539: (@pxref{Address arithmetic}). As an example, consider a structure with
                   9540: the following fields
1.57      anton    9541: 
1.78      anton    9542: @table @code
                   9543: @item a
                   9544: is a float
                   9545: @item b
                   9546: is a cell
                   9547: @item c
                   9548: is a float
                   9549: @end table
1.57      anton    9550: 
1.78      anton    9551: Given the (float-aligned) base address of the structure we get the
                   9552: address of the field
1.52      anton    9553: 
1.78      anton    9554: @table @code
                   9555: @item a
                   9556: without doing anything further.
                   9557: @item b
                   9558: with @code{float+}
                   9559: @item c
                   9560: with @code{float+ cell+ faligned}
                   9561: @end table
1.52      anton    9562: 
1.78      anton    9563: It is easy to see that this can become quite tiring. 
1.52      anton    9564: 
1.78      anton    9565: Moreover, it is not very readable, because seeing a
                   9566: @code{cell+} tells us neither which kind of structure is
                   9567: accessed nor what field is accessed; we have to somehow infer the kind
                   9568: of structure, and then look up in the documentation, which field of
                   9569: that structure corresponds to that offset.
1.53      anton    9570: 
1.78      anton    9571: Finally, this kind of address arithmetic also causes maintenance
                   9572: troubles: If you add or delete a field somewhere in the middle of the
                   9573: structure, you have to find and change all computations for the fields
                   9574: afterwards.
1.52      anton    9575: 
1.78      anton    9576: So, instead of using @code{cell+} and friends directly, how
                   9577: about storing the offsets in constants:
1.52      anton    9578: 
1.78      anton    9579: @example
                   9580: 0 constant a-offset
                   9581: 0 float+ constant b-offset
                   9582: 0 float+ cell+ faligned c-offset
                   9583: @end example
1.64      pazsan   9584: 
1.78      anton    9585: Now we can get the address of field @code{x} with @code{x-offset
                   9586: +}. This is much better in all respects. Of course, you still
                   9587: have to change all later offset definitions if you add a field. You can
                   9588: fix this by declaring the offsets in the following way:
1.57      anton    9589: 
1.78      anton    9590: @example
                   9591: 0 constant a-offset
                   9592: a-offset float+ constant b-offset
                   9593: b-offset cell+ faligned constant c-offset
                   9594: @end example
1.57      anton    9595: 
1.78      anton    9596: Since we always use the offsets with @code{+}, we could use a defining
                   9597: word @code{cfield} that includes the @code{+} in the action of the
                   9598: defined word:
1.64      pazsan   9599: 
1.78      anton    9600: @example
                   9601: : cfield ( n "name" -- )
                   9602:     create ,
                   9603: does> ( name execution: addr1 -- addr2 )
                   9604:     @@ + ;
1.64      pazsan   9605: 
1.78      anton    9606: 0 cfield a
                   9607: 0 a float+ cfield b
                   9608: 0 b cell+ faligned cfield c
                   9609: @end example
1.64      pazsan   9610: 
1.78      anton    9611: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64      pazsan   9612: 
1.78      anton    9613: The structure field words now can be used quite nicely. However,
                   9614: their definition is still a bit cumbersome: We have to repeat the
                   9615: name, the information about size and alignment is distributed before
                   9616: and after the field definitions etc.  The structure package presented
                   9617: here addresses these problems.
1.64      pazsan   9618: 
1.78      anton    9619: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   9620: @subsection Structure Usage
                   9621: @cindex structure usage
1.57      anton    9622: 
1.78      anton    9623: @cindex @code{field} usage
                   9624: @cindex @code{struct} usage
                   9625: @cindex @code{end-struct} usage
                   9626: You can define a structure for a (data-less) linked list with:
1.57      anton    9627: @example
1.78      anton    9628: struct
                   9629:     cell% field list-next
                   9630: end-struct list%
1.57      anton    9631: @end example
                   9632: 
1.78      anton    9633: With the address of the list node on the stack, you can compute the
                   9634: address of the field that contains the address of the next node with
                   9635: @code{list-next}. E.g., you can determine the length of a list
                   9636: with:
1.57      anton    9637: 
                   9638: @example
1.78      anton    9639: : list-length ( list -- n )
                   9640: \ "list" is a pointer to the first element of a linked list
                   9641: \ "n" is the length of the list
                   9642:     0 BEGIN ( list1 n1 )
                   9643:         over
                   9644:     WHILE ( list1 n1 )
                   9645:         1+ swap list-next @@ swap
                   9646:     REPEAT
                   9647:     nip ;
1.57      anton    9648: @end example
                   9649: 
1.78      anton    9650: You can reserve memory for a list node in the dictionary with
                   9651: @code{list% %allot}, which leaves the address of the list node on the
                   9652: stack. For the equivalent allocation on the heap you can use @code{list%
                   9653: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   9654: use @code{list% %allocate}). You can get the the size of a list
                   9655: node with @code{list% %size} and its alignment with @code{list%
                   9656: %alignment}.
                   9657: 
                   9658: Note that in ANS Forth the body of a @code{create}d word is
                   9659: @code{aligned} but not necessarily @code{faligned};
                   9660: therefore, if you do a:
1.57      anton    9661: 
                   9662: @example
1.78      anton    9663: create @emph{name} foo% %allot drop
1.57      anton    9664: @end example
                   9665: 
1.78      anton    9666: @noindent
                   9667: then the memory alloted for @code{foo%} is guaranteed to start at the
                   9668: body of @code{@emph{name}} only if @code{foo%} contains only character,
                   9669: cell and double fields.  Therefore, if your structure contains floats,
                   9670: better use
1.57      anton    9671: 
                   9672: @example
1.78      anton    9673: foo% %allot constant @emph{name}
1.57      anton    9674: @end example
                   9675: 
1.78      anton    9676: @cindex structures containing structures
                   9677: You can include a structure @code{foo%} as a field of
                   9678: another structure, like this:
1.65      anton    9679: @example
1.78      anton    9680: struct
                   9681: ...
                   9682:     foo% field ...
                   9683: ...
                   9684: end-struct ...
1.65      anton    9685: @end example
1.52      anton    9686: 
1.78      anton    9687: @cindex structure extension
                   9688: @cindex extended records
                   9689: Instead of starting with an empty structure, you can extend an
                   9690: existing structure. E.g., a plain linked list without data, as defined
                   9691: above, is hardly useful; You can extend it to a linked list of integers,
                   9692: like this:@footnote{This feature is also known as @emph{extended
                   9693: records}. It is the main innovation in the Oberon language; in other
                   9694: words, adding this feature to Modula-2 led Wirth to create a new
                   9695: language, write a new compiler etc.  Adding this feature to Forth just
                   9696: required a few lines of code.}
1.52      anton    9697: 
1.78      anton    9698: @example
                   9699: list%
                   9700:     cell% field intlist-int
                   9701: end-struct intlist%
                   9702: @end example
1.55      anton    9703: 
1.78      anton    9704: @code{intlist%} is a structure with two fields:
                   9705: @code{list-next} and @code{intlist-int}.
1.55      anton    9706: 
1.78      anton    9707: @cindex structures containing arrays
                   9708: You can specify an array type containing @emph{n} elements of
                   9709: type @code{foo%} like this:
1.55      anton    9710: 
                   9711: @example
1.78      anton    9712: foo% @emph{n} *
1.56      anton    9713: @end example
1.55      anton    9714: 
1.78      anton    9715: You can use this array type in any place where you can use a normal
                   9716: type, e.g., when defining a @code{field}, or with
                   9717: @code{%allot}.
                   9718: 
                   9719: @cindex first field optimization
                   9720: The first field is at the base address of a structure and the word for
                   9721: this field (e.g., @code{list-next}) actually does not change the address
                   9722: on the stack. You may be tempted to leave it away in the interest of
                   9723: run-time and space efficiency. This is not necessary, because the
                   9724: structure package optimizes this case: If you compile a first-field
                   9725: words, no code is generated. So, in the interest of readability and
                   9726: maintainability you should include the word for the field when accessing
                   9727: the field.
1.52      anton    9728: 
                   9729: 
1.78      anton    9730: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   9731: @subsection Structure Naming Convention
                   9732: @cindex structure naming convention
1.52      anton    9733: 
1.78      anton    9734: The field names that come to (my) mind are often quite generic, and,
                   9735: if used, would cause frequent name clashes. E.g., many structures
                   9736: probably contain a @code{counter} field. The structure names
                   9737: that come to (my) mind are often also the logical choice for the names
                   9738: of words that create such a structure.
1.52      anton    9739: 
1.78      anton    9740: Therefore, I have adopted the following naming conventions: 
1.52      anton    9741: 
1.78      anton    9742: @itemize @bullet
                   9743: @cindex field naming convention
                   9744: @item
                   9745: The names of fields are of the form
                   9746: @code{@emph{struct}-@emph{field}}, where
                   9747: @code{@emph{struct}} is the basic name of the structure, and
                   9748: @code{@emph{field}} is the basic name of the field. You can
                   9749: think of field words as converting the (address of the)
                   9750: structure into the (address of the) field.
1.52      anton    9751: 
1.78      anton    9752: @cindex structure naming convention
                   9753: @item
                   9754: The names of structures are of the form
                   9755: @code{@emph{struct}%}, where
                   9756: @code{@emph{struct}} is the basic name of the structure.
                   9757: @end itemize
1.52      anton    9758: 
1.78      anton    9759: This naming convention does not work that well for fields of extended
                   9760: structures; e.g., the integer list structure has a field
                   9761: @code{intlist-int}, but has @code{list-next}, not
                   9762: @code{intlist-next}.
1.53      anton    9763: 
1.78      anton    9764: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   9765: @subsection Structure Implementation
                   9766: @cindex structure implementation
                   9767: @cindex implementation of structures
1.52      anton    9768: 
1.78      anton    9769: The central idea in the implementation is to pass the data about the
                   9770: structure being built on the stack, not in some global
                   9771: variable. Everything else falls into place naturally once this design
                   9772: decision is made.
1.53      anton    9773: 
1.78      anton    9774: The type description on the stack is of the form @emph{align
                   9775: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   9776: very simple.
1.53      anton    9777: 
1.78      anton    9778: @code{field} is a defining word that uses @code{Create}
                   9779: and @code{DOES>}. The body of the field contains the offset
                   9780: of the field, and the normal @code{DOES>} action is simply:
1.53      anton    9781: 
                   9782: @example
1.78      anton    9783: @@ +
1.53      anton    9784: @end example
                   9785: 
1.78      anton    9786: @noindent
                   9787: i.e., add the offset to the address, giving the stack effect
                   9788: @i{addr1 -- addr2} for a field.
                   9789: 
                   9790: @cindex first field optimization, implementation
                   9791: This simple structure is slightly complicated by the optimization
                   9792: for fields with offset 0, which requires a different
                   9793: @code{DOES>}-part (because we cannot rely on there being
                   9794: something on the stack if such a field is invoked during
                   9795: compilation). Therefore, we put the different @code{DOES>}-parts
                   9796: in separate words, and decide which one to invoke based on the
                   9797: offset. For a zero offset, the field is basically a noop; it is
                   9798: immediate, and therefore no code is generated when it is compiled.
1.53      anton    9799: 
1.78      anton    9800: @node Structure Glossary,  , Structure Implementation, Structures
                   9801: @subsection Structure Glossary
                   9802: @cindex structure glossary
1.53      anton    9803: 
1.5       anton    9804: 
1.78      anton    9805: doc-%align
                   9806: doc-%alignment
                   9807: doc-%alloc
                   9808: doc-%allocate
                   9809: doc-%allot
                   9810: doc-cell%
                   9811: doc-char%
                   9812: doc-dfloat%
                   9813: doc-double%
                   9814: doc-end-struct
                   9815: doc-field
                   9816: doc-float%
                   9817: doc-naligned
                   9818: doc-sfloat%
                   9819: doc-%size
                   9820: doc-struct
1.54      anton    9821: 
                   9822: 
1.26      crook    9823: @c -------------------------------------------------------------
1.78      anton    9824: @node Object-oriented Forth, Programming Tools, Structures, Words
                   9825: @section Object-oriented Forth
                   9826: 
                   9827: Gforth comes with three packages for object-oriented programming:
                   9828: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   9829: is preloaded, so you have to @code{include} them before use. The most
                   9830: important differences between these packages (and others) are discussed
                   9831: in @ref{Comparison with other object models}. All packages are written
                   9832: in ANS Forth and can be used with any other ANS Forth.
1.5       anton    9833: 
1.78      anton    9834: @menu
                   9835: * Why object-oriented programming?::  
                   9836: * Object-Oriented Terminology::  
                   9837: * Objects::                     
                   9838: * OOF::                         
                   9839: * Mini-OOF::                    
                   9840: * Comparison with other object models::  
                   9841: @end menu
1.5       anton    9842: 
1.78      anton    9843: @c ----------------------------------------------------------------
                   9844: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
                   9845: @subsection Why object-oriented programming?
                   9846: @cindex object-oriented programming motivation
                   9847: @cindex motivation for object-oriented programming
1.44      crook    9848: 
1.78      anton    9849: Often we have to deal with several data structures (@emph{objects}),
                   9850: that have to be treated similarly in some respects, but differently in
                   9851: others. Graphical objects are the textbook example: circles, triangles,
                   9852: dinosaurs, icons, and others, and we may want to add more during program
                   9853: development. We want to apply some operations to any graphical object,
                   9854: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   9855: has to do something different for every kind of object.
                   9856: @comment TODO add some other operations eg perimeter, area
                   9857: @comment and tie in to concrete examples later..
1.5       anton    9858: 
1.78      anton    9859: We could implement @code{draw} as a big @code{CASE}
                   9860: control structure that executes the appropriate code depending on the
                   9861: kind of object to be drawn. This would be not be very elegant, and,
                   9862: moreover, we would have to change @code{draw} every time we add
                   9863: a new kind of graphical object (say, a spaceship).
1.44      crook    9864: 
1.78      anton    9865: What we would rather do is: When defining spaceships, we would tell
                   9866: the system: ``Here's how you @code{draw} a spaceship; you figure
                   9867: out the rest''.
1.5       anton    9868: 
1.78      anton    9869: This is the problem that all systems solve that (rightfully) call
                   9870: themselves object-oriented; the object-oriented packages presented here
                   9871: solve this problem (and not much else).
                   9872: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44      crook    9873: 
1.78      anton    9874: @c ------------------------------------------------------------------------
                   9875: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
                   9876: @subsection Object-Oriented Terminology
                   9877: @cindex object-oriented terminology
                   9878: @cindex terminology for object-oriented programming
1.5       anton    9879: 
1.78      anton    9880: This section is mainly for reference, so you don't have to understand
                   9881: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   9882: short:
1.44      crook    9883: 
1.78      anton    9884: @table @emph
                   9885: @cindex class
                   9886: @item class
                   9887: a data structure definition with some extras.
1.5       anton    9888: 
1.78      anton    9889: @cindex object
                   9890: @item object
                   9891: an instance of the data structure described by the class definition.
1.5       anton    9892: 
1.78      anton    9893: @cindex instance variables
                   9894: @item instance variables
                   9895: fields of the data structure.
1.5       anton    9896: 
1.78      anton    9897: @cindex selector
                   9898: @cindex method selector
                   9899: @cindex virtual function
                   9900: @item selector
                   9901: (or @emph{method selector}) a word (e.g.,
                   9902: @code{draw}) that performs an operation on a variety of data
                   9903: structures (classes). A selector describes @emph{what} operation to
                   9904: perform. In C++ terminology: a (pure) virtual function.
1.5       anton    9905: 
1.78      anton    9906: @cindex method
                   9907: @item method
                   9908: the concrete definition that performs the operation
                   9909: described by the selector for a specific class. A method specifies
                   9910: @emph{how} the operation is performed for a specific class.
1.5       anton    9911: 
1.78      anton    9912: @cindex selector invocation
                   9913: @cindex message send
                   9914: @cindex invoking a selector
                   9915: @item selector invocation
                   9916: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   9917: is used for determining which method is used. In Smalltalk terminology:
                   9918: a message (consisting of the selector and the other arguments) is sent
                   9919: to the object.
1.5       anton    9920: 
1.78      anton    9921: @cindex receiving object
                   9922: @item receiving object
                   9923: the object used for determining the method executed by a selector
                   9924: invocation. In the @file{objects.fs} model, it is the object that is on
                   9925: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   9926: the Smalltalk @emph{message} terminology.)
1.5       anton    9927: 
1.78      anton    9928: @cindex child class
                   9929: @cindex parent class
                   9930: @cindex inheritance
                   9931: @item child class
                   9932: a class that has (@emph{inherits}) all properties (instance variables,
                   9933: selectors, methods) from a @emph{parent class}. In Smalltalk
                   9934: terminology: The subclass inherits from the superclass. In C++
                   9935: terminology: The derived class inherits from the base class.
1.5       anton    9936: 
1.78      anton    9937: @end table
1.5       anton    9938: 
1.78      anton    9939: @c If you wonder about the message sending terminology, it comes from
                   9940: @c a time when each object had it's own task and objects communicated via
                   9941: @c message passing; eventually the Smalltalk developers realized that
                   9942: @c they can do most things through simple (indirect) calls. They kept the
                   9943: @c terminology.
1.5       anton    9944: 
1.78      anton    9945: @c --------------------------------------------------------------
                   9946: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   9947: @subsection The @file{objects.fs} model
                   9948: @cindex objects
                   9949: @cindex object-oriented programming
1.26      crook    9950: 
1.78      anton    9951: @cindex @file{objects.fs}
                   9952: @cindex @file{oof.fs}
1.26      crook    9953: 
1.78      anton    9954: This section describes the @file{objects.fs} package. This material also
                   9955: has been published in M. Anton Ertl,
                   9956: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
                   9957: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
                   9958: 37--43.
                   9959: @c McKewan's and Zsoter's packages
1.26      crook    9960: 
1.78      anton    9961: This section assumes that you have read @ref{Structures}.
1.5       anton    9962: 
1.78      anton    9963: The techniques on which this model is based have been used to implement
                   9964: the parser generator, Gray, and have also been used in Gforth for
                   9965: implementing the various flavours of word lists (hashed or not,
                   9966: case-sensitive or not, special-purpose word lists for locals etc.).
1.5       anton    9967: 
                   9968: 
1.26      crook    9969: @menu
1.78      anton    9970: * Properties of the Objects model::  
                   9971: * Basic Objects Usage::         
                   9972: * The Objects base class::      
                   9973: * Creating objects::            
                   9974: * Object-Oriented Programming Style::  
                   9975: * Class Binding::               
                   9976: * Method conveniences::         
                   9977: * Classes and Scoping::         
                   9978: * Dividing classes::            
                   9979: * Object Interfaces::           
                   9980: * Objects Implementation::      
                   9981: * Objects Glossary::            
1.26      crook    9982: @end menu
1.5       anton    9983: 
1.78      anton    9984: Marcel Hendrix provided helpful comments on this section.
1.5       anton    9985: 
1.78      anton    9986: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   9987: @subsubsection Properties of the @file{objects.fs} model
                   9988: @cindex @file{objects.fs} properties
1.5       anton    9989: 
1.78      anton    9990: @itemize @bullet
                   9991: @item
                   9992: It is straightforward to pass objects on the stack. Passing
                   9993: selectors on the stack is a little less convenient, but possible.
1.44      crook    9994: 
1.78      anton    9995: @item
                   9996: Objects are just data structures in memory, and are referenced by their
                   9997: address. You can create words for objects with normal defining words
                   9998: like @code{constant}. Likewise, there is no difference between instance
                   9999: variables that contain objects and those that contain other data.
1.5       anton    10000: 
1.78      anton    10001: @item
                   10002: Late binding is efficient and easy to use.
1.44      crook    10003: 
1.78      anton    10004: @item
                   10005: It avoids parsing, and thus avoids problems with state-smartness
                   10006: and reduced extensibility; for convenience there are a few parsing
                   10007: words, but they have non-parsing counterparts. There are also a few
                   10008: defining words that parse. This is hard to avoid, because all standard
                   10009: defining words parse (except @code{:noname}); however, such
                   10010: words are not as bad as many other parsing words, because they are not
                   10011: state-smart.
1.5       anton    10012: 
1.78      anton    10013: @item
                   10014: It does not try to incorporate everything. It does a few things and does
                   10015: them well (IMO). In particular, this model was not designed to support
                   10016: information hiding (although it has features that may help); you can use
                   10017: a separate package for achieving this.
1.5       anton    10018: 
1.78      anton    10019: @item
                   10020: It is layered; you don't have to learn and use all features to use this
                   10021: model. Only a few features are necessary (@pxref{Basic Objects Usage},
                   10022: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
                   10023: are optional and independent of each other.
1.5       anton    10024: 
1.78      anton    10025: @item
                   10026: An implementation in ANS Forth is available.
1.5       anton    10027: 
1.78      anton    10028: @end itemize
1.5       anton    10029: 
1.44      crook    10030: 
1.78      anton    10031: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   10032: @subsubsection Basic @file{objects.fs} Usage
                   10033: @cindex basic objects usage
                   10034: @cindex objects, basic usage
1.5       anton    10035: 
1.78      anton    10036: You can define a class for graphical objects like this:
1.44      crook    10037: 
1.78      anton    10038: @cindex @code{class} usage
                   10039: @cindex @code{end-class} usage
                   10040: @cindex @code{selector} usage
1.5       anton    10041: @example
1.78      anton    10042: object class \ "object" is the parent class
                   10043:   selector draw ( x y graphical -- )
                   10044: end-class graphical
                   10045: @end example
                   10046: 
                   10047: This code defines a class @code{graphical} with an
                   10048: operation @code{draw}.  We can perform the operation
                   10049: @code{draw} on any @code{graphical} object, e.g.:
                   10050: 
                   10051: @example
                   10052: 100 100 t-rex draw
1.26      crook    10053: @end example
1.5       anton    10054: 
1.78      anton    10055: @noindent
                   10056: where @code{t-rex} is a word (say, a constant) that produces a
                   10057: graphical object.
                   10058: 
                   10059: @comment TODO add a 2nd operation eg perimeter.. and use for
                   10060: @comment a concrete example
1.5       anton    10061: 
1.78      anton    10062: @cindex abstract class
                   10063: How do we create a graphical object? With the present definitions,
                   10064: we cannot create a useful graphical object. The class
                   10065: @code{graphical} describes graphical objects in general, but not
                   10066: any concrete graphical object type (C++ users would call it an
                   10067: @emph{abstract class}); e.g., there is no method for the selector
                   10068: @code{draw} in the class @code{graphical}.
1.5       anton    10069: 
1.78      anton    10070: For concrete graphical objects, we define child classes of the
                   10071: class @code{graphical}, e.g.:
1.5       anton    10072: 
1.78      anton    10073: @cindex @code{overrides} usage
                   10074: @cindex @code{field} usage in class definition
1.26      crook    10075: @example
1.78      anton    10076: graphical class \ "graphical" is the parent class
                   10077:   cell% field circle-radius
1.5       anton    10078: 
1.78      anton    10079: :noname ( x y circle -- )
                   10080:   circle-radius @@ draw-circle ;
                   10081: overrides draw
1.5       anton    10082: 
1.78      anton    10083: :noname ( n-radius circle -- )
                   10084:   circle-radius ! ;
                   10085: overrides construct
1.5       anton    10086: 
1.78      anton    10087: end-class circle
                   10088: @end example
1.44      crook    10089: 
1.78      anton    10090: Here we define a class @code{circle} as a child of @code{graphical},
                   10091: with field @code{circle-radius} (which behaves just like a field
                   10092: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   10093: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   10094: defined in @code{object}, the parent class of @code{graphical}).
1.5       anton    10095: 
1.78      anton    10096: Now we can create a circle on the heap (i.e.,
                   10097: @code{allocate}d memory) with:
1.44      crook    10098: 
1.78      anton    10099: @cindex @code{heap-new} usage
1.5       anton    10100: @example
1.78      anton    10101: 50 circle heap-new constant my-circle
1.5       anton    10102: @end example
                   10103: 
1.78      anton    10104: @noindent
                   10105: @code{heap-new} invokes @code{construct}, thus
                   10106: initializing the field @code{circle-radius} with 50. We can draw
                   10107: this new circle at (100,100) with:
1.5       anton    10108: 
                   10109: @example
1.78      anton    10110: 100 100 my-circle draw
1.5       anton    10111: @end example
                   10112: 
1.78      anton    10113: @cindex selector invocation, restrictions
                   10114: @cindex class definition, restrictions
                   10115: Note: You can only invoke a selector if the object on the TOS
                   10116: (the receiving object) belongs to the class where the selector was
                   10117: defined or one of its descendents; e.g., you can invoke
                   10118: @code{draw} only for objects belonging to @code{graphical}
                   10119: or its descendents (e.g., @code{circle}).  Immediately before
                   10120: @code{end-class}, the search order has to be the same as
                   10121: immediately after @code{class}.
                   10122: 
                   10123: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   10124: @subsubsection The @file{object.fs} base class
                   10125: @cindex @code{object} class
                   10126: 
                   10127: When you define a class, you have to specify a parent class.  So how do
                   10128: you start defining classes? There is one class available from the start:
                   10129: @code{object}. It is ancestor for all classes and so is the
                   10130: only class that has no parent. It has two selectors: @code{construct}
                   10131: and @code{print}.
                   10132: 
                   10133: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   10134: @subsubsection Creating objects
                   10135: @cindex creating objects
                   10136: @cindex object creation
                   10137: @cindex object allocation options
                   10138: 
                   10139: @cindex @code{heap-new} discussion
                   10140: @cindex @code{dict-new} discussion
                   10141: @cindex @code{construct} discussion
                   10142: You can create and initialize an object of a class on the heap with
                   10143: @code{heap-new} ( ... class -- object ) and in the dictionary
                   10144: (allocation with @code{allot}) with @code{dict-new} (
                   10145: ... class -- object ). Both words invoke @code{construct}, which
                   10146: consumes the stack items indicated by "..." above.
                   10147: 
                   10148: @cindex @code{init-object} discussion
                   10149: @cindex @code{class-inst-size} discussion
                   10150: If you want to allocate memory for an object yourself, you can get its
                   10151: alignment and size with @code{class-inst-size 2@@} ( class --
                   10152: align size ). Once you have memory for an object, you can initialize
                   10153: it with @code{init-object} ( ... class object -- );
                   10154: @code{construct} does only a part of the necessary work.
                   10155: 
                   10156: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   10157: @subsubsection Object-Oriented Programming Style
                   10158: @cindex object-oriented programming style
                   10159: @cindex programming style, object-oriented
1.5       anton    10160: 
1.78      anton    10161: This section is not exhaustive.
1.5       anton    10162: 
1.78      anton    10163: @cindex stack effects of selectors
                   10164: @cindex selectors and stack effects
                   10165: In general, it is a good idea to ensure that all methods for the
                   10166: same selector have the same stack effect: when you invoke a selector,
                   10167: you often have no idea which method will be invoked, so, unless all
                   10168: methods have the same stack effect, you will not know the stack effect
                   10169: of the selector invocation.
1.5       anton    10170: 
1.78      anton    10171: One exception to this rule is methods for the selector
                   10172: @code{construct}. We know which method is invoked, because we
                   10173: specify the class to be constructed at the same place. Actually, I
                   10174: defined @code{construct} as a selector only to give the users a
                   10175: convenient way to specify initialization. The way it is used, a
                   10176: mechanism different from selector invocation would be more natural
                   10177: (but probably would take more code and more space to explain).
1.5       anton    10178: 
1.78      anton    10179: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   10180: @subsubsection Class Binding
                   10181: @cindex class binding
                   10182: @cindex early binding
1.5       anton    10183: 
1.78      anton    10184: @cindex late binding
                   10185: Normal selector invocations determine the method at run-time depending
                   10186: on the class of the receiving object. This run-time selection is called
                   10187: @i{late binding}.
1.5       anton    10188: 
1.78      anton    10189: Sometimes it's preferable to invoke a different method. For example,
                   10190: you might want to use the simple method for @code{print}ing
                   10191: @code{object}s instead of the possibly long-winded @code{print} method
                   10192: of the receiver class. You can achieve this by replacing the invocation
                   10193: of @code{print} with:
1.5       anton    10194: 
1.78      anton    10195: @cindex @code{[bind]} usage
1.5       anton    10196: @example
1.78      anton    10197: [bind] object print
1.5       anton    10198: @end example
                   10199: 
1.78      anton    10200: @noindent
                   10201: in compiled code or:
                   10202: 
                   10203: @cindex @code{bind} usage
1.5       anton    10204: @example
1.78      anton    10205: bind object print
1.5       anton    10206: @end example
                   10207: 
1.78      anton    10208: @cindex class binding, alternative to
                   10209: @noindent
                   10210: in interpreted code. Alternatively, you can define the method with a
                   10211: name (e.g., @code{print-object}), and then invoke it through the
                   10212: name. Class binding is just a (often more convenient) way to achieve
                   10213: the same effect; it avoids name clutter and allows you to invoke
                   10214: methods directly without naming them first.
1.5       anton    10215: 
1.78      anton    10216: @cindex superclass binding
                   10217: @cindex parent class binding
                   10218: A frequent use of class binding is this: When we define a method
                   10219: for a selector, we often want the method to do what the selector does
                   10220: in the parent class, and a little more. There is a special word for
                   10221: this purpose: @code{[parent]}; @code{[parent]
                   10222: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   10223: selector}}, where @code{@emph{parent}} is the parent
                   10224: class of the current class. E.g., a method definition might look like:
1.44      crook    10225: 
1.78      anton    10226: @cindex @code{[parent]} usage
                   10227: @example
                   10228: :noname
                   10229:   dup [parent] foo \ do parent's foo on the receiving object
                   10230:   ... \ do some more
                   10231: ; overrides foo
                   10232: @end example
1.6       pazsan   10233: 
1.78      anton    10234: @cindex class binding as optimization
                   10235: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   10236: March 1997), Andrew McKewan presents class binding as an optimization
                   10237: technique. I recommend not using it for this purpose unless you are in
                   10238: an emergency. Late binding is pretty fast with this model anyway, so the
                   10239: benefit of using class binding is small; the cost of using class binding
                   10240: where it is not appropriate is reduced maintainability.
1.44      crook    10241: 
1.78      anton    10242: While we are at programming style questions: You should bind
                   10243: selectors only to ancestor classes of the receiving object. E.g., say,
                   10244: you know that the receiving object is of class @code{foo} or its
                   10245: descendents; then you should bind only to @code{foo} and its
                   10246: ancestors.
1.12      anton    10247: 
1.78      anton    10248: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   10249: @subsubsection Method conveniences
                   10250: @cindex method conveniences
1.44      crook    10251: 
1.78      anton    10252: In a method you usually access the receiving object pretty often.  If
                   10253: you define the method as a plain colon definition (e.g., with
                   10254: @code{:noname}), you may have to do a lot of stack
                   10255: gymnastics. To avoid this, you can define the method with @code{m:
                   10256: ... ;m}. E.g., you could define the method for
                   10257: @code{draw}ing a @code{circle} with
1.6       pazsan   10258: 
1.78      anton    10259: @cindex @code{this} usage
                   10260: @cindex @code{m:} usage
                   10261: @cindex @code{;m} usage
                   10262: @example
                   10263: m: ( x y circle -- )
                   10264:   ( x y ) this circle-radius @@ draw-circle ;m
                   10265: @end example
1.6       pazsan   10266: 
1.78      anton    10267: @cindex @code{exit} in @code{m: ... ;m}
                   10268: @cindex @code{exitm} discussion
                   10269: @cindex @code{catch} in @code{m: ... ;m}
                   10270: When this method is executed, the receiver object is removed from the
                   10271: stack; you can access it with @code{this} (admittedly, in this
                   10272: example the use of @code{m: ... ;m} offers no advantage). Note
                   10273: that I specify the stack effect for the whole method (i.e. including
                   10274: the receiver object), not just for the code between @code{m:}
                   10275: and @code{;m}. You cannot use @code{exit} in
                   10276: @code{m:...;m}; instead, use
                   10277: @code{exitm}.@footnote{Moreover, for any word that calls
                   10278: @code{catch} and was defined before loading
                   10279: @code{objects.fs}, you have to redefine it like I redefined
                   10280: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12      anton    10281: 
1.78      anton    10282: @cindex @code{inst-var} usage
                   10283: You will frequently use sequences of the form @code{this
                   10284: @emph{field}} (in the example above: @code{this
                   10285: circle-radius}). If you use the field only in this way, you can
                   10286: define it with @code{inst-var} and eliminate the
                   10287: @code{this} before the field name. E.g., the @code{circle}
                   10288: class above could also be defined with:
1.6       pazsan   10289: 
1.78      anton    10290: @example
                   10291: graphical class
                   10292:   cell% inst-var radius
1.6       pazsan   10293: 
1.78      anton    10294: m: ( x y circle -- )
                   10295:   radius @@ draw-circle ;m
                   10296: overrides draw
1.6       pazsan   10297: 
1.78      anton    10298: m: ( n-radius circle -- )
                   10299:   radius ! ;m
                   10300: overrides construct
1.6       pazsan   10301: 
1.78      anton    10302: end-class circle
                   10303: @end example
1.6       pazsan   10304: 
1.78      anton    10305: @code{radius} can only be used in @code{circle} and its
                   10306: descendent classes and inside @code{m:...;m}.
1.6       pazsan   10307: 
1.78      anton    10308: @cindex @code{inst-value} usage
                   10309: You can also define fields with @code{inst-value}, which is
                   10310: to @code{inst-var} what @code{value} is to
                   10311: @code{variable}.  You can change the value of such a field with
                   10312: @code{[to-inst]}.  E.g., we could also define the class
                   10313: @code{circle} like this:
1.44      crook    10314: 
1.78      anton    10315: @example
                   10316: graphical class
                   10317:   inst-value radius
1.6       pazsan   10318: 
1.78      anton    10319: m: ( x y circle -- )
                   10320:   radius draw-circle ;m
                   10321: overrides draw
1.44      crook    10322: 
1.78      anton    10323: m: ( n-radius circle -- )
                   10324:   [to-inst] radius ;m
                   10325: overrides construct
1.6       pazsan   10326: 
1.78      anton    10327: end-class circle
                   10328: @end example
1.6       pazsan   10329: 
1.78      anton    10330: @c !! :m is easy to confuse with m:.  Another name would be better.
1.6       pazsan   10331: 
1.78      anton    10332: @c Finally, you can define named methods with @code{:m}.  One use of this
                   10333: @c feature is the definition of words that occur only in one class and are
                   10334: @c not intended to be overridden, but which still need method context
                   10335: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
                   10336: @c would be bound frequently, if defined anonymously.
1.6       pazsan   10337: 
                   10338: 
1.78      anton    10339: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
                   10340: @subsubsection Classes and Scoping
                   10341: @cindex classes and scoping
                   10342: @cindex scoping and classes
1.6       pazsan   10343: 
1.78      anton    10344: Inheritance is frequent, unlike structure extension. This exacerbates
                   10345: the problem with the field name convention (@pxref{Structure Naming
                   10346: Convention}): One always has to remember in which class the field was
                   10347: originally defined; changing a part of the class structure would require
                   10348: changes for renaming in otherwise unaffected code.
1.6       pazsan   10349: 
1.78      anton    10350: @cindex @code{inst-var} visibility
                   10351: @cindex @code{inst-value} visibility
                   10352: To solve this problem, I added a scoping mechanism (which was not in my
                   10353: original charter): A field defined with @code{inst-var} (or
                   10354: @code{inst-value}) is visible only in the class where it is defined and in
                   10355: the descendent classes of this class.  Using such fields only makes
                   10356: sense in @code{m:}-defined methods in these classes anyway.
1.6       pazsan   10357: 
1.78      anton    10358: This scoping mechanism allows us to use the unadorned field name,
                   10359: because name clashes with unrelated words become much less likely.
1.6       pazsan   10360: 
1.78      anton    10361: @cindex @code{protected} discussion
                   10362: @cindex @code{private} discussion
                   10363: Once we have this mechanism, we can also use it for controlling the
                   10364: visibility of other words: All words defined after
                   10365: @code{protected} are visible only in the current class and its
                   10366: descendents. @code{public} restores the compilation
                   10367: (i.e. @code{current}) word list that was in effect before. If you
                   10368: have several @code{protected}s without an intervening
                   10369: @code{public} or @code{set-current}, @code{public}
                   10370: will restore the compilation word list in effect before the first of
                   10371: these @code{protected}s.
1.6       pazsan   10372: 
1.78      anton    10373: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
                   10374: @subsubsection Dividing classes
                   10375: @cindex Dividing classes
                   10376: @cindex @code{methods}...@code{end-methods}
1.6       pazsan   10377: 
1.78      anton    10378: You may want to do the definition of methods separate from the
                   10379: definition of the class, its selectors, fields, and instance variables,
                   10380: i.e., separate the implementation from the definition.  You can do this
                   10381: in the following way:
1.6       pazsan   10382: 
1.78      anton    10383: @example
                   10384: graphical class
                   10385:   inst-value radius
                   10386: end-class circle
1.6       pazsan   10387: 
1.78      anton    10388: ... \ do some other stuff
1.6       pazsan   10389: 
1.78      anton    10390: circle methods \ now we are ready
1.44      crook    10391: 
1.78      anton    10392: m: ( x y circle -- )
                   10393:   radius draw-circle ;m
                   10394: overrides draw
1.6       pazsan   10395: 
1.78      anton    10396: m: ( n-radius circle -- )
                   10397:   [to-inst] radius ;m
                   10398: overrides construct
1.44      crook    10399: 
1.78      anton    10400: end-methods
                   10401: @end example
1.7       pazsan   10402: 
1.78      anton    10403: You can use several @code{methods}...@code{end-methods} sections.  The
                   10404: only things you can do to the class in these sections are: defining
                   10405: methods, and overriding the class's selectors.  You must not define new
                   10406: selectors or fields.
1.7       pazsan   10407: 
1.78      anton    10408: Note that you often have to override a selector before using it.  In
                   10409: particular, you usually have to override @code{construct} with a new
                   10410: method before you can invoke @code{heap-new} and friends.  E.g., you
                   10411: must not create a circle before the @code{overrides construct} sequence
                   10412: in the example above.
1.7       pazsan   10413: 
1.78      anton    10414: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
                   10415: @subsubsection Object Interfaces
                   10416: @cindex object interfaces
                   10417: @cindex interfaces for objects
1.7       pazsan   10418: 
1.78      anton    10419: In this model you can only call selectors defined in the class of the
                   10420: receiving objects or in one of its ancestors. If you call a selector
                   10421: with a receiving object that is not in one of these classes, the
                   10422: result is undefined; if you are lucky, the program crashes
                   10423: immediately.
1.7       pazsan   10424: 
1.78      anton    10425: @cindex selectors common to hardly-related classes
                   10426: Now consider the case when you want to have a selector (or several)
                   10427: available in two classes: You would have to add the selector to a
                   10428: common ancestor class, in the worst case to @code{object}. You
                   10429: may not want to do this, e.g., because someone else is responsible for
                   10430: this ancestor class.
1.7       pazsan   10431: 
1.78      anton    10432: The solution for this problem is interfaces. An interface is a
                   10433: collection of selectors. If a class implements an interface, the
                   10434: selectors become available to the class and its descendents. A class
                   10435: can implement an unlimited number of interfaces. For the problem
                   10436: discussed above, we would define an interface for the selector(s), and
                   10437: both classes would implement the interface.
1.7       pazsan   10438: 
1.78      anton    10439: As an example, consider an interface @code{storage} for
                   10440: writing objects to disk and getting them back, and a class
                   10441: @code{foo} that implements it. The code would look like this:
1.7       pazsan   10442: 
1.78      anton    10443: @cindex @code{interface} usage
                   10444: @cindex @code{end-interface} usage
                   10445: @cindex @code{implementation} usage
                   10446: @example
                   10447: interface
                   10448:   selector write ( file object -- )
                   10449:   selector read1 ( file object -- )
                   10450: end-interface storage
1.13      pazsan   10451: 
1.78      anton    10452: bar class
                   10453:   storage implementation
1.13      pazsan   10454: 
1.78      anton    10455: ... overrides write
                   10456: ... overrides read1
                   10457: ...
                   10458: end-class foo
                   10459: @end example
1.13      pazsan   10460: 
1.78      anton    10461: @noindent
                   10462: (I would add a word @code{read} @i{( file -- object )} that uses
                   10463: @code{read1} internally, but that's beyond the point illustrated
                   10464: here.)
1.13      pazsan   10465: 
1.78      anton    10466: Note that you cannot use @code{protected} in an interface; and
                   10467: of course you cannot define fields.
1.13      pazsan   10468: 
1.78      anton    10469: In the Neon model, all selectors are available for all classes;
                   10470: therefore it does not need interfaces. The price you pay in this model
                   10471: is slower late binding, and therefore, added complexity to avoid late
                   10472: binding.
1.13      pazsan   10473: 
1.78      anton    10474: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   10475: @subsubsection @file{objects.fs} Implementation
                   10476: @cindex @file{objects.fs} implementation
1.13      pazsan   10477: 
1.78      anton    10478: @cindex @code{object-map} discussion
                   10479: An object is a piece of memory, like one of the data structures
                   10480: described with @code{struct...end-struct}. It has a field
                   10481: @code{object-map} that points to the method map for the object's
                   10482: class.
1.13      pazsan   10483: 
1.78      anton    10484: @cindex method map
                   10485: @cindex virtual function table
                   10486: The @emph{method map}@footnote{This is Self terminology; in C++
                   10487: terminology: virtual function table.} is an array that contains the
                   10488: execution tokens (@i{xt}s) of the methods for the object's class. Each
                   10489: selector contains an offset into a method map.
1.13      pazsan   10490: 
1.78      anton    10491: @cindex @code{selector} implementation, class
                   10492: @code{selector} is a defining word that uses
                   10493: @code{CREATE} and @code{DOES>}. The body of the
                   10494: selector contains the offset; the @code{DOES>} action for a
                   10495: class selector is, basically:
1.8       pazsan   10496: 
                   10497: @example
1.78      anton    10498: ( object addr ) @@ over object-map @@ + @@ execute
1.13      pazsan   10499: @end example
                   10500: 
1.78      anton    10501: Since @code{object-map} is the first field of the object, it
                   10502: does not generate any code. As you can see, calling a selector has a
                   10503: small, constant cost.
1.26      crook    10504: 
1.78      anton    10505: @cindex @code{current-interface} discussion
                   10506: @cindex class implementation and representation
                   10507: A class is basically a @code{struct} combined with a method
                   10508: map. During the class definition the alignment and size of the class
                   10509: are passed on the stack, just as with @code{struct}s, so
                   10510: @code{field} can also be used for defining class
                   10511: fields. However, passing more items on the stack would be
                   10512: inconvenient, so @code{class} builds a data structure in memory,
                   10513: which is accessed through the variable
                   10514: @code{current-interface}. After its definition is complete, the
                   10515: class is represented on the stack by a pointer (e.g., as parameter for
                   10516: a child class definition).
1.26      crook    10517: 
1.78      anton    10518: A new class starts off with the alignment and size of its parent,
                   10519: and a copy of the parent's method map. Defining new fields extends the
                   10520: size and alignment; likewise, defining new selectors extends the
                   10521: method map. @code{overrides} just stores a new @i{xt} in the method
                   10522: map at the offset given by the selector.
1.13      pazsan   10523: 
1.78      anton    10524: @cindex class binding, implementation
                   10525: Class binding just gets the @i{xt} at the offset given by the selector
                   10526: from the class's method map and @code{compile,}s (in the case of
                   10527: @code{[bind]}) it.
1.13      pazsan   10528: 
1.78      anton    10529: @cindex @code{this} implementation
                   10530: @cindex @code{catch} and @code{this}
                   10531: @cindex @code{this} and @code{catch}
                   10532: I implemented @code{this} as a @code{value}. At the
                   10533: start of an @code{m:...;m} method the old @code{this} is
                   10534: stored to the return stack and restored at the end; and the object on
                   10535: the TOS is stored @code{TO this}. This technique has one
                   10536: disadvantage: If the user does not leave the method via
                   10537: @code{;m}, but via @code{throw} or @code{exit},
                   10538: @code{this} is not restored (and @code{exit} may
                   10539: crash). To deal with the @code{throw} problem, I have redefined
                   10540: @code{catch} to save and restore @code{this}; the same
                   10541: should be done with any word that can catch an exception. As for
                   10542: @code{exit}, I simply forbid it (as a replacement, there is
                   10543: @code{exitm}).
1.13      pazsan   10544: 
1.78      anton    10545: @cindex @code{inst-var} implementation
                   10546: @code{inst-var} is just the same as @code{field}, with
                   10547: a different @code{DOES>} action:
1.13      pazsan   10548: @example
1.78      anton    10549: @@ this +
1.8       pazsan   10550: @end example
1.78      anton    10551: Similar for @code{inst-value}.
1.8       pazsan   10552: 
1.78      anton    10553: @cindex class scoping implementation
                   10554: Each class also has a word list that contains the words defined with
                   10555: @code{inst-var} and @code{inst-value}, and its protected
                   10556: words. It also has a pointer to its parent. @code{class} pushes
                   10557: the word lists of the class and all its ancestors onto the search order stack,
                   10558: and @code{end-class} drops them.
1.20      pazsan   10559: 
1.78      anton    10560: @cindex interface implementation
                   10561: An interface is like a class without fields, parent and protected
                   10562: words; i.e., it just has a method map. If a class implements an
                   10563: interface, its method map contains a pointer to the method map of the
                   10564: interface. The positive offsets in the map are reserved for class
                   10565: methods, therefore interface map pointers have negative
                   10566: offsets. Interfaces have offsets that are unique throughout the
                   10567: system, unlike class selectors, whose offsets are only unique for the
                   10568: classes where the selector is available (invokable).
1.20      pazsan   10569: 
1.78      anton    10570: This structure means that interface selectors have to perform one
                   10571: indirection more than class selectors to find their method. Their body
                   10572: contains the interface map pointer offset in the class method map, and
                   10573: the method offset in the interface method map. The
                   10574: @code{does>} action for an interface selector is, basically:
1.20      pazsan   10575: 
                   10576: @example
1.78      anton    10577: ( object selector-body )
                   10578: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   10579: swap object-map @@ + @@ ( object selector-body map )
                   10580: swap selector-offset @@ + @@ execute
1.20      pazsan   10581: @end example
                   10582: 
1.78      anton    10583: where @code{object-map} and @code{selector-offset} are
                   10584: first fields and generate no code.
1.20      pazsan   10585: 
1.78      anton    10586: As a concrete example, consider the following code:
1.20      pazsan   10587: 
                   10588: @example
1.78      anton    10589: interface
                   10590:   selector if1sel1
                   10591:   selector if1sel2
                   10592: end-interface if1
1.20      pazsan   10593: 
1.78      anton    10594: object class
                   10595:   if1 implementation
                   10596:   selector cl1sel1
                   10597:   cell% inst-var cl1iv1
1.20      pazsan   10598: 
1.78      anton    10599: ' m1 overrides construct
                   10600: ' m2 overrides if1sel1
                   10601: ' m3 overrides if1sel2
                   10602: ' m4 overrides cl1sel2
                   10603: end-class cl1
1.20      pazsan   10604: 
1.78      anton    10605: create obj1 object dict-new drop
                   10606: create obj2 cl1    dict-new drop
                   10607: @end example
1.20      pazsan   10608: 
1.78      anton    10609: The data structure created by this code (including the data structure
                   10610: for @code{object}) is shown in the
                   10611: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
                   10612: @comment TODO add this diagram..
1.20      pazsan   10613: 
1.78      anton    10614: @node Objects Glossary,  , Objects Implementation, Objects
                   10615: @subsubsection @file{objects.fs} Glossary
                   10616: @cindex @file{objects.fs} Glossary
1.20      pazsan   10617: 
                   10618: 
1.78      anton    10619: doc---objects-bind
                   10620: doc---objects-<bind>
                   10621: doc---objects-bind'
                   10622: doc---objects-[bind]
                   10623: doc---objects-class
                   10624: doc---objects-class->map
                   10625: doc---objects-class-inst-size
                   10626: doc---objects-class-override!
1.79      anton    10627: doc---objects-class-previous
                   10628: doc---objects-class>order
1.78      anton    10629: doc---objects-construct
                   10630: doc---objects-current'
                   10631: doc---objects-[current]
                   10632: doc---objects-current-interface
                   10633: doc---objects-dict-new
                   10634: doc---objects-end-class
                   10635: doc---objects-end-class-noname
                   10636: doc---objects-end-interface
                   10637: doc---objects-end-interface-noname
                   10638: doc---objects-end-methods
                   10639: doc---objects-exitm
                   10640: doc---objects-heap-new
                   10641: doc---objects-implementation
                   10642: doc---objects-init-object
                   10643: doc---objects-inst-value
                   10644: doc---objects-inst-var
                   10645: doc---objects-interface
                   10646: doc---objects-m:
                   10647: doc---objects-:m
                   10648: doc---objects-;m
                   10649: doc---objects-method
                   10650: doc---objects-methods
                   10651: doc---objects-object
                   10652: doc---objects-overrides
                   10653: doc---objects-[parent]
                   10654: doc---objects-print
                   10655: doc---objects-protected
                   10656: doc---objects-public
                   10657: doc---objects-selector
                   10658: doc---objects-this
                   10659: doc---objects-<to-inst>
                   10660: doc---objects-[to-inst]
                   10661: doc---objects-to-this
                   10662: doc---objects-xt-new
1.20      pazsan   10663: 
                   10664: 
1.78      anton    10665: @c -------------------------------------------------------------
                   10666: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   10667: @subsection The @file{oof.fs} model
                   10668: @cindex oof
                   10669: @cindex object-oriented programming
1.20      pazsan   10670: 
1.78      anton    10671: @cindex @file{objects.fs}
                   10672: @cindex @file{oof.fs}
1.20      pazsan   10673: 
1.78      anton    10674: This section describes the @file{oof.fs} package.
1.20      pazsan   10675: 
1.78      anton    10676: The package described in this section has been used in bigFORTH since 1991, and
                   10677: used for two large applications: a chromatographic system used to
                   10678: create new medicaments, and a graphic user interface library (MINOS).
1.20      pazsan   10679: 
1.78      anton    10680: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   10681: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   10682: 10(2), 1994.
1.20      pazsan   10683: 
1.78      anton    10684: @menu
                   10685: * Properties of the OOF model::  
                   10686: * Basic OOF Usage::             
                   10687: * The OOF base class::          
                   10688: * Class Declaration::           
                   10689: * Class Implementation::        
                   10690: @end menu
1.20      pazsan   10691: 
1.78      anton    10692: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   10693: @subsubsection Properties of the @file{oof.fs} model
                   10694: @cindex @file{oof.fs} properties
1.20      pazsan   10695: 
1.78      anton    10696: @itemize @bullet
                   10697: @item
                   10698: This model combines object oriented programming with information
                   10699: hiding. It helps you writing large application, where scoping is
                   10700: necessary, because it provides class-oriented scoping.
1.20      pazsan   10701: 
1.78      anton    10702: @item
                   10703: Named objects, object pointers, and object arrays can be created,
                   10704: selector invocation uses the ``object selector'' syntax. Selector invocation
                   10705: to objects and/or selectors on the stack is a bit less convenient, but
                   10706: possible.
1.44      crook    10707: 
1.78      anton    10708: @item
                   10709: Selector invocation and instance variable usage of the active object is
                   10710: straightforward, since both make use of the active object.
1.44      crook    10711: 
1.78      anton    10712: @item
                   10713: Late binding is efficient and easy to use.
1.20      pazsan   10714: 
1.78      anton    10715: @item
                   10716: State-smart objects parse selectors. However, extensibility is provided
                   10717: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20      pazsan   10718: 
1.78      anton    10719: @item
                   10720: An implementation in ANS Forth is available.
1.20      pazsan   10721: 
1.78      anton    10722: @end itemize
1.23      crook    10723: 
                   10724: 
1.78      anton    10725: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   10726: @subsubsection Basic @file{oof.fs} Usage
                   10727: @cindex @file{oof.fs} usage
1.23      crook    10728: 
1.78      anton    10729: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23      crook    10730: 
1.78      anton    10731: You can define a class for graphical objects like this:
1.23      crook    10732: 
1.78      anton    10733: @cindex @code{class} usage
                   10734: @cindex @code{class;} usage
                   10735: @cindex @code{method} usage
                   10736: @example
                   10737: object class graphical \ "object" is the parent class
                   10738:   method draw ( x y graphical -- )
                   10739: class;
                   10740: @end example
1.23      crook    10741: 
1.78      anton    10742: This code defines a class @code{graphical} with an
                   10743: operation @code{draw}.  We can perform the operation
                   10744: @code{draw} on any @code{graphical} object, e.g.:
1.23      crook    10745: 
1.78      anton    10746: @example
                   10747: 100 100 t-rex draw
                   10748: @end example
1.23      crook    10749: 
1.78      anton    10750: @noindent
                   10751: where @code{t-rex} is an object or object pointer, created with e.g.
                   10752: @code{graphical : t-rex}.
1.23      crook    10753: 
1.78      anton    10754: @cindex abstract class
                   10755: How do we create a graphical object? With the present definitions,
                   10756: we cannot create a useful graphical object. The class
                   10757: @code{graphical} describes graphical objects in general, but not
                   10758: any concrete graphical object type (C++ users would call it an
                   10759: @emph{abstract class}); e.g., there is no method for the selector
                   10760: @code{draw} in the class @code{graphical}.
1.23      crook    10761: 
1.78      anton    10762: For concrete graphical objects, we define child classes of the
                   10763: class @code{graphical}, e.g.:
1.23      crook    10764: 
1.78      anton    10765: @example
                   10766: graphical class circle \ "graphical" is the parent class
                   10767:   cell var circle-radius
                   10768: how:
                   10769:   : draw ( x y -- )
                   10770:     circle-radius @@ draw-circle ;
1.23      crook    10771: 
1.78      anton    10772:   : init ( n-radius -- (
                   10773:     circle-radius ! ;
                   10774: class;
                   10775: @end example
1.1       anton    10776: 
1.78      anton    10777: Here we define a class @code{circle} as a child of @code{graphical},
                   10778: with a field @code{circle-radius}; it defines new methods for the
                   10779: selectors @code{draw} and @code{init} (@code{init} is defined in
                   10780: @code{object}, the parent class of @code{graphical}).
1.1       anton    10781: 
1.78      anton    10782: Now we can create a circle in the dictionary with:
1.1       anton    10783: 
1.78      anton    10784: @example
                   10785: 50 circle : my-circle
                   10786: @end example
1.21      crook    10787: 
1.78      anton    10788: @noindent
                   10789: @code{:} invokes @code{init}, thus initializing the field
                   10790: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   10791: with:
1.1       anton    10792: 
1.78      anton    10793: @example
                   10794: 100 100 my-circle draw
                   10795: @end example
1.1       anton    10796: 
1.78      anton    10797: @cindex selector invocation, restrictions
                   10798: @cindex class definition, restrictions
                   10799: Note: You can only invoke a selector if the receiving object belongs to
                   10800: the class where the selector was defined or one of its descendents;
                   10801: e.g., you can invoke @code{draw} only for objects belonging to
                   10802: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   10803: mechanism will check if you try to invoke a selector that is not
                   10804: defined in this class hierarchy, so you'll get an error at compilation
                   10805: time.
1.1       anton    10806: 
                   10807: 
1.78      anton    10808: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   10809: @subsubsection The @file{oof.fs} base class
                   10810: @cindex @file{oof.fs} base class
1.1       anton    10811: 
1.78      anton    10812: When you define a class, you have to specify a parent class.  So how do
                   10813: you start defining classes? There is one class available from the start:
                   10814: @code{object}. You have to use it as ancestor for all classes. It is the
                   10815: only class that has no parent. Classes are also objects, except that
                   10816: they don't have instance variables; class manipulation such as
                   10817: inheritance or changing definitions of a class is handled through
                   10818: selectors of the class @code{object}.
1.1       anton    10819: 
1.78      anton    10820: @code{object} provides a number of selectors:
1.1       anton    10821: 
1.78      anton    10822: @itemize @bullet
                   10823: @item
                   10824: @code{class} for subclassing, @code{definitions} to add definitions
                   10825: later on, and @code{class?} to get type informations (is the class a
                   10826: subclass of the class passed on the stack?).
1.1       anton    10827: 
1.78      anton    10828: doc---object-class
                   10829: doc---object-definitions
                   10830: doc---object-class?
1.1       anton    10831: 
                   10832: 
1.26      crook    10833: @item
1.78      anton    10834: @code{init} and @code{dispose} as constructor and destructor of the
                   10835: object. @code{init} is invocated after the object's memory is allocated,
                   10836: while @code{dispose} also handles deallocation. Thus if you redefine
                   10837: @code{dispose}, you have to call the parent's dispose with @code{super
                   10838: dispose}, too.
                   10839: 
                   10840: doc---object-init
                   10841: doc---object-dispose
                   10842: 
1.1       anton    10843: 
1.26      crook    10844: @item
1.78      anton    10845: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   10846: @code{[]} to create named and unnamed objects and object arrays or
                   10847: object pointers.
                   10848: 
                   10849: doc---object-new
                   10850: doc---object-new[]
                   10851: doc---object-:
                   10852: doc---object-ptr
                   10853: doc---object-asptr
                   10854: doc---object-[]
                   10855: 
1.1       anton    10856: 
1.26      crook    10857: @item
1.78      anton    10858: @code{::} and @code{super} for explicit scoping. You should use explicit
                   10859: scoping only for super classes or classes with the same set of instance
                   10860: variables. Explicitly-scoped selectors use early binding.
1.21      crook    10861: 
1.78      anton    10862: doc---object-::
                   10863: doc---object-super
1.21      crook    10864: 
                   10865: 
1.26      crook    10866: @item
1.78      anton    10867: @code{self} to get the address of the object
1.21      crook    10868: 
1.78      anton    10869: doc---object-self
1.21      crook    10870: 
                   10871: 
1.78      anton    10872: @item
                   10873: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   10874: pointers and instance defers.
1.21      crook    10875: 
1.78      anton    10876: doc---object-bind
                   10877: doc---object-bound
                   10878: doc---object-link
                   10879: doc---object-is
1.21      crook    10880: 
                   10881: 
1.78      anton    10882: @item
                   10883: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   10884: form the stack, and @code{postpone} to generate selector invocation code.
1.21      crook    10885: 
1.78      anton    10886: doc---object-'
                   10887: doc---object-postpone
1.21      crook    10888: 
                   10889: 
1.78      anton    10890: @item
                   10891: @code{with} and @code{endwith} to select the active object from the
                   10892: stack, and enable its scope. Using @code{with} and @code{endwith}
                   10893: also allows you to create code using selector @code{postpone} without being
                   10894: trapped by the state-smart objects.
1.21      crook    10895: 
1.78      anton    10896: doc---object-with
                   10897: doc---object-endwith
1.21      crook    10898: 
                   10899: 
1.78      anton    10900: @end itemize
1.21      crook    10901: 
1.78      anton    10902: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   10903: @subsubsection Class Declaration
                   10904: @cindex class declaration
1.21      crook    10905: 
1.78      anton    10906: @itemize @bullet
                   10907: @item
                   10908: Instance variables
1.21      crook    10909: 
1.78      anton    10910: doc---oof-var
1.21      crook    10911: 
                   10912: 
1.78      anton    10913: @item
                   10914: Object pointers
1.21      crook    10915: 
1.78      anton    10916: doc---oof-ptr
                   10917: doc---oof-asptr
1.21      crook    10918: 
                   10919: 
1.78      anton    10920: @item
                   10921: Instance defers
1.21      crook    10922: 
1.78      anton    10923: doc---oof-defer
1.21      crook    10924: 
                   10925: 
1.78      anton    10926: @item
                   10927: Method selectors
1.21      crook    10928: 
1.78      anton    10929: doc---oof-early
                   10930: doc---oof-method
1.21      crook    10931: 
                   10932: 
1.78      anton    10933: @item
                   10934: Class-wide variables
1.21      crook    10935: 
1.78      anton    10936: doc---oof-static
1.21      crook    10937: 
                   10938: 
1.78      anton    10939: @item
                   10940: End declaration
1.1       anton    10941: 
1.78      anton    10942: doc---oof-how:
                   10943: doc---oof-class;
1.21      crook    10944: 
                   10945: 
1.78      anton    10946: @end itemize
1.21      crook    10947: 
1.78      anton    10948: @c -------------------------------------------------------------
                   10949: @node Class Implementation,  , Class Declaration, OOF
                   10950: @subsubsection Class Implementation
                   10951: @cindex class implementation
1.21      crook    10952: 
1.78      anton    10953: @c -------------------------------------------------------------
                   10954: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   10955: @subsection The @file{mini-oof.fs} model
                   10956: @cindex mini-oof
1.21      crook    10957: 
1.78      anton    10958: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79      anton    10959: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78      anton    10960: and reduces to the bare minimum of features. This is based on a posting
                   10961: of Bernd Paysan in comp.lang.forth.
1.21      crook    10962: 
1.78      anton    10963: @menu
                   10964: * Basic Mini-OOF Usage::        
                   10965: * Mini-OOF Example::            
                   10966: * Mini-OOF Implementation::     
                   10967: @end menu
1.21      crook    10968: 
1.78      anton    10969: @c -------------------------------------------------------------
                   10970: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
                   10971: @subsubsection Basic @file{mini-oof.fs} Usage
                   10972: @cindex mini-oof usage
1.21      crook    10973: 
1.78      anton    10974: There is a base class (@code{class}, which allocates one cell for the
                   10975: object pointer) plus seven other words: to define a method, a variable,
                   10976: a class; to end a class, to resolve binding, to allocate an object and
                   10977: to compile a class method.
                   10978: @comment TODO better description of the last one
1.26      crook    10979: 
1.21      crook    10980: 
1.78      anton    10981: doc-object
                   10982: doc-method
                   10983: doc-var
                   10984: doc-class
                   10985: doc-end-class
                   10986: doc-defines
                   10987: doc-new
                   10988: doc-::
1.21      crook    10989: 
                   10990: 
                   10991: 
1.78      anton    10992: @c -------------------------------------------------------------
                   10993: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   10994: @subsubsection Mini-OOF Example
                   10995: @cindex mini-oof example
1.1       anton    10996: 
1.78      anton    10997: A short example shows how to use this package. This example, in slightly
                   10998: extended form, is supplied as @file{moof-exm.fs}
                   10999: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20      pazsan   11000: 
1.26      crook    11001: @example
1.78      anton    11002: object class
                   11003:   method init
                   11004:   method draw
                   11005: end-class graphical
1.26      crook    11006: @end example
1.20      pazsan   11007: 
1.78      anton    11008: This code defines a class @code{graphical} with an
                   11009: operation @code{draw}.  We can perform the operation
                   11010: @code{draw} on any @code{graphical} object, e.g.:
1.20      pazsan   11011: 
1.26      crook    11012: @example
1.78      anton    11013: 100 100 t-rex draw
1.26      crook    11014: @end example
1.12      anton    11015: 
1.78      anton    11016: where @code{t-rex} is an object or object pointer, created with e.g.
                   11017: @code{graphical new Constant t-rex}.
1.12      anton    11018: 
1.78      anton    11019: For concrete graphical objects, we define child classes of the
                   11020: class @code{graphical}, e.g.:
1.12      anton    11021: 
1.26      crook    11022: @example
                   11023: graphical class
1.78      anton    11024:   cell var circle-radius
                   11025: end-class circle \ "graphical" is the parent class
1.12      anton    11026: 
1.78      anton    11027: :noname ( x y -- )
                   11028:   circle-radius @@ draw-circle ; circle defines draw
                   11029: :noname ( r -- )
                   11030:   circle-radius ! ; circle defines init
                   11031: @end example
1.12      anton    11032: 
1.78      anton    11033: There is no implicit init method, so we have to define one. The creation
                   11034: code of the object now has to call init explicitely.
1.21      crook    11035: 
1.78      anton    11036: @example
                   11037: circle new Constant my-circle
                   11038: 50 my-circle init
1.12      anton    11039: @end example
                   11040: 
1.78      anton    11041: It is also possible to add a function to create named objects with
                   11042: automatic call of @code{init}, given that all objects have @code{init}
                   11043: on the same place:
1.38      anton    11044: 
1.78      anton    11045: @example
                   11046: : new: ( .. o "name" -- )
                   11047:     new dup Constant init ;
                   11048: 80 circle new: large-circle
                   11049: @end example
1.12      anton    11050: 
1.78      anton    11051: We can draw this new circle at (100,100) with:
1.12      anton    11052: 
1.78      anton    11053: @example
                   11054: 100 100 my-circle draw
                   11055: @end example
1.12      anton    11056: 
1.78      anton    11057: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
                   11058: @subsubsection @file{mini-oof.fs} Implementation
1.12      anton    11059: 
1.78      anton    11060: Object-oriented systems with late binding typically use a
                   11061: ``vtable''-approach: the first variable in each object is a pointer to a
                   11062: table, which contains the methods as function pointers. The vtable
                   11063: may also contain other information.
1.12      anton    11064: 
1.79      anton    11065: So first, let's declare selectors:
1.37      anton    11066: 
                   11067: @example
1.79      anton    11068: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
1.78      anton    11069:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
                   11070: @end example
1.37      anton    11071: 
1.79      anton    11072: During selector declaration, the number of selectors and instance
                   11073: variables is on the stack (in address units). @code{method} creates one
                   11074: selector and increments the selector number. To execute a selector, it
1.78      anton    11075: takes the object, fetches the vtable pointer, adds the offset, and
1.79      anton    11076: executes the method @i{xt} stored there. Each selector takes the object
                   11077: it is invoked with as top of stack parameter; it passes the parameters
                   11078: (including the object) unchanged to the appropriate method which should
1.78      anton    11079: consume that object.
1.37      anton    11080: 
1.78      anton    11081: Now, we also have to declare instance variables
1.37      anton    11082: 
1.78      anton    11083: @example
1.79      anton    11084: : var ( m v size "name" -- m v' ) Create  over , +
1.78      anton    11085:   DOES> ( o -- addr ) @@ + ;
1.37      anton    11086: @end example
                   11087: 
1.78      anton    11088: As before, a word is created with the current offset. Instance
                   11089: variables can have different sizes (cells, floats, doubles, chars), so
                   11090: all we do is take the size and add it to the offset. If your machine
                   11091: has alignment restrictions, put the proper @code{aligned} or
                   11092: @code{faligned} before the variable, to adjust the variable
                   11093: offset. That's why it is on the top of stack.
1.37      anton    11094: 
1.78      anton    11095: We need a starting point (the base object) and some syntactic sugar:
1.37      anton    11096: 
1.78      anton    11097: @example
                   11098: Create object  1 cells , 2 cells ,
1.79      anton    11099: : class ( class -- class selectors vars ) dup 2@@ ;
1.78      anton    11100: @end example
1.12      anton    11101: 
1.78      anton    11102: For inheritance, the vtable of the parent object has to be
                   11103: copied when a new, derived class is declared. This gives all the
                   11104: methods of the parent class, which can be overridden, though.
1.12      anton    11105: 
1.78      anton    11106: @example
1.79      anton    11107: : end-class  ( class selectors vars "name" -- )
1.78      anton    11108:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   11109:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
                   11110: @end example
1.12      anton    11111: 
1.78      anton    11112: The first line creates the vtable, initialized with
                   11113: @code{noop}s. The second line is the inheritance mechanism, it
                   11114: copies the xts from the parent vtable.
1.12      anton    11115: 
1.78      anton    11116: We still have no way to define new methods, let's do that now:
1.12      anton    11117: 
1.26      crook    11118: @example
1.79      anton    11119: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78      anton    11120: @end example
1.12      anton    11121: 
1.78      anton    11122: To allocate a new object, we need a word, too:
1.12      anton    11123: 
1.78      anton    11124: @example
                   11125: : new ( class -- o )  here over @@ allot swap over ! ;
1.12      anton    11126: @end example
                   11127: 
1.78      anton    11128: Sometimes derived classes want to access the method of the
                   11129: parent object. There are two ways to achieve this with Mini-OOF:
                   11130: first, you could use named words, and second, you could look up the
                   11131: vtable of the parent object.
1.12      anton    11132: 
1.78      anton    11133: @example
                   11134: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
                   11135: @end example
1.12      anton    11136: 
                   11137: 
1.78      anton    11138: Nothing can be more confusing than a good example, so here is
                   11139: one. First let's declare a text object (called
                   11140: @code{button}), that stores text and position:
1.12      anton    11141: 
1.78      anton    11142: @example
                   11143: object class
                   11144:   cell var text
                   11145:   cell var len
                   11146:   cell var x
                   11147:   cell var y
                   11148:   method init
                   11149:   method draw
                   11150: end-class button
                   11151: @end example
1.12      anton    11152: 
1.78      anton    11153: @noindent
                   11154: Now, implement the two methods, @code{draw} and @code{init}:
1.21      crook    11155: 
1.26      crook    11156: @example
1.78      anton    11157: :noname ( o -- )
                   11158:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
                   11159:  button defines draw
                   11160: :noname ( addr u o -- )
                   11161:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
                   11162:  button defines init
1.26      crook    11163: @end example
1.12      anton    11164: 
1.78      anton    11165: @noindent
                   11166: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79      anton    11167: new data and no new selectors:
1.78      anton    11168: 
                   11169: @example
                   11170: button class
                   11171: end-class bold-button
1.12      anton    11172: 
1.78      anton    11173: : bold   27 emit ." [1m" ;
                   11174: : normal 27 emit ." [0m" ;
                   11175: @end example
1.1       anton    11176: 
1.78      anton    11177: @noindent
                   11178: The class @code{bold-button} has a different draw method to
                   11179: @code{button}, but the new method is defined in terms of the draw method
                   11180: for @code{button}:
1.20      pazsan   11181: 
1.78      anton    11182: @example
                   11183: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   11184: @end example
1.21      crook    11185: 
1.78      anton    11186: @noindent
1.79      anton    11187: Finally, create two objects and apply selectors:
1.21      crook    11188: 
1.26      crook    11189: @example
1.78      anton    11190: button new Constant foo
                   11191: s" thin foo" foo init
                   11192: page
                   11193: foo draw
                   11194: bold-button new Constant bar
                   11195: s" fat bar" bar init
                   11196: 1 bar y !
                   11197: bar draw
1.26      crook    11198: @end example
1.21      crook    11199: 
                   11200: 
1.78      anton    11201: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
                   11202: @subsection Comparison with other object models
                   11203: @cindex comparison of object models
                   11204: @cindex object models, comparison
                   11205: 
                   11206: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   11207: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   11208: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   11209: relation of the object models described here to two well-known and two
                   11210: closely-related (by the use of method maps) models.  Andras Zsoter
                   11211: helped us with this section.
                   11212: 
                   11213: @cindex Neon model
                   11214: The most popular model currently seems to be the Neon model (see
                   11215: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   11216: 1997) by Andrew McKewan) but this model has a number of limitations
                   11217: @footnote{A longer version of this critique can be
                   11218: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   11219: Dimensions, May 1997) by Anton Ertl.}:
                   11220: 
                   11221: @itemize @bullet
                   11222: @item
                   11223: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
                   11224: to pass objects on the stack.
1.21      crook    11225: 
1.78      anton    11226: @item
                   11227: It requires that the selector parses the input stream (at
1.79      anton    11228: compile time); this leads to reduced extensibility and to bugs that are
1.78      anton    11229: hard to find.
1.21      crook    11230: 
1.78      anton    11231: @item
1.79      anton    11232: It allows using every selector on every object; this eliminates the
                   11233: need for interfaces, but makes it harder to create efficient
                   11234: implementations.
1.78      anton    11235: @end itemize
1.21      crook    11236: 
1.78      anton    11237: @cindex Pountain's object-oriented model
                   11238: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   11239: Press, London, 1987) by Dick Pountain. However, it is not really about
                   11240: object-oriented programming, because it hardly deals with late
                   11241: binding. Instead, it focuses on features like information hiding and
                   11242: overloading that are characteristic of modular languages like Ada (83).
1.26      crook    11243: 
1.78      anton    11244: @cindex Zsoter's object-oriented model
1.79      anton    11245: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
                   11246: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
                   11247: describes a model that makes heavy use of an active object (like
                   11248: @code{this} in @file{objects.fs}): The active object is not only used
                   11249: for accessing all fields, but also specifies the receiving object of
                   11250: every selector invocation; you have to change the active object
                   11251: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
                   11252: changes more or less implicitly at @code{m: ... ;m}. Such a change at
                   11253: the method entry point is unnecessary with Zsoter's model, because the
                   11254: receiving object is the active object already. On the other hand, the
                   11255: explicit change is absolutely necessary in that model, because otherwise
                   11256: no one could ever change the active object. An ANS Forth implementation
                   11257: of this model is available through
                   11258: @uref{http://www.forth.org/oopf.html}.
1.21      crook    11259: 
1.78      anton    11260: @cindex @file{oof.fs}, differences to other models
                   11261: The @file{oof.fs} model combines information hiding and overloading
                   11262: resolution (by keeping names in various word lists) with object-oriented
                   11263: programming. It sets the active object implicitly on method entry, but
                   11264: also allows explicit changing (with @code{>o...o>} or with
                   11265: @code{with...endwith}). It uses parsing and state-smart objects and
                   11266: classes for resolving overloading and for early binding: the object or
                   11267: class parses the selector and determines the method from this. If the
                   11268: selector is not parsed by an object or class, it performs a call to the
                   11269: selector for the active object (late binding), like Zsoter's model.
                   11270: Fields are always accessed through the active object. The big
                   11271: disadvantage of this model is the parsing and the state-smartness, which
                   11272: reduces extensibility and increases the opportunities for subtle bugs;
                   11273: essentially, you are only safe if you never tick or @code{postpone} an
                   11274: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21      crook    11275: 
1.78      anton    11276: @cindex @file{mini-oof.fs}, differences to other models
                   11277: The @file{mini-oof.fs} model is quite similar to a very stripped-down
                   11278: version of the @file{objects.fs} model, but syntactically it is a
                   11279: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21      crook    11280: 
                   11281: 
1.78      anton    11282: @c -------------------------------------------------------------
                   11283: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
                   11284: @section Programming Tools
                   11285: @cindex programming tools
1.21      crook    11286: 
1.78      anton    11287: @c !! move this and assembler down below OO stuff.
1.21      crook    11288: 
1.78      anton    11289: @menu
                   11290: * Examining::                   
                   11291: * Forgetting words::            
                   11292: * Debugging::                   Simple and quick.
                   11293: * Assertions::                  Making your programs self-checking.
                   11294: * Singlestep Debugger::         Executing your program word by word.
                   11295: @end menu
1.21      crook    11296: 
1.78      anton    11297: @node Examining, Forgetting words, Programming Tools, Programming Tools
                   11298: @subsection Examining data and code
                   11299: @cindex examining data and code
                   11300: @cindex data examination
                   11301: @cindex code examination
1.44      crook    11302: 
1.78      anton    11303: The following words inspect the stack non-destructively:
1.21      crook    11304: 
1.78      anton    11305: doc-.s
                   11306: doc-f.s
1.44      crook    11307: 
1.78      anton    11308: There is a word @code{.r} but it does @i{not} display the return stack!
                   11309: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21      crook    11310: 
1.78      anton    11311: doc-depth
                   11312: doc-fdepth
                   11313: doc-clearstack
1.21      crook    11314: 
1.78      anton    11315: The following words inspect memory.
1.21      crook    11316: 
1.78      anton    11317: doc-?
                   11318: doc-dump
1.21      crook    11319: 
1.78      anton    11320: And finally, @code{see} allows to inspect code:
1.21      crook    11321: 
1.78      anton    11322: doc-see
                   11323: doc-xt-see
1.111     anton    11324: doc-simple-see
                   11325: doc-simple-see-range
1.21      crook    11326: 
1.78      anton    11327: @node Forgetting words, Debugging, Examining, Programming Tools
                   11328: @subsection Forgetting words
                   11329: @cindex words, forgetting
                   11330: @cindex forgeting words
1.21      crook    11331: 
1.78      anton    11332: @c  anton: other, maybe better places for this subsection: Defining Words;
                   11333: @c  Dictionary allocation.  At least a reference should be there.
1.21      crook    11334: 
1.78      anton    11335: Forth allows you to forget words (and everything that was alloted in the
                   11336: dictonary after them) in a LIFO manner.
1.21      crook    11337: 
1.78      anton    11338: doc-marker
1.21      crook    11339: 
1.78      anton    11340: The most common use of this feature is during progam development: when
                   11341: you change a source file, forget all the words it defined and load it
                   11342: again (since you also forget everything defined after the source file
                   11343: was loaded, you have to reload that, too).  Note that effects like
                   11344: storing to variables and destroyed system words are not undone when you
                   11345: forget words.  With a system like Gforth, that is fast enough at
                   11346: starting up and compiling, I find it more convenient to exit and restart
                   11347: Gforth, as this gives me a clean slate.
1.21      crook    11348: 
1.78      anton    11349: Here's an example of using @code{marker} at the start of a source file
                   11350: that you are debugging; it ensures that you only ever have one copy of
                   11351: the file's definitions compiled at any time:
1.21      crook    11352: 
1.78      anton    11353: @example
                   11354: [IFDEF] my-code
                   11355:     my-code
                   11356: [ENDIF]
1.26      crook    11357: 
1.78      anton    11358: marker my-code
                   11359: init-included-files
1.21      crook    11360: 
1.78      anton    11361: \ .. definitions start here
                   11362: \ .
                   11363: \ .
                   11364: \ end
                   11365: @end example
1.21      crook    11366: 
1.26      crook    11367: 
1.78      anton    11368: @node Debugging, Assertions, Forgetting words, Programming Tools
                   11369: @subsection Debugging
                   11370: @cindex debugging
1.21      crook    11371: 
1.78      anton    11372: Languages with a slow edit/compile/link/test development loop tend to
                   11373: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21      crook    11374: 
1.78      anton    11375: A much better (faster) way in fast-compiling languages is to add
                   11376: printing code at well-selected places, let the program run, look at
                   11377: the output, see where things went wrong, add more printing code, etc.,
                   11378: until the bug is found.
1.21      crook    11379: 
1.78      anton    11380: The simple debugging aids provided in @file{debugs.fs}
                   11381: are meant to support this style of debugging.
1.21      crook    11382: 
1.78      anton    11383: The word @code{~~} prints debugging information (by default the source
                   11384: location and the stack contents). It is easy to insert. If you use Emacs
                   11385: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   11386: query-replace them with nothing). The deferred words
1.101     anton    11387: @code{printdebugdata} and @code{.debugline} control the output of
1.78      anton    11388: @code{~~}. The default source location output format works well with
                   11389: Emacs' compilation mode, so you can step through the program at the
                   11390: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   11391: is that you can step in any direction and you know where the crash has
                   11392: happened or where the strange data has occurred).
1.21      crook    11393: 
1.78      anton    11394: doc-~~
                   11395: doc-printdebugdata
1.101     anton    11396: doc-.debugline
1.21      crook    11397: 
1.106     anton    11398: @cindex filenames in @code{~~} output
                   11399: @code{~~} (and assertions) will usually print the wrong file name if a
                   11400: marker is executed in the same file after their occurance.  They will
                   11401: print @samp{*somewhere*} as file name if a marker is executed in the
                   11402: same file before their occurance.
                   11403: 
                   11404: 
1.78      anton    11405: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   11406: @subsection Assertions
                   11407: @cindex assertions
1.21      crook    11408: 
1.78      anton    11409: It is a good idea to make your programs self-checking, especially if you
                   11410: make an assumption that may become invalid during maintenance (for
                   11411: example, that a certain field of a data structure is never zero). Gforth
                   11412: supports @dfn{assertions} for this purpose. They are used like this:
1.21      crook    11413: 
                   11414: @example
1.78      anton    11415: assert( @i{flag} )
1.26      crook    11416: @end example
                   11417: 
1.78      anton    11418: The code between @code{assert(} and @code{)} should compute a flag, that
                   11419: should be true if everything is alright and false otherwise. It should
                   11420: not change anything else on the stack. The overall stack effect of the
                   11421: assertion is @code{( -- )}. E.g.
1.21      crook    11422: 
1.26      crook    11423: @example
1.78      anton    11424: assert( 1 1 + 2 = ) \ what we learn in school
                   11425: assert( dup 0<> ) \ assert that the top of stack is not zero
                   11426: assert( false ) \ this code should not be reached
1.21      crook    11427: @end example
                   11428: 
1.78      anton    11429: The need for assertions is different at different times. During
                   11430: debugging, we want more checking, in production we sometimes care more
                   11431: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   11432: becomes a comment. Depending on the importance of an assertion and the
                   11433: time it takes to check it, you may want to turn off some assertions and
                   11434: keep others turned on. Gforth provides several levels of assertions for
                   11435: this purpose:
                   11436: 
                   11437: 
                   11438: doc-assert0(
                   11439: doc-assert1(
                   11440: doc-assert2(
                   11441: doc-assert3(
                   11442: doc-assert(
                   11443: doc-)
1.21      crook    11444: 
                   11445: 
1.78      anton    11446: The variable @code{assert-level} specifies the highest assertions that
                   11447: are turned on. I.e., at the default @code{assert-level} of one,
                   11448: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   11449: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26      crook    11450: 
1.78      anton    11451: The value of @code{assert-level} is evaluated at compile-time, not at
                   11452: run-time. Therefore you cannot turn assertions on or off at run-time;
                   11453: you have to set the @code{assert-level} appropriately before compiling a
                   11454: piece of code. You can compile different pieces of code at different
                   11455: @code{assert-level}s (e.g., a trusted library at level 1 and
                   11456: newly-written code at level 3).
1.26      crook    11457: 
                   11458: 
1.78      anton    11459: doc-assert-level
1.26      crook    11460: 
                   11461: 
1.78      anton    11462: If an assertion fails, a message compatible with Emacs' compilation mode
                   11463: is produced and the execution is aborted (currently with @code{ABORT"}.
                   11464: If there is interest, we will introduce a special throw code. But if you
                   11465: intend to @code{catch} a specific condition, using @code{throw} is
                   11466: probably more appropriate than an assertion).
1.106     anton    11467: 
                   11468: @cindex filenames in assertion output
                   11469: Assertions (and @code{~~}) will usually print the wrong file name if a
                   11470: marker is executed in the same file after their occurance.  They will
                   11471: print @samp{*somewhere*} as file name if a marker is executed in the
                   11472: same file before their occurance.
1.44      crook    11473: 
1.78      anton    11474: Definitions in ANS Forth for these assertion words are provided
                   11475: in @file{compat/assert.fs}.
1.26      crook    11476: 
1.44      crook    11477: 
1.78      anton    11478: @node Singlestep Debugger,  , Assertions, Programming Tools
                   11479: @subsection Singlestep Debugger
                   11480: @cindex singlestep Debugger
                   11481: @cindex debugging Singlestep
1.44      crook    11482: 
1.112     anton    11483: The singlestep debugger does not work in this release.
                   11484: 
1.78      anton    11485: When you create a new word there's often the need to check whether it
                   11486: behaves correctly or not. You can do this by typing @code{dbg
                   11487: badword}. A debug session might look like this:
1.26      crook    11488: 
1.78      anton    11489: @example
                   11490: : badword 0 DO i . LOOP ;  ok
                   11491: 2 dbg badword 
                   11492: : badword  
                   11493: Scanning code...
1.44      crook    11494: 
1.78      anton    11495: Nesting debugger ready!
1.44      crook    11496: 
1.78      anton    11497: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   11498: 400D4740  8049F68 DO             -> [ 0 ] 
                   11499: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   11500: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   11501: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   11502: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   11503: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   11504: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   11505: 400D4758  804B384 ;              ->  ok
                   11506: @end example
1.21      crook    11507: 
1.78      anton    11508: Each line displayed is one step. You always have to hit return to
                   11509: execute the next word that is displayed. If you don't want to execute
                   11510: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   11511: an overview what keys are available:
1.44      crook    11512: 
1.78      anton    11513: @table @i
1.44      crook    11514: 
1.78      anton    11515: @item @key{RET}
                   11516: Next; Execute the next word.
1.21      crook    11517: 
1.78      anton    11518: @item n
                   11519: Nest; Single step through next word.
1.44      crook    11520: 
1.78      anton    11521: @item u
                   11522: Unnest; Stop debugging and execute rest of word. If we got to this word
                   11523: with nest, continue debugging with the calling word.
1.44      crook    11524: 
1.78      anton    11525: @item d
                   11526: Done; Stop debugging and execute rest.
1.21      crook    11527: 
1.78      anton    11528: @item s
                   11529: Stop; Abort immediately.
1.44      crook    11530: 
1.78      anton    11531: @end table
1.44      crook    11532: 
1.78      anton    11533: Debugging large application with this mechanism is very difficult, because
                   11534: you have to nest very deeply into the program before the interesting part
                   11535: begins. This takes a lot of time. 
1.26      crook    11536: 
1.78      anton    11537: To do it more directly put a @code{BREAK:} command into your source code.
                   11538: When program execution reaches @code{BREAK:} the single step debugger is
                   11539: invoked and you have all the features described above.
1.44      crook    11540: 
1.78      anton    11541: If you have more than one part to debug it is useful to know where the
                   11542: program has stopped at the moment. You can do this by the 
                   11543: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   11544: string is typed out when the ``breakpoint'' is reached.
1.44      crook    11545: 
1.26      crook    11546: 
1.78      anton    11547: doc-dbg
                   11548: doc-break:
                   11549: doc-break"
1.44      crook    11550: 
                   11551: 
1.26      crook    11552: 
1.78      anton    11553: @c -------------------------------------------------------------
                   11554: @node Assembler and Code Words, Threading Words, Programming Tools, Words
                   11555: @section Assembler and Code Words
                   11556: @cindex assembler
                   11557: @cindex code words
1.44      crook    11558: 
1.78      anton    11559: @menu
                   11560: * Code and ;code::              
                   11561: * Common Assembler::            Assembler Syntax
                   11562: * Common Disassembler::         
                   11563: * 386 Assembler::               Deviations and special cases
                   11564: * Alpha Assembler::             Deviations and special cases
                   11565: * MIPS assembler::              Deviations and special cases
                   11566: * Other assemblers::            How to write them
                   11567: @end menu
1.21      crook    11568: 
1.78      anton    11569: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
                   11570: @subsection @code{Code} and @code{;code}
1.26      crook    11571: 
1.78      anton    11572: Gforth provides some words for defining primitives (words written in
                   11573: machine code), and for defining the machine-code equivalent of
                   11574: @code{DOES>}-based defining words. However, the machine-independent
                   11575: nature of Gforth poses a few problems: First of all, Gforth runs on
                   11576: several architectures, so it can provide no standard assembler. What's
                   11577: worse is that the register allocation not only depends on the processor,
                   11578: but also on the @code{gcc} version and options used.
1.44      crook    11579: 
1.78      anton    11580: The words that Gforth offers encapsulate some system dependences (e.g.,
                   11581: the header structure), so a system-independent assembler may be used in
                   11582: Gforth. If you do not have an assembler, you can compile machine code
                   11583: directly with @code{,} and @code{c,}@footnote{This isn't portable,
                   11584: because these words emit stuff in @i{data} space; it works because
                   11585: Gforth has unified code/data spaces. Assembler isn't likely to be
                   11586: portable anyway.}.
1.21      crook    11587: 
1.44      crook    11588: 
1.78      anton    11589: doc-assembler
                   11590: doc-init-asm
                   11591: doc-code
                   11592: doc-end-code
                   11593: doc-;code
                   11594: doc-flush-icache
1.44      crook    11595: 
1.21      crook    11596: 
1.78      anton    11597: If @code{flush-icache} does not work correctly, @code{code} words
                   11598: etc. will not work (reliably), either.
1.44      crook    11599: 
1.78      anton    11600: The typical usage of these @code{code} words can be shown most easily by
                   11601: analogy to the equivalent high-level defining words:
1.44      crook    11602: 
1.78      anton    11603: @example
                   11604: : foo                              code foo
                   11605:    <high-level Forth words>              <assembler>
                   11606: ;                                  end-code
                   11607:                                 
                   11608: : bar                              : bar
                   11609:    <high-level Forth words>           <high-level Forth words>
                   11610:    CREATE                             CREATE
                   11611:       <high-level Forth words>           <high-level Forth words>
                   11612:    DOES>                              ;code
                   11613:       <high-level Forth words>           <assembler>
                   11614: ;                                  end-code
                   11615: @end example
1.21      crook    11616: 
1.78      anton    11617: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44      crook    11618: 
1.78      anton    11619: @cindex registers of the inner interpreter
                   11620: In the assembly code you will want to refer to the inner interpreter's
                   11621: registers (e.g., the data stack pointer) and you may want to use other
                   11622: registers for temporary storage. Unfortunately, the register allocation
                   11623: is installation-dependent.
1.44      crook    11624: 
1.78      anton    11625: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100     anton    11626: (return stack pointer) may be in different places in @code{gforth} and
                   11627: @code{gforth-fast}, or different installations.  This means that you
                   11628: cannot write a @code{NEXT} routine that works reliably on both versions
                   11629: or different installations; so for doing @code{NEXT}, I recommend
                   11630: jumping to @code{' noop >code-address}, which contains nothing but a
                   11631: @code{NEXT}.
1.21      crook    11632: 
1.78      anton    11633: For general accesses to the inner interpreter's registers, the easiest
                   11634: solution is to use explicit register declarations (@pxref{Explicit Reg
                   11635: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
                   11636: all of the inner interpreter's registers: You have to compile Gforth
                   11637: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
                   11638: the appropriate declarations must be present in the @code{machine.h}
                   11639: file (see @code{mips.h} for an example; you can find a full list of all
                   11640: declarable register symbols with @code{grep register engine.c}). If you
                   11641: give explicit registers to all variables that are declared at the
                   11642: beginning of @code{engine()}, you should be able to use the other
                   11643: caller-saved registers for temporary storage. Alternatively, you can use
                   11644: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
                   11645: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
                   11646: reserve a register (however, this restriction on register allocation may
                   11647: slow Gforth significantly).
1.44      crook    11648: 
1.78      anton    11649: If this solution is not viable (e.g., because @code{gcc} does not allow
                   11650: you to explicitly declare all the registers you need), you have to find
                   11651: out by looking at the code where the inner interpreter's registers
                   11652: reside and which registers can be used for temporary storage. You can
                   11653: get an assembly listing of the engine's code with @code{make engine.s}.
1.44      crook    11654: 
1.78      anton    11655: In any case, it is good practice to abstract your assembly code from the
                   11656: actual register allocation. E.g., if the data stack pointer resides in
                   11657: register @code{$17}, create an alias for this register called @code{sp},
                   11658: and use that in your assembly code.
1.21      crook    11659: 
1.78      anton    11660: @cindex code words, portable
                   11661: Another option for implementing normal and defining words efficiently
                   11662: is to add the desired functionality to the source of Gforth. For normal
                   11663: words you just have to edit @file{primitives} (@pxref{Automatic
                   11664: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
                   11665: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
                   11666: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44      crook    11667: 
1.78      anton    11668: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
                   11669: @subsection Common Assembler
1.44      crook    11670: 
1.78      anton    11671: The assemblers in Gforth generally use a postfix syntax, i.e., the
                   11672: instruction name follows the operands.
1.21      crook    11673: 
1.78      anton    11674: The operands are passed in the usual order (the same that is used in the
                   11675: manual of the architecture).  Since they all are Forth words, they have
                   11676: to be separated by spaces; you can also use Forth words to compute the
                   11677: operands.
1.44      crook    11678: 
1.78      anton    11679: The instruction names usually end with a @code{,}.  This makes it easier
                   11680: to visually separate instructions if you put several of them on one
                   11681: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21      crook    11682: 
1.78      anton    11683: Registers are usually specified by number; e.g., (decimal) @code{11}
                   11684: specifies registers R11 and F11 on the Alpha architecture (which one,
                   11685: depends on the instruction).  The usual names are also available, e.g.,
                   11686: @code{s2} for R11 on Alpha.
1.21      crook    11687: 
1.78      anton    11688: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
                   11689: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
                   11690: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
                   11691: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
                   11692: conditions are specified in a way specific to each assembler.
1.1       anton    11693: 
1.78      anton    11694: Note that the register assignments of the Gforth engine can change
                   11695: between Gforth versions, or even between different compilations of the
                   11696: same Gforth version (e.g., if you use a different GCC version).  So if
                   11697: you want to refer to Gforth's registers (e.g., the stack pointer or
                   11698: TOS), I recommend defining your own words for refering to these
                   11699: registers, and using them later on; then you can easily adapt to a
                   11700: changed register assignment.  The stability of the register assignment
                   11701: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1       anton    11702: 
1.100     anton    11703: The most common use of these registers is to dispatch to the next word
                   11704: (the @code{next} routine).  A portable way to do this is to jump to
                   11705: @code{' noop >code-address} (of course, this is less efficient than
                   11706: integrating the @code{next} code and scheduling it well).
1.1       anton    11707: 
1.96      anton    11708: Another difference between Gforth version is that the top of stack is
                   11709: kept in memory in @code{gforth} and, on most platforms, in a register in
                   11710: @code{gforth-fast}.
                   11711: 
1.78      anton    11712: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
                   11713: @subsection Common Disassembler
1.1       anton    11714: 
1.78      anton    11715: You can disassemble a @code{code} word with @code{see}
                   11716: (@pxref{Debugging}).  You can disassemble a section of memory with
1.1       anton    11717: 
1.78      anton    11718: doc-disasm
1.44      crook    11719: 
1.78      anton    11720: The disassembler generally produces output that can be fed into the
                   11721: assembler (i.e., same syntax, etc.).  It also includes additional
                   11722: information in comments.  In particular, the address of the instruction
                   11723: is given in a comment before the instruction.
1.1       anton    11724: 
1.78      anton    11725: @code{See} may display more or less than the actual code of the word,
                   11726: because the recognition of the end of the code is unreliable.  You can
                   11727: use @code{disasm} if it did not display enough.  It may display more, if
                   11728: the code word is not immediately followed by a named word.  If you have
1.116     anton    11729: something else there, you can follow the word with @code{align latest ,}
1.78      anton    11730: to ensure that the end is recognized.
1.21      crook    11731: 
1.78      anton    11732: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
                   11733: @subsection 386 Assembler
1.44      crook    11734: 
1.78      anton    11735: The 386 assembler included in Gforth was written by Bernd Paysan, it's
                   11736: available under GPL, and originally part of bigFORTH.
1.21      crook    11737: 
1.78      anton    11738: The 386 disassembler included in Gforth was written by Andrew McKewan
                   11739: and is in the public domain.
1.21      crook    11740: 
1.91      anton    11741: The disassembler displays code in an Intel-like prefix syntax.
1.21      crook    11742: 
1.78      anton    11743: The assembler uses a postfix syntax with reversed parameters.
1.1       anton    11744: 
1.78      anton    11745: The assembler includes all instruction of the Athlon, i.e. 486 core
                   11746: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
                   11747: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
                   11748: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1       anton    11749: 
1.78      anton    11750: There are several prefixes to switch between different operation sizes,
                   11751: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
                   11752: double-word accesses. Addressing modes can be switched with @code{.wa}
                   11753: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
                   11754: need a prefix for byte register names (@code{AL} et al).
1.1       anton    11755: 
1.78      anton    11756: For floating point operations, the prefixes are @code{.fs} (IEEE
                   11757: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
                   11758: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21      crook    11759: 
1.78      anton    11760: The MMX opcodes don't have size prefixes, they are spelled out like in
                   11761: the Intel assembler. Instead of move from and to memory, there are
                   11762: PLDQ/PLDD and PSTQ/PSTD.
1.21      crook    11763: 
1.78      anton    11764: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
                   11765: ax.  Immediate values are indicated by postfixing them with @code{#},
1.91      anton    11766: e.g., @code{3 #}.  Here are some examples of addressing modes in various
                   11767: syntaxes:
1.21      crook    11768: 
1.26      crook    11769: @example
1.91      anton    11770: Gforth          Intel (NASM)   AT&T (gas)      Name
                   11771: .w ax           ax             %ax             register (16 bit)
                   11772: ax              eax            %eax            register (32 bit)
                   11773: 3 #             offset 3       $3              immediate
                   11774: 1000 #)         byte ptr 1000  1000            displacement
                   11775: bx )            [ebx]          (%ebx)          base
                   11776: 100 di d)       100[edi]       100(%edi)       base+displacement
                   11777: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
                   11778: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
                   11779: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
                   11780: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
                   11781: @end example
                   11782: 
                   11783: You can use @code{L)} and @code{LI)} instead of @code{D)} and
                   11784: @code{DI)} to enforce 32-bit displacement fields (useful for
                   11785: later patching).
1.21      crook    11786: 
1.78      anton    11787: Some example of instructions are:
1.1       anton    11788: 
                   11789: @example
1.78      anton    11790: ax bx mov             \ move ebx,eax
                   11791: 3 # ax mov            \ mov eax,3
                   11792: 100 di ) ax mov       \ mov eax,100[edi]
                   11793: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
                   11794: .w ax bx mov          \ mov bx,ax
1.1       anton    11795: @end example
                   11796: 
1.78      anton    11797: The following forms are supported for binary instructions:
1.1       anton    11798: 
                   11799: @example
1.78      anton    11800: <reg> <reg> <inst>
                   11801: <n> # <reg> <inst>
                   11802: <mem> <reg> <inst>
                   11803: <reg> <mem> <inst>
1.1       anton    11804: @end example
                   11805: 
1.78      anton    11806: Immediate to memory is not supported.  The shift/rotate syntax is:
1.1       anton    11807: 
1.26      crook    11808: @example
1.78      anton    11809: <reg/mem> 1 # shl \ shortens to shift without immediate
                   11810: <reg/mem> 4 # shl
                   11811: <reg/mem> cl shl
1.26      crook    11812: @end example
1.1       anton    11813: 
1.78      anton    11814: Precede string instructions (@code{movs} etc.) with @code{.b} to get
                   11815: the byte version.
1.1       anton    11816: 
1.78      anton    11817: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
                   11818: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
                   11819: pc < >= <= >}. (Note that most of these words shadow some Forth words
                   11820: when @code{assembler} is in front of @code{forth} in the search path,
                   11821: e.g., in @code{code} words).  Currently the control structure words use
                   11822: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
                   11823: to shuffle them (you can also use @code{swap} etc.).
1.21      crook    11824: 
1.78      anton    11825: Here is an example of a @code{code} word (assumes that the stack pointer
                   11826: is in esi and the TOS is in ebx):
1.21      crook    11827: 
1.26      crook    11828: @example
1.78      anton    11829: code my+ ( n1 n2 -- n )
                   11830:     4 si D) bx add
                   11831:     4 # si add
                   11832:     Next
                   11833: end-code
1.26      crook    11834: @end example
1.21      crook    11835: 
1.78      anton    11836: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
                   11837: @subsection Alpha Assembler
1.21      crook    11838: 
1.78      anton    11839: The Alpha assembler and disassembler were originally written by Bernd
                   11840: Thallner.
1.26      crook    11841: 
1.78      anton    11842: The register names @code{a0}--@code{a5} are not available to avoid
                   11843: shadowing hex numbers.
1.2       jwilke   11844: 
1.78      anton    11845: Immediate forms of arithmetic instructions are distinguished by a
                   11846: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
                   11847: does not count as arithmetic instruction).
1.2       jwilke   11848: 
1.78      anton    11849: You have to specify all operands to an instruction, even those that
                   11850: other assemblers consider optional, e.g., the destination register for
                   11851: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2       jwilke   11852: 
1.78      anton    11853: You can specify conditions for @code{if,} by removing the first @code{b}
                   11854: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2       jwilke   11855: 
1.26      crook    11856: @example
1.78      anton    11857: 11 fgt if, \ if F11>0e
                   11858:   ...
                   11859: endif,
1.26      crook    11860: @end example
1.2       jwilke   11861: 
1.78      anton    11862: @code{fbgt,} gives @code{fgt}.  
                   11863: 
                   11864: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
                   11865: @subsection MIPS assembler
1.2       jwilke   11866: 
1.78      anton    11867: The MIPS assembler was originally written by Christian Pirker.
1.2       jwilke   11868: 
1.78      anton    11869: Currently the assembler and disassembler only cover the MIPS-I
                   11870: architecture (R3000), and don't support FP instructions.
1.2       jwilke   11871: 
1.78      anton    11872: The register names @code{$a0}--@code{$a3} are not available to avoid
                   11873: shadowing hex numbers.
1.2       jwilke   11874: 
1.78      anton    11875: Because there is no way to distinguish registers from immediate values,
                   11876: you have to explicitly use the immediate forms of instructions, i.e.,
                   11877: @code{addiu,}, not just @code{addu,} (@command{as} does this
                   11878: implicitly).
1.2       jwilke   11879: 
1.78      anton    11880: If the architecture manual specifies several formats for the instruction
                   11881: (e.g., for @code{jalr,}), you usually have to use the one with more
                   11882: arguments (i.e., two for @code{jalr,}).  When in doubt, see
                   11883: @code{arch/mips/testasm.fs} for an example of correct use.
1.2       jwilke   11884: 
1.78      anton    11885: Branches and jumps in the MIPS architecture have a delay slot.  You have
                   11886: to fill it yourself (the simplest way is to use @code{nop,}), the
                   11887: assembler does not do it for you (unlike @command{as}).  Even
                   11888: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
                   11889: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
                   11890: and @code{then,} just specify branch targets, they are not affected.
1.2       jwilke   11891: 
1.78      anton    11892: Note that you must not put branches, jumps, or @code{li,} into the delay
                   11893: slot: @code{li,} may expand to several instructions, and control flow
                   11894: instructions may not be put into the branch delay slot in any case.
1.2       jwilke   11895: 
1.78      anton    11896: For branches the argument specifying the target is a relative address;
                   11897: You have to add the address of the delay slot to get the absolute
                   11898: address.
1.1       anton    11899: 
1.78      anton    11900: The MIPS architecture also has load delay slots and restrictions on
                   11901: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
                   11902: yourself to satisfy these restrictions, the assembler does not do it for
                   11903: you.
1.1       anton    11904: 
1.78      anton    11905: You can specify the conditions for @code{if,} etc. by taking a
                   11906: conditional branch and leaving away the @code{b} at the start and the
                   11907: @code{,} at the end.  E.g.,
1.1       anton    11908: 
1.26      crook    11909: @example
1.78      anton    11910: 4 5 eq if,
                   11911:   ... \ do something if $4 equals $5
                   11912: then,
1.26      crook    11913: @end example
1.1       anton    11914: 
1.78      anton    11915: @node Other assemblers,  , MIPS assembler, Assembler and Code Words
                   11916: @subsection Other assemblers
                   11917: 
                   11918: If you want to contribute another assembler/disassembler, please contact
1.103     anton    11919: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
                   11920: an assembler already.  If you are writing them from scratch, please use
                   11921: a similar syntax style as the one we use (i.e., postfix, commas at the
                   11922: end of the instruction names, @pxref{Common Assembler}); make the output
                   11923: of the disassembler be valid input for the assembler, and keep the style
1.78      anton    11924: similar to the style we used.
                   11925: 
                   11926: Hints on implementation: The most important part is to have a good test
                   11927: suite that contains all instructions.  Once you have that, the rest is
                   11928: easy.  For actual coding you can take a look at
                   11929: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
                   11930: the assembler and disassembler, avoiding redundancy and some potential
                   11931: bugs.  You can also look at that file (and @pxref{Advanced does> usage
                   11932: example}) to get ideas how to factor a disassembler.
                   11933: 
                   11934: Start with the disassembler, because it's easier to reuse data from the
                   11935: disassembler for the assembler than the other way round.
1.1       anton    11936: 
1.78      anton    11937: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
                   11938: how simple it can be.
1.1       anton    11939: 
1.78      anton    11940: @c -------------------------------------------------------------
                   11941: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
                   11942: @section Threading Words
                   11943: @cindex threading words
1.1       anton    11944: 
1.78      anton    11945: @cindex code address
                   11946: These words provide access to code addresses and other threading stuff
                   11947: in Gforth (and, possibly, other interpretive Forths). It more or less
                   11948: abstracts away the differences between direct and indirect threading
                   11949: (and, for direct threading, the machine dependences). However, at
                   11950: present this wordset is still incomplete. It is also pretty low-level;
                   11951: some day it will hopefully be made unnecessary by an internals wordset
                   11952: that abstracts implementation details away completely.
1.1       anton    11953: 
1.78      anton    11954: The terminology used here stems from indirect threaded Forth systems; in
                   11955: such a system, the XT of a word is represented by the CFA (code field
                   11956: address) of a word; the CFA points to a cell that contains the code
                   11957: address.  The code address is the address of some machine code that
                   11958: performs the run-time action of invoking the word (e.g., the
                   11959: @code{dovar:} routine pushes the address of the body of the word (a
                   11960: variable) on the stack
                   11961: ).
1.1       anton    11962: 
1.78      anton    11963: @cindex code address
                   11964: @cindex code field address
                   11965: In an indirect threaded Forth, you can get the code address of @i{name}
                   11966: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
                   11967: >code-address}, independent of the threading method.
1.1       anton    11968: 
1.78      anton    11969: doc-threading-method
                   11970: doc->code-address
                   11971: doc-code-address!
1.1       anton    11972: 
1.78      anton    11973: @cindex @code{does>}-handler
                   11974: @cindex @code{does>}-code
                   11975: For a word defined with @code{DOES>}, the code address usually points to
                   11976: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
                   11977: routine (in Gforth on some platforms, it can also point to the dodoes
                   11978: routine itself).  What you are typically interested in, though, is
                   11979: whether a word is a @code{DOES>}-defined word, and what Forth code it
                   11980: executes; @code{>does-code} tells you that.
1.1       anton    11981: 
1.78      anton    11982: doc->does-code
1.1       anton    11983: 
1.78      anton    11984: To create a @code{DOES>}-defined word with the following basic words,
                   11985: you have to set up a @code{DOES>}-handler with @code{does-handler!};
                   11986: @code{/does-handler} aus behind you have to place your executable Forth
                   11987: code.  Finally you have to create a word and modify its behaviour with
                   11988: @code{does-handler!}.
1.1       anton    11989: 
1.78      anton    11990: doc-does-code!
                   11991: doc-does-handler!
                   11992: doc-/does-handler
1.1       anton    11993: 
1.78      anton    11994: The code addresses produced by various defining words are produced by
                   11995: the following words:
1.1       anton    11996: 
1.78      anton    11997: doc-docol:
                   11998: doc-docon:
                   11999: doc-dovar:
                   12000: doc-douser:
                   12001: doc-dodefer:
                   12002: doc-dofield:
1.1       anton    12003: 
1.99      anton    12004: @cindex definer
                   12005: The following two words generalize @code{>code-address},
                   12006: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
                   12007: 
                   12008: doc->definer
                   12009: doc-definer!
                   12010: 
1.26      crook    12011: @c -------------------------------------------------------------
1.78      anton    12012: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21      crook    12013: @section Passing Commands to the Operating System
                   12014: @cindex operating system - passing commands
                   12015: @cindex shell commands
                   12016: 
                   12017: Gforth allows you to pass an arbitrary string to the host operating
                   12018: system shell (if such a thing exists) for execution.
                   12019: 
1.44      crook    12020: 
1.21      crook    12021: doc-sh
                   12022: doc-system
                   12023: doc-$?
1.23      crook    12024: doc-getenv
1.21      crook    12025: 
1.44      crook    12026: 
1.26      crook    12027: @c -------------------------------------------------------------
1.47      crook    12028: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
                   12029: @section Keeping track of Time
                   12030: @cindex time-related words
                   12031: 
                   12032: doc-ms
                   12033: doc-time&date
1.79      anton    12034: doc-utime
                   12035: doc-cputime
1.47      crook    12036: 
                   12037: 
                   12038: @c -------------------------------------------------------------
                   12039: @node Miscellaneous Words,  , Keeping track of Time, Words
1.21      crook    12040: @section Miscellaneous Words
                   12041: @cindex miscellaneous words
                   12042: 
1.29      crook    12043: @comment TODO find homes for these
                   12044: 
1.26      crook    12045: These section lists the ANS Forth words that are not documented
1.21      crook    12046: elsewhere in this manual. Ultimately, they all need proper homes.
                   12047: 
1.68      anton    12048: doc-quit
1.44      crook    12049: 
1.26      crook    12050: The following ANS Forth words are not currently supported by Gforth 
1.27      crook    12051: (@pxref{ANS conformance}):
1.21      crook    12052: 
                   12053: @code{EDITOR} 
                   12054: @code{EMIT?} 
                   12055: @code{FORGET} 
                   12056: 
1.24      anton    12057: @c ******************************************************************
                   12058: @node Error messages, Tools, Words, Top
                   12059: @chapter Error messages
                   12060: @cindex error messages
                   12061: @cindex backtrace
                   12062: 
                   12063: A typical Gforth error message looks like this:
                   12064: 
                   12065: @example
1.86      anton    12066: in file included from \evaluated string/:-1
1.24      anton    12067: in file included from ./yyy.fs:1
                   12068: ./xxx.fs:4: Invalid memory address
                   12069: bar
                   12070: ^^^
1.79      anton    12071: Backtrace:
1.25      anton    12072: $400E664C @@
                   12073: $400E6664 foo
1.24      anton    12074: @end example
                   12075: 
                   12076: The message identifying the error is @code{Invalid memory address}.  The
                   12077: error happened when text-interpreting line 4 of the file
                   12078: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
                   12079: word on the line where the error happened, is pointed out (with
                   12080: @code{^^^}).
                   12081: 
                   12082: The file containing the error was included in line 1 of @file{./yyy.fs},
                   12083: and @file{yyy.fs} was included from a non-file (in this case, by giving
                   12084: @file{yyy.fs} as command-line parameter to Gforth).
                   12085: 
                   12086: At the end of the error message you find a return stack dump that can be
                   12087: interpreted as a backtrace (possibly empty). On top you find the top of
                   12088: the return stack when the @code{throw} happened, and at the bottom you
                   12089: find the return stack entry just above the return stack of the topmost
                   12090: text interpreter.
                   12091: 
                   12092: To the right of most return stack entries you see a guess for the word
                   12093: that pushed that return stack entry as its return address. This gives a
                   12094: backtrace. In our case we see that @code{bar} called @code{foo}, and
                   12095: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
                   12096: address} exception).
                   12097: 
                   12098: Note that the backtrace is not perfect: We don't know which return stack
                   12099: entries are return addresses (so we may get false positives); and in
                   12100: some cases (e.g., for @code{abort"}) we cannot determine from the return
                   12101: address the word that pushed the return address, so for some return
                   12102: addresses you see no names in the return stack dump.
1.25      anton    12103: 
                   12104: @cindex @code{catch} and backtraces
                   12105: The return stack dump represents the return stack at the time when a
                   12106: specific @code{throw} was executed.  In programs that make use of
                   12107: @code{catch}, it is not necessarily clear which @code{throw} should be
                   12108: used for the return stack dump (e.g., consider one @code{throw} that
                   12109: indicates an error, which is caught, and during recovery another error
1.42      anton    12110: happens; which @code{throw} should be used for the stack dump?).  Gforth
1.25      anton    12111: presents the return stack dump for the first @code{throw} after the last
                   12112: executed (not returned-to) @code{catch}; this works well in the usual
                   12113: case.
                   12114: 
                   12115: @cindex @code{gforth-fast} and backtraces
                   12116: @cindex @code{gforth-fast}, difference from @code{gforth}
                   12117: @cindex backtraces with @code{gforth-fast}
                   12118: @cindex return stack dump with @code{gforth-fast}
1.79      anton    12119: @code{Gforth} is able to do a return stack dump for throws generated
1.25      anton    12120: from primitives (e.g., invalid memory address, stack empty etc.);
                   12121: @code{gforth-fast} is only able to do a return stack dump from a
1.96      anton    12122: directly called @code{throw} (including @code{abort} etc.).  Given an
1.30      anton    12123: exception caused by a primitive in @code{gforth-fast}, you will
                   12124: typically see no return stack dump at all; however, if the exception is
                   12125: caught by @code{catch} (e.g., for restoring some state), and then
                   12126: @code{throw}n again, the return stack dump will be for the first such
                   12127: @code{throw}.
1.2       jwilke   12128: 
1.5       anton    12129: @c ******************************************************************
1.24      anton    12130: @node Tools, ANS conformance, Error messages, Top
1.1       anton    12131: @chapter Tools
                   12132: 
                   12133: @menu
                   12134: * ANS Report::                  Report the words used, sorted by wordset.
                   12135: @end menu
                   12136: 
                   12137: See also @ref{Emacs and Gforth}.
                   12138: 
                   12139: @node ANS Report,  , Tools, Tools
                   12140: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   12141: @cindex @file{ans-report.fs}
                   12142: @cindex report the words used in your program
                   12143: @cindex words used in your program
                   12144: 
                   12145: If you want to label a Forth program as ANS Forth Program, you must
                   12146: document which wordsets the program uses; for extension wordsets, it is
                   12147: helpful to list the words the program requires from these wordsets
                   12148: (because Forth systems are allowed to provide only some words of them).
                   12149: 
                   12150: The @file{ans-report.fs} tool makes it easy for you to determine which
                   12151: words from which wordset and which non-ANS words your application
                   12152: uses. You simply have to include @file{ans-report.fs} before loading the
                   12153: program you want to check. After loading your program, you can get the
                   12154: report with @code{print-ans-report}. A typical use is to run this as
                   12155: batch job like this:
                   12156: @example
                   12157: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   12158: @end example
                   12159: 
                   12160: The output looks like this (for @file{compat/control.fs}):
                   12161: @example
                   12162: The program uses the following words
                   12163: from CORE :
                   12164: : POSTPONE THEN ; immediate ?dup IF 0= 
                   12165: from BLOCK-EXT :
                   12166: \ 
                   12167: from FILE :
                   12168: ( 
                   12169: @end example
                   12170: 
                   12171: @subsection Caveats
                   12172: 
                   12173: Note that @file{ans-report.fs} just checks which words are used, not whether
                   12174: they are used in an ANS Forth conforming way!
                   12175: 
                   12176: Some words are defined in several wordsets in the
                   12177: standard. @file{ans-report.fs} reports them for only one of the
                   12178: wordsets, and not necessarily the one you expect. It depends on usage
                   12179: which wordset is the right one to specify. E.g., if you only use the
                   12180: compilation semantics of @code{S"}, it is a Core word; if you also use
                   12181: its interpretation semantics, it is a File word.
                   12182: 
                   12183: @c ******************************************************************
1.65      anton    12184: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1       anton    12185: @chapter ANS conformance
                   12186: @cindex ANS conformance of Gforth
                   12187: 
                   12188: To the best of our knowledge, Gforth is an
                   12189: 
                   12190: ANS Forth System
                   12191: @itemize @bullet
                   12192: @item providing the Core Extensions word set
                   12193: @item providing the Block word set
                   12194: @item providing the Block Extensions word set
                   12195: @item providing the Double-Number word set
                   12196: @item providing the Double-Number Extensions word set
                   12197: @item providing the Exception word set
                   12198: @item providing the Exception Extensions word set
                   12199: @item providing the Facility word set
1.40      anton    12200: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1       anton    12201: @item providing the File Access word set
                   12202: @item providing the File Access Extensions word set
                   12203: @item providing the Floating-Point word set
                   12204: @item providing the Floating-Point Extensions word set
                   12205: @item providing the Locals word set
                   12206: @item providing the Locals Extensions word set
                   12207: @item providing the Memory-Allocation word set
                   12208: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   12209: @item providing the Programming-Tools word set
                   12210: @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
                   12211: @item providing the Search-Order word set
                   12212: @item providing the Search-Order Extensions word set
                   12213: @item providing the String word set
                   12214: @item providing the String Extensions word set (another easy one)
                   12215: @end itemize
                   12216: 
1.118     anton    12217: Gforth has the following environmental restrictions:
                   12218: 
                   12219: @cindex environmental restrictions
                   12220: @itemize @bullet
                   12221: @item
                   12222: While processing the OS command line, if an exception is not caught,
                   12223: Gforth exits with a non-zero exit code instyead of performing QUIT.
                   12224: 
                   12225: @item
                   12226: When an @code{throw} is performed after a @code{query}, Gforth does not
                   12227: allways restore the input source specification in effect at the
                   12228: corresponding catch.
                   12229: 
                   12230: @end itemize
                   12231: 
                   12232: 
1.1       anton    12233: @cindex system documentation
                   12234: In addition, ANS Forth systems are required to document certain
                   12235: implementation choices. This chapter tries to meet these
                   12236: requirements. In many cases it gives a way to ask the system for the
                   12237: information instead of providing the information directly, in
                   12238: particular, if the information depends on the processor, the operating
                   12239: system or the installation options chosen, or if they are likely to
                   12240: change during the maintenance of Gforth.
                   12241: 
                   12242: @comment The framework for the rest has been taken from pfe.
                   12243: 
                   12244: @menu
                   12245: * The Core Words::              
                   12246: * The optional Block word set::  
                   12247: * The optional Double Number word set::  
                   12248: * The optional Exception word set::  
                   12249: * The optional Facility word set::  
                   12250: * The optional File-Access word set::  
                   12251: * The optional Floating-Point word set::  
                   12252: * The optional Locals word set::  
                   12253: * The optional Memory-Allocation word set::  
                   12254: * The optional Programming-Tools word set::  
                   12255: * The optional Search-Order word set::  
                   12256: @end menu
                   12257: 
                   12258: 
                   12259: @c =====================================================================
                   12260: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   12261: @comment  node-name,  next,  previous,  up
                   12262: @section The Core Words
                   12263: @c =====================================================================
                   12264: @cindex core words, system documentation
                   12265: @cindex system documentation, core words
                   12266: 
                   12267: @menu
                   12268: * core-idef::                   Implementation Defined Options                   
                   12269: * core-ambcond::                Ambiguous Conditions                
                   12270: * core-other::                  Other System Documentation                  
                   12271: @end menu
                   12272: 
                   12273: @c ---------------------------------------------------------------------
                   12274: @node core-idef, core-ambcond, The Core Words, The Core Words
                   12275: @subsection Implementation Defined Options
                   12276: @c ---------------------------------------------------------------------
                   12277: @cindex core words, implementation-defined options
                   12278: @cindex implementation-defined options, core words
                   12279: 
                   12280: 
                   12281: @table @i
                   12282: @item (Cell) aligned addresses:
                   12283: @cindex cell-aligned addresses
                   12284: @cindex aligned addresses
                   12285: processor-dependent. Gforth's alignment words perform natural alignment
                   12286: (e.g., an address aligned for a datum of size 8 is divisible by
                   12287: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   12288: 
                   12289: @item @code{EMIT} and non-graphic characters:
                   12290: @cindex @code{EMIT} and non-graphic characters
                   12291: @cindex non-graphic characters and @code{EMIT}
                   12292: The character is output using the C library function (actually, macro)
                   12293: @code{putc}.
                   12294: 
                   12295: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   12296: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   12297: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   12298: @cindex @code{ACCEPT}, editing
                   12299: @cindex @code{EXPECT}, editing
                   12300: This is modeled on the GNU readline library (@pxref{Readline
                   12301: Interaction, , Command Line Editing, readline, The GNU Readline
                   12302: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   12303: producing a full word completion every time you type it (instead of
1.28      crook    12304: producing the common prefix of all completions). @xref{Command-line editing}.
1.1       anton    12305: 
                   12306: @item character set:
                   12307: @cindex character set
                   12308: The character set of your computer and display device. Gforth is
                   12309: 8-bit-clean (but some other component in your system may make trouble).
                   12310: 
                   12311: @item Character-aligned address requirements:
                   12312: @cindex character-aligned address requirements
                   12313: installation-dependent. Currently a character is represented by a C
                   12314: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   12315: (Comments on that requested).
                   12316: 
                   12317: @item character-set extensions and matching of names:
                   12318: @cindex character-set extensions and matching of names
1.26      crook    12319: @cindex case-sensitivity for name lookup
                   12320: @cindex name lookup, case-sensitivity
                   12321: @cindex locale and case-sensitivity
1.21      crook    12322: Any character except the ASCII NUL character can be used in a
1.1       anton    12323: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47      crook    12324: matching is performed using the C library function @code{strncasecmp}, whose
1.1       anton    12325: function is probably influenced by the locale. E.g., the @code{C} locale
                   12326: does not know about accents and umlauts, so they are matched
                   12327: case-sensitively in that locale. For portability reasons it is best to
                   12328: write programs such that they work in the @code{C} locale. Then one can
                   12329: use libraries written by a Polish programmer (who might use words
                   12330: containing ISO Latin-2 encoded characters) and by a French programmer
                   12331: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   12332: funny results for some of the words (which ones, depends on the font you
                   12333: are using)). Also, the locale you prefer may not be available in other
                   12334: operating systems. Hopefully, Unicode will solve these problems one day.
                   12335: 
                   12336: @item conditions under which control characters match a space delimiter:
                   12337: @cindex space delimiters
                   12338: @cindex control characters as delimiters
1.117     anton    12339: If @code{word} is called with the space character as a delimiter, all
1.1       anton    12340: white-space characters (as identified by the C macro @code{isspace()})
1.117     anton    12341: are delimiters. @code{Parse}, on the other hand, treats space like other
                   12342: delimiters.  @code{Parse-word}, which is used by the outer
1.1       anton    12343: interpreter (aka text interpreter) by default, treats all white-space
                   12344: characters as delimiters.
                   12345: 
1.26      crook    12346: @item format of the control-flow stack:
                   12347: @cindex control-flow stack, format
                   12348: The data stack is used as control-flow stack. The size of a control-flow
1.1       anton    12349: stack item in cells is given by the constant @code{cs-item-size}. At the
                   12350: time of this writing, an item consists of a (pointer to a) locals list
                   12351: (third), an address in the code (second), and a tag for identifying the
                   12352: item (TOS). The following tags are used: @code{defstart},
                   12353: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   12354: @code{scopestart}.
                   12355: 
                   12356: @item conversion of digits > 35
                   12357: @cindex digits > 35
                   12358: The characters @code{[\]^_'} are the digits with the decimal value
                   12359: 36@minus{}41. There is no way to input many of the larger digits.
                   12360: 
                   12361: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   12362: @cindex @code{EXPECT}, display after end of input
                   12363: @cindex @code{ACCEPT}, display after end of input
                   12364: The cursor is moved to the end of the entered string. If the input is
                   12365: terminated using the @kbd{Return} key, a space is typed.
                   12366: 
                   12367: @item exception abort sequence of @code{ABORT"}:
                   12368: @cindex exception abort sequence of @code{ABORT"}
                   12369: @cindex @code{ABORT"}, exception abort sequence
                   12370: The error string is stored into the variable @code{"error} and a
                   12371: @code{-2 throw} is performed.
                   12372: 
                   12373: @item input line terminator:
                   12374: @cindex input line terminator
                   12375: @cindex line terminator on input
1.26      crook    12376: @cindex newline character on input
1.1       anton    12377: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   12378: lines. One of these characters is typically produced when you type the
                   12379: @kbd{Enter} or @kbd{Return} key.
                   12380: 
                   12381: @item maximum size of a counted string:
                   12382: @cindex maximum size of a counted string
                   12383: @cindex counted string, maximum size
                   12384: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79      anton    12385: on all platforms, but this may change.
1.1       anton    12386: 
                   12387: @item maximum size of a parsed string:
                   12388: @cindex maximum size of a parsed string
                   12389: @cindex parsed string, maximum size
                   12390: Given by the constant @code{/line}. Currently 255 characters.
                   12391: 
                   12392: @item maximum size of a definition name, in characters:
                   12393: @cindex maximum size of a definition name, in characters
                   12394: @cindex name, maximum length
1.113     anton    12395: MAXU/8
1.1       anton    12396: 
                   12397: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   12398: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   12399: @cindex @code{ENVIRONMENT?} string length, maximum
1.113     anton    12400: MAXU/8
1.1       anton    12401: 
                   12402: @item method of selecting the user input device:
                   12403: @cindex user input device, method of selecting
                   12404: The user input device is the standard input. There is currently no way to
                   12405: change it from within Gforth. However, the input can typically be
                   12406: redirected in the command line that starts Gforth.
                   12407: 
                   12408: @item method of selecting the user output device:
                   12409: @cindex user output device, method of selecting
                   12410: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    12411: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   12412: output when the user output device is a terminal, otherwise the output
                   12413: is buffered.
1.1       anton    12414: 
                   12415: @item methods of dictionary compilation:
                   12416: What are we expected to document here?
                   12417: 
                   12418: @item number of bits in one address unit:
                   12419: @cindex number of bits in one address unit
                   12420: @cindex address unit, size in bits
                   12421: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79      anton    12422: platforms.
1.1       anton    12423: 
                   12424: @item number representation and arithmetic:
                   12425: @cindex number representation and arithmetic
1.79      anton    12426: Processor-dependent. Binary two's complement on all current platforms.
1.1       anton    12427: 
                   12428: @item ranges for integer types:
                   12429: @cindex ranges for integer types
                   12430: @cindex integer types, ranges
                   12431: Installation-dependent. Make environmental queries for @code{MAX-N},
                   12432: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   12433: unsigned (and positive) types is 0. The lower bound for signed types on
                   12434: two's complement and one's complement machines machines can be computed
                   12435: by adding 1 to the upper bound.
                   12436: 
                   12437: @item read-only data space regions:
                   12438: @cindex read-only data space regions
                   12439: @cindex data-space, read-only regions
                   12440: The whole Forth data space is writable.
                   12441: 
                   12442: @item size of buffer at @code{WORD}:
                   12443: @cindex size of buffer at @code{WORD}
                   12444: @cindex @code{WORD} buffer size
                   12445: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   12446: shared with the pictured numeric output string. If overwriting
                   12447: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   12448: space, although only as much can be sensibly used as fits in a counted
                   12449: string.
                   12450: 
                   12451: @item size of one cell in address units:
                   12452: @cindex cell size
                   12453: @code{1 cells .}.
                   12454: 
                   12455: @item size of one character in address units:
                   12456: @cindex char size
1.79      anton    12457: @code{1 chars .}. 1 on all current platforms.
1.1       anton    12458: 
                   12459: @item size of the keyboard terminal buffer:
                   12460: @cindex size of the keyboard terminal buffer
                   12461: @cindex terminal buffer, size
                   12462: Varies. You can determine the size at a specific time using @code{lp@@
                   12463: tib - .}. It is shared with the locals stack and TIBs of files that
                   12464: include the current file. You can change the amount of space for TIBs
                   12465: and locals stack at Gforth startup with the command line option
                   12466: @code{-l}.
                   12467: 
                   12468: @item size of the pictured numeric output buffer:
                   12469: @cindex size of the pictured numeric output buffer
                   12470: @cindex pictured numeric output buffer, size
                   12471: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   12472: shared with @code{WORD}.
                   12473: 
                   12474: @item size of the scratch area returned by @code{PAD}:
                   12475: @cindex size of the scratch area returned by @code{PAD}
                   12476: @cindex @code{PAD} size
                   12477: The remainder of dictionary space. @code{unused pad here - - .}.
                   12478: 
                   12479: @item system case-sensitivity characteristics:
                   12480: @cindex case-sensitivity characteristics
1.26      crook    12481: Dictionary searches are case-insensitive (except in
1.1       anton    12482: @code{TABLE}s). However, as explained above under @i{character-set
                   12483: extensions}, the matching for non-ASCII characters is determined by the
                   12484: locale you are using. In the default @code{C} locale all non-ASCII
                   12485: characters are matched case-sensitively.
                   12486: 
                   12487: @item system prompt:
                   12488: @cindex system prompt
                   12489: @cindex prompt
                   12490: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   12491: 
                   12492: @item division rounding:
                   12493: @cindex division rounding
                   12494: installation dependent. @code{s" floored" environment? drop .}. We leave
                   12495: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
                   12496: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
                   12497: 
                   12498: @item values of @code{STATE} when true:
                   12499: @cindex @code{STATE} values
                   12500: -1.
                   12501: 
                   12502: @item values returned after arithmetic overflow:
                   12503: On two's complement machines, arithmetic is performed modulo
                   12504: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   12505: arithmetic (with appropriate mapping for signed types). Division by zero
                   12506: typically results in a @code{-55 throw} (Floating-point unidentified
1.80      anton    12507: fault) or @code{-10 throw} (divide by zero).
1.1       anton    12508: 
                   12509: @item whether the current definition can be found after @t{DOES>}:
                   12510: @cindex @t{DOES>}, visibility of current definition
                   12511: No.
                   12512: 
                   12513: @end table
                   12514: 
                   12515: @c ---------------------------------------------------------------------
                   12516: @node core-ambcond, core-other, core-idef, The Core Words
                   12517: @subsection Ambiguous conditions
                   12518: @c ---------------------------------------------------------------------
                   12519: @cindex core words, ambiguous conditions
                   12520: @cindex ambiguous conditions, core words
                   12521: 
                   12522: @table @i
                   12523: 
                   12524: @item a name is neither a word nor a number:
                   12525: @cindex name not found
1.26      crook    12526: @cindex undefined word
1.80      anton    12527: @code{-13 throw} (Undefined word).
1.1       anton    12528: 
                   12529: @item a definition name exceeds the maximum length allowed:
1.26      crook    12530: @cindex word name too long
1.1       anton    12531: @code{-19 throw} (Word name too long)
                   12532: 
                   12533: @item addressing a region not inside the various data spaces of the forth system:
                   12534: @cindex Invalid memory address
1.32      anton    12535: The stacks, code space and header space are accessible. Machine code space is
1.1       anton    12536: typically readable. Accessing other addresses gives results dependent on
                   12537: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   12538: address).
                   12539: 
                   12540: @item argument type incompatible with parameter:
1.26      crook    12541: @cindex argument type mismatch
1.1       anton    12542: This is usually not caught. Some words perform checks, e.g., the control
                   12543: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   12544: mismatch).
                   12545: 
                   12546: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   12547: @cindex Interpreting a compile-only word, for @code{'} etc.
                   12548: @cindex execution token of words with undefined execution semantics
                   12549: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   12550: get an execution token for @code{compile-only-error} (which performs a
                   12551: @code{-14 throw} when executed).
                   12552: 
                   12553: @item dividing by zero:
                   12554: @cindex dividing by zero
                   12555: @cindex floating point unidentified fault, integer division
1.80      anton    12556: On some platforms, this produces a @code{-10 throw} (Division by
1.24      anton    12557: zero); on other systems, this typically results in a @code{-55 throw}
                   12558: (Floating-point unidentified fault).
1.1       anton    12559: 
                   12560: @item insufficient data stack or return stack space:
                   12561: @cindex insufficient data stack or return stack space
                   12562: @cindex stack overflow
1.26      crook    12563: @cindex address alignment exception, stack overflow
1.1       anton    12564: @cindex Invalid memory address, stack overflow
                   12565: Depending on the operating system, the installation, and the invocation
                   12566: of Gforth, this is either checked by the memory management hardware, or
1.24      anton    12567: it is not checked. If it is checked, you typically get a @code{-3 throw}
                   12568: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
                   12569: throw} (Invalid memory address) (depending on the platform and how you
                   12570: achieved the overflow) as soon as the overflow happens. If it is not
                   12571: checked, overflows typically result in mysterious illegal memory
                   12572: accesses, producing @code{-9 throw} (Invalid memory address) or
                   12573: @code{-23 throw} (Address alignment exception); they might also destroy
                   12574: the internal data structure of @code{ALLOCATE} and friends, resulting in
                   12575: various errors in these words.
1.1       anton    12576: 
                   12577: @item insufficient space for loop control parameters:
                   12578: @cindex insufficient space for loop control parameters
1.80      anton    12579: Like other return stack overflows.
1.1       anton    12580: 
                   12581: @item insufficient space in the dictionary:
                   12582: @cindex insufficient space in the dictionary
                   12583: @cindex dictionary overflow
1.12      anton    12584: If you try to allot (either directly with @code{allot}, or indirectly
                   12585: with @code{,}, @code{create} etc.) more memory than available in the
                   12586: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   12587: to access memory beyond the end of the dictionary, the results are
                   12588: similar to stack overflows.
1.1       anton    12589: 
                   12590: @item interpreting a word with undefined interpretation semantics:
                   12591: @cindex interpreting a word with undefined interpretation semantics
                   12592: @cindex Interpreting a compile-only word
                   12593: For some words, we have defined interpretation semantics. For the
                   12594: others: @code{-14 throw} (Interpreting a compile-only word).
                   12595: 
                   12596: @item modifying the contents of the input buffer or a string literal:
                   12597: @cindex modifying the contents of the input buffer or a string literal
                   12598: These are located in writable memory and can be modified.
                   12599: 
                   12600: @item overflow of the pictured numeric output string:
                   12601: @cindex overflow of the pictured numeric output string
                   12602: @cindex pictured numeric output string, overflow
1.24      anton    12603: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1       anton    12604: 
                   12605: @item parsed string overflow:
                   12606: @cindex parsed string overflow
                   12607: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   12608: 
                   12609: @item producing a result out of range:
                   12610: @cindex result out of range
                   12611: On two's complement machines, arithmetic is performed modulo
                   12612: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   12613: arithmetic (with appropriate mapping for signed types). Division by zero
1.24      anton    12614: typically results in a @code{-10 throw} (divide by zero) or @code{-55
                   12615: throw} (floating point unidentified fault). @code{convert} and
                   12616: @code{>number} currently overflow silently.
1.1       anton    12617: 
                   12618: @item reading from an empty data or return stack:
                   12619: @cindex stack empty
                   12620: @cindex stack underflow
1.24      anton    12621: @cindex return stack underflow
1.1       anton    12622: The data stack is checked by the outer (aka text) interpreter after
                   12623: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   12624: underflow) is performed. Apart from that, stacks may be checked or not,
1.24      anton    12625: depending on operating system, installation, and invocation. If they are
                   12626: caught by a check, they typically result in @code{-4 throw} (Stack
                   12627: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
                   12628: (Invalid memory address), depending on the platform and which stack
                   12629: underflows and by how much. Note that even if the system uses checking
                   12630: (through the MMU), your program may have to underflow by a significant
                   12631: number of stack items to trigger the reaction (the reason for this is
                   12632: that the MMU, and therefore the checking, works with a page-size
                   12633: granularity).  If there is no checking, the symptoms resulting from an
                   12634: underflow are similar to those from an overflow.  Unbalanced return
1.80      anton    12635: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24      anton    12636: (Invalid memory address) and Illegal Instruction (typically @code{-260
                   12637: throw}).
1.1       anton    12638: 
                   12639: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   12640: @cindex unexpected end of the input buffer
                   12641: @cindex zero-length string as a name
                   12642: @cindex Attempt to use zero-length string as a name
                   12643: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   12644: use zero-length string as a name). Words like @code{'} probably will not
                   12645: find what they search. Note that it is possible to create zero-length
                   12646: names with @code{nextname} (should it not?).
                   12647: 
                   12648: @item @code{>IN} greater than input buffer:
                   12649: @cindex @code{>IN} greater than input buffer
                   12650: The next invocation of a parsing word returns a string with length 0.
                   12651: 
                   12652: @item @code{RECURSE} appears after @code{DOES>}:
                   12653: @cindex @code{RECURSE} appears after @code{DOES>}
                   12654: Compiles a recursive call to the defining word, not to the defined word.
                   12655: 
                   12656: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   12657: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26      crook    12658: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1       anton    12659: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   12660: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   12661: the end of the file was reached), its source-id may be
                   12662: reused. Therefore, restoring an input source specification referencing a
                   12663: closed file may lead to unpredictable results instead of a @code{-12
                   12664: THROW}.
                   12665: 
                   12666: In the future, Gforth may be able to restore input source specifications
                   12667: from other than the current input source.
                   12668: 
                   12669: @item data space containing definitions gets de-allocated:
                   12670: @cindex data space containing definitions gets de-allocated
                   12671: Deallocation with @code{allot} is not checked. This typically results in
                   12672: memory access faults or execution of illegal instructions.
                   12673: 
                   12674: @item data space read/write with incorrect alignment:
                   12675: @cindex data space read/write with incorrect alignment
                   12676: @cindex alignment faults
1.26      crook    12677: @cindex address alignment exception
1.1       anton    12678: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    12679: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    12680: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   12681: (Invalid memory address). There are reportedly some processors with
1.12      anton    12682: alignment restrictions that do not report violations.
1.1       anton    12683: 
                   12684: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   12685: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   12686: Like other alignment errors.
                   12687: 
                   12688: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   12689: Like other stack underflows.
                   12690: 
                   12691: @item loop control parameters not available:
                   12692: @cindex loop control parameters not available
                   12693: Not checked. The counted loop words simply assume that the top of return
                   12694: stack items are loop control parameters and behave accordingly.
                   12695: 
                   12696: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   12697: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   12698: @cindex last word was headerless
                   12699: @code{abort" last word was headerless"}.
                   12700: 
                   12701: @item name not defined by @code{VALUE} used by @code{TO}:
                   12702: @cindex name not defined by @code{VALUE} used by @code{TO}
                   12703: @cindex @code{TO} on non-@code{VALUE}s
                   12704: @cindex Invalid name argument, @code{TO}
                   12705: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   12706: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   12707: 
                   12708: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   12709: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26      crook    12710: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1       anton    12711: @code{-13 throw} (Undefined word)
                   12712: 
                   12713: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   12714: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   12715: Gforth behaves as if they were of the same type. I.e., you can predict
                   12716: the behaviour by interpreting all parameters as, e.g., signed.
                   12717: 
                   12718: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   12719: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   12720: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   12721: compilation semantics of @code{TO}.
                   12722: 
                   12723: @item String longer than a counted string returned by @code{WORD}:
1.26      crook    12724: @cindex string longer than a counted string returned by @code{WORD}
1.1       anton    12725: @cindex @code{WORD}, string overflow
                   12726: Not checked. The string will be ok, but the count will, of course,
                   12727: contain only the least significant bits of the length.
                   12728: 
                   12729: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   12730: @cindex @code{LSHIFT}, large shift counts
                   12731: @cindex @code{RSHIFT}, large shift counts
                   12732: Processor-dependent. Typical behaviours are returning 0 and using only
                   12733: the low bits of the shift count.
                   12734: 
                   12735: @item word not defined via @code{CREATE}:
                   12736: @cindex @code{>BODY} of non-@code{CREATE}d words
                   12737: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   12738: 
                   12739: @cindex @code{DOES>} of non-@code{CREATE}d words
                   12740: @code{DOES>} changes the execution semantics of the last defined word no
                   12741: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   12742: @code{CREATE , DOES>}.
                   12743: 
                   12744: @item words improperly used outside @code{<#} and @code{#>}:
                   12745: Not checked. As usual, you can expect memory faults.
                   12746: 
                   12747: @end table
                   12748: 
                   12749: 
                   12750: @c ---------------------------------------------------------------------
                   12751: @node core-other,  , core-ambcond, The Core Words
                   12752: @subsection Other system documentation
                   12753: @c ---------------------------------------------------------------------
                   12754: @cindex other system documentation, core words
                   12755: @cindex core words, other system documentation
                   12756: 
                   12757: @table @i
                   12758: @item nonstandard words using @code{PAD}:
                   12759: @cindex @code{PAD} use by nonstandard words
                   12760: None.
                   12761: 
                   12762: @item operator's terminal facilities available:
                   12763: @cindex operator's terminal facilities available
1.80      anton    12764: After processing the OS's command line, Gforth goes into interactive mode,
1.1       anton    12765: and you can give commands to Gforth interactively. The actual facilities
                   12766: available depend on how you invoke Gforth.
                   12767: 
                   12768: @item program data space available:
                   12769: @cindex program data space available
                   12770: @cindex data space available
                   12771: @code{UNUSED .} gives the remaining dictionary space. The total
                   12772: dictionary space can be specified with the @code{-m} switch
                   12773: (@pxref{Invoking Gforth}) when Gforth starts up.
                   12774: 
                   12775: @item return stack space available:
                   12776: @cindex return stack space available
                   12777: You can compute the total return stack space in cells with
                   12778: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   12779: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   12780: 
                   12781: @item stack space available:
                   12782: @cindex stack space available
                   12783: You can compute the total data stack space in cells with
                   12784: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   12785: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   12786: 
                   12787: @item system dictionary space required, in address units:
                   12788: @cindex system dictionary space required, in address units
                   12789: Type @code{here forthstart - .} after startup. At the time of this
                   12790: writing, this gives 80080 (bytes) on a 32-bit system.
                   12791: @end table
                   12792: 
                   12793: 
                   12794: @c =====================================================================
                   12795: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   12796: @section The optional Block word set
                   12797: @c =====================================================================
                   12798: @cindex system documentation, block words
                   12799: @cindex block words, system documentation
                   12800: 
                   12801: @menu
                   12802: * block-idef::                  Implementation Defined Options
                   12803: * block-ambcond::               Ambiguous Conditions               
                   12804: * block-other::                 Other System Documentation                 
                   12805: @end menu
                   12806: 
                   12807: 
                   12808: @c ---------------------------------------------------------------------
                   12809: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   12810: @subsection Implementation Defined Options
                   12811: @c ---------------------------------------------------------------------
                   12812: @cindex implementation-defined options, block words
                   12813: @cindex block words, implementation-defined options
                   12814: 
                   12815: @table @i
                   12816: @item the format for display by @code{LIST}:
                   12817: @cindex @code{LIST} display format
                   12818: First the screen number is displayed, then 16 lines of 64 characters,
                   12819: each line preceded by the line number.
                   12820: 
                   12821: @item the length of a line affected by @code{\}:
                   12822: @cindex length of a line affected by @code{\}
                   12823: @cindex @code{\}, line length in blocks
                   12824: 64 characters.
                   12825: @end table
                   12826: 
                   12827: 
                   12828: @c ---------------------------------------------------------------------
                   12829: @node block-ambcond, block-other, block-idef, The optional Block word set
                   12830: @subsection Ambiguous conditions
                   12831: @c ---------------------------------------------------------------------
                   12832: @cindex block words, ambiguous conditions
                   12833: @cindex ambiguous conditions, block words
                   12834: 
                   12835: @table @i
                   12836: @item correct block read was not possible:
                   12837: @cindex block read not possible
                   12838: Typically results in a @code{throw} of some OS-derived value (between
                   12839: -512 and -2048). If the blocks file was just not long enough, blanks are
                   12840: supplied for the missing portion.
                   12841: 
                   12842: @item I/O exception in block transfer:
                   12843: @cindex I/O exception in block transfer
                   12844: @cindex block transfer, I/O exception
                   12845: Typically results in a @code{throw} of some OS-derived value (between
                   12846: -512 and -2048).
                   12847: 
                   12848: @item invalid block number:
                   12849: @cindex invalid block number
                   12850: @cindex block number invalid
                   12851: @code{-35 throw} (Invalid block number)
                   12852: 
                   12853: @item a program directly alters the contents of @code{BLK}:
                   12854: @cindex @code{BLK}, altering @code{BLK}
                   12855: The input stream is switched to that other block, at the same
                   12856: position. If the storing to @code{BLK} happens when interpreting
                   12857: non-block input, the system will get quite confused when the block ends.
                   12858: 
                   12859: @item no current block buffer for @code{UPDATE}:
                   12860: @cindex @code{UPDATE}, no current block buffer
                   12861: @code{UPDATE} has no effect.
                   12862: 
                   12863: @end table
                   12864: 
                   12865: @c ---------------------------------------------------------------------
                   12866: @node block-other,  , block-ambcond, The optional Block word set
                   12867: @subsection Other system documentation
                   12868: @c ---------------------------------------------------------------------
                   12869: @cindex other system documentation, block words
                   12870: @cindex block words, other system documentation
                   12871: 
                   12872: @table @i
                   12873: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   12874: No restrictions (yet).
                   12875: 
                   12876: @item the number of blocks available for source and data:
                   12877: depends on your disk space.
                   12878: 
                   12879: @end table
                   12880: 
                   12881: 
                   12882: @c =====================================================================
                   12883: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   12884: @section The optional Double Number word set
                   12885: @c =====================================================================
                   12886: @cindex system documentation, double words
                   12887: @cindex double words, system documentation
                   12888: 
                   12889: @menu
                   12890: * double-ambcond::              Ambiguous Conditions              
                   12891: @end menu
                   12892: 
                   12893: 
                   12894: @c ---------------------------------------------------------------------
                   12895: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   12896: @subsection Ambiguous conditions
                   12897: @c ---------------------------------------------------------------------
                   12898: @cindex double words, ambiguous conditions
                   12899: @cindex ambiguous conditions, double words
                   12900: 
                   12901: @table @i
1.29      crook    12902: @item @i{d} outside of range of @i{n} in @code{D>S}:
                   12903: @cindex @code{D>S}, @i{d} out of range of @i{n} 
                   12904: The least significant cell of @i{d} is produced.
1.1       anton    12905: 
                   12906: @end table
                   12907: 
                   12908: 
                   12909: @c =====================================================================
                   12910: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   12911: @section The optional Exception word set
                   12912: @c =====================================================================
                   12913: @cindex system documentation, exception words
                   12914: @cindex exception words, system documentation
                   12915: 
                   12916: @menu
                   12917: * exception-idef::              Implementation Defined Options              
                   12918: @end menu
                   12919: 
                   12920: 
                   12921: @c ---------------------------------------------------------------------
                   12922: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   12923: @subsection Implementation Defined Options
                   12924: @c ---------------------------------------------------------------------
                   12925: @cindex implementation-defined options, exception words
                   12926: @cindex exception words, implementation-defined options
                   12927: 
                   12928: @table @i
                   12929: @item @code{THROW}-codes used in the system:
                   12930: @cindex @code{THROW}-codes used in the system
                   12931: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29      crook    12932: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1       anton    12933: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   12934: allocation operations). The mapping from OS error numbers to throw codes
                   12935: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   12936: undefined OS errors produce a message with a strange number; e.g.,
                   12937: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   12938: @end table
                   12939: 
                   12940: @c =====================================================================
                   12941: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   12942: @section The optional Facility word set
                   12943: @c =====================================================================
                   12944: @cindex system documentation, facility words
                   12945: @cindex facility words, system documentation
                   12946: 
                   12947: @menu
                   12948: * facility-idef::               Implementation Defined Options               
                   12949: * facility-ambcond::            Ambiguous Conditions            
                   12950: @end menu
                   12951: 
                   12952: 
                   12953: @c ---------------------------------------------------------------------
                   12954: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   12955: @subsection Implementation Defined Options
                   12956: @c ---------------------------------------------------------------------
                   12957: @cindex implementation-defined options, facility words
                   12958: @cindex facility words, implementation-defined options
                   12959: 
                   12960: @table @i
                   12961: @item encoding of keyboard events (@code{EKEY}):
                   12962: @cindex keyboard events, encoding in @code{EKEY}
                   12963: @cindex @code{EKEY}, encoding of keyboard events
1.40      anton    12964: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41      anton    12965: Other keys are encoded with the constants @code{k-left}, @code{k-right},
                   12966: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
                   12967: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
                   12968: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40      anton    12969: 
1.1       anton    12970: 
                   12971: @item duration of a system clock tick:
                   12972: @cindex duration of a system clock tick
                   12973: @cindex clock tick duration
                   12974: System dependent. With respect to @code{MS}, the time is specified in
                   12975: microseconds. How well the OS and the hardware implement this, is
                   12976: another question.
                   12977: 
                   12978: @item repeatability to be expected from the execution of @code{MS}:
                   12979: @cindex repeatability to be expected from the execution of @code{MS}
                   12980: @cindex @code{MS}, repeatability to be expected
                   12981: System dependent. On Unix, a lot depends on load. If the system is
                   12982: lightly loaded, and the delay is short enough that Gforth does not get
                   12983: swapped out, the performance should be acceptable. Under MS-DOS and
                   12984: other single-tasking systems, it should be good.
                   12985: 
                   12986: @end table
                   12987: 
                   12988: 
                   12989: @c ---------------------------------------------------------------------
                   12990: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   12991: @subsection Ambiguous conditions
                   12992: @c ---------------------------------------------------------------------
                   12993: @cindex facility words, ambiguous conditions
                   12994: @cindex ambiguous conditions, facility words
                   12995: 
                   12996: @table @i
                   12997: @item @code{AT-XY} can't be performed on user output device:
                   12998: @cindex @code{AT-XY} can't be performed on user output device
                   12999: Largely terminal dependent. No range checks are done on the arguments.
                   13000: No errors are reported. You may see some garbage appearing, you may see
                   13001: simply nothing happen.
                   13002: 
                   13003: @end table
                   13004: 
                   13005: 
                   13006: @c =====================================================================
                   13007: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   13008: @section The optional File-Access word set
                   13009: @c =====================================================================
                   13010: @cindex system documentation, file words
                   13011: @cindex file words, system documentation
                   13012: 
                   13013: @menu
                   13014: * file-idef::                   Implementation Defined Options
                   13015: * file-ambcond::                Ambiguous Conditions                
                   13016: @end menu
                   13017: 
                   13018: @c ---------------------------------------------------------------------
                   13019: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   13020: @subsection Implementation Defined Options
                   13021: @c ---------------------------------------------------------------------
                   13022: @cindex implementation-defined options, file words
                   13023: @cindex file words, implementation-defined options
                   13024: 
                   13025: @table @i
                   13026: @item file access methods used:
                   13027: @cindex file access methods used
                   13028: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   13029: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   13030: @code{wb}): The file is cleared, if it exists, and created, if it does
                   13031: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   13032: @code{create-file} creates a file with 666 permissions modified by your
                   13033: umask.
                   13034: 
                   13035: @item file exceptions:
                   13036: @cindex file exceptions
                   13037: The file words do not raise exceptions (except, perhaps, memory access
                   13038: faults when you pass illegal addresses or file-ids).
                   13039: 
                   13040: @item file line terminator:
                   13041: @cindex file line terminator
                   13042: System-dependent. Gforth uses C's newline character as line
                   13043: terminator. What the actual character code(s) of this are is
                   13044: system-dependent.
                   13045: 
                   13046: @item file name format:
                   13047: @cindex file name format
                   13048: System dependent. Gforth just uses the file name format of your OS.
                   13049: 
                   13050: @item information returned by @code{FILE-STATUS}:
                   13051: @cindex @code{FILE-STATUS}, returned information
                   13052: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   13053: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   13054: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   13055: along with the returned mode.
                   13056: 
                   13057: @item input file state after an exception when including source:
                   13058: @cindex exception when including source
                   13059: All files that are left via the exception are closed.
                   13060: 
1.29      crook    13061: @item @i{ior} values and meaning:
                   13062: @cindex @i{ior} values and meaning
1.68      anton    13063: @cindex @i{wior} values and meaning
1.29      crook    13064: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    13065: intended as throw codes. They typically are in the range
                   13066: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    13067: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    13068: 
                   13069: @item maximum depth of file input nesting:
                   13070: @cindex maximum depth of file input nesting
                   13071: @cindex file input nesting, maximum depth
                   13072: limited by the amount of return stack, locals/TIB stack, and the number
                   13073: of open files available. This should not give you troubles.
                   13074: 
                   13075: @item maximum size of input line:
                   13076: @cindex maximum size of input line
                   13077: @cindex input line size, maximum
                   13078: @code{/line}. Currently 255.
                   13079: 
                   13080: @item methods of mapping block ranges to files:
                   13081: @cindex mapping block ranges to files
                   13082: @cindex files containing blocks
                   13083: @cindex blocks in files
                   13084: By default, blocks are accessed in the file @file{blocks.fb} in the
                   13085: current working directory. The file can be switched with @code{USE}.
                   13086: 
                   13087: @item number of string buffers provided by @code{S"}:
                   13088: @cindex @code{S"}, number of string buffers
                   13089: 1
                   13090: 
                   13091: @item size of string buffer used by @code{S"}:
                   13092: @cindex @code{S"}, size of string buffer
                   13093: @code{/line}. currently 255.
                   13094: 
                   13095: @end table
                   13096: 
                   13097: @c ---------------------------------------------------------------------
                   13098: @node file-ambcond,  , file-idef, The optional File-Access word set
                   13099: @subsection Ambiguous conditions
                   13100: @c ---------------------------------------------------------------------
                   13101: @cindex file words, ambiguous conditions
                   13102: @cindex ambiguous conditions, file words
                   13103: 
                   13104: @table @i
                   13105: @item attempting to position a file outside its boundaries:
                   13106: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   13107: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   13108: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   13109: 
                   13110: @item attempting to read from file positions not yet written:
                   13111: @cindex reading from file positions not yet written
                   13112: End-of-file, i.e., zero characters are read and no error is reported.
                   13113: 
1.29      crook    13114: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
                   13115: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
1.1       anton    13116: An appropriate exception may be thrown, but a memory fault or other
                   13117: problem is more probable.
                   13118: 
1.29      crook    13119: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
                   13120: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
                   13121: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
                   13122: The @i{ior} produced by the operation, that discovered the problem, is
1.1       anton    13123: thrown.
                   13124: 
                   13125: @item named file cannot be opened (@code{INCLUDED}):
                   13126: @cindex @code{INCLUDED}, named file cannot be opened
1.29      crook    13127: The @i{ior} produced by @code{open-file} is thrown.
1.1       anton    13128: 
                   13129: @item requesting an unmapped block number:
                   13130: @cindex unmapped block numbers
                   13131: There are no unmapped legal block numbers. On some operating systems,
                   13132: writing a block with a large number may overflow the file system and
                   13133: have an error message as consequence.
                   13134: 
                   13135: @item using @code{source-id} when @code{blk} is non-zero:
                   13136: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   13137: @code{source-id} performs its function. Typically it will give the id of
                   13138: the source which loaded the block. (Better ideas?)
                   13139: 
                   13140: @end table
                   13141: 
                   13142: 
                   13143: @c =====================================================================
                   13144: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   13145: @section The optional Floating-Point word set
                   13146: @c =====================================================================
                   13147: @cindex system documentation, floating-point words
                   13148: @cindex floating-point words, system documentation
                   13149: 
                   13150: @menu
                   13151: * floating-idef::               Implementation Defined Options
                   13152: * floating-ambcond::            Ambiguous Conditions            
                   13153: @end menu
                   13154: 
                   13155: 
                   13156: @c ---------------------------------------------------------------------
                   13157: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   13158: @subsection Implementation Defined Options
                   13159: @c ---------------------------------------------------------------------
                   13160: @cindex implementation-defined options, floating-point words
                   13161: @cindex floating-point words, implementation-defined options
                   13162: 
                   13163: @table @i
                   13164: @item format and range of floating point numbers:
                   13165: @cindex format and range of floating point numbers
                   13166: @cindex floating point numbers, format and range
                   13167: System-dependent; the @code{double} type of C.
                   13168: 
1.29      crook    13169: @item results of @code{REPRESENT} when @i{float} is out of range:
                   13170: @cindex  @code{REPRESENT}, results when @i{float} is out of range
1.1       anton    13171: System dependent; @code{REPRESENT} is implemented using the C library
                   13172: function @code{ecvt()} and inherits its behaviour in this respect.
                   13173: 
                   13174: @item rounding or truncation of floating-point numbers:
                   13175: @cindex rounding of floating-point numbers
                   13176: @cindex truncation of floating-point numbers
                   13177: @cindex floating-point numbers, rounding or truncation
                   13178: System dependent; the rounding behaviour is inherited from the hosting C
                   13179: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   13180: nearest, and break ties by rounding to even (i.e., such that the last
                   13181: bit of the mantissa is 0).
                   13182: 
                   13183: @item size of floating-point stack:
                   13184: @cindex floating-point stack size
                   13185: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   13186: the floating-point stack (in floats). You can specify this on startup
                   13187: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   13188: 
                   13189: @item width of floating-point stack:
                   13190: @cindex floating-point stack width 
                   13191: @code{1 floats}.
                   13192: 
                   13193: @end table
                   13194: 
                   13195: 
                   13196: @c ---------------------------------------------------------------------
                   13197: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   13198: @subsection Ambiguous conditions
                   13199: @c ---------------------------------------------------------------------
                   13200: @cindex floating-point words, ambiguous conditions
                   13201: @cindex ambiguous conditions, floating-point words
                   13202: 
                   13203: @table @i
                   13204: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   13205: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   13206: System-dependent. Typically results in a @code{-23 THROW} like other
                   13207: alignment violations.
                   13208: 
                   13209: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   13210: @cindex @code{f@@} used with an address that is not float aligned
                   13211: @cindex @code{f!} used with an address that is not float aligned
                   13212: System-dependent. Typically results in a @code{-23 THROW} like other
                   13213: alignment violations.
                   13214: 
                   13215: @item floating-point result out of range:
                   13216: @cindex floating-point result out of range
1.80      anton    13217: System-dependent. Can result in a @code{-43 throw} (floating point
                   13218: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
                   13219: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1       anton    13220: unidentified fault), or can produce a special value representing, e.g.,
                   13221: Infinity.
                   13222: 
                   13223: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   13224: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   13225: System-dependent. Typically results in an alignment fault like other
                   13226: alignment violations.
                   13227: 
1.35      anton    13228: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   13229: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1       anton    13230: The floating-point number is converted into decimal nonetheless.
                   13231: 
                   13232: @item Both arguments are equal to zero (@code{FATAN2}):
                   13233: @cindex @code{FATAN2}, both arguments are equal to zero
                   13234: System-dependent. @code{FATAN2} is implemented using the C library
                   13235: function @code{atan2()}.
                   13236: 
1.29      crook    13237: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
                   13238: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
                   13239: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1       anton    13240: because of small errors and the tan will be a very large (or very small)
                   13241: but finite number.
                   13242: 
1.29      crook    13243: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
                   13244: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1       anton    13245: The result is rounded to the nearest float.
                   13246: 
                   13247: @item dividing by zero:
                   13248: @cindex dividing by zero, floating-point
                   13249: @cindex floating-point dividing by zero
                   13250: @cindex floating-point unidentified fault, FP divide-by-zero
1.80      anton    13251: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
                   13252: (floating point divide by zero) or @code{-55 throw} (Floating-point
                   13253: unidentified fault).
1.1       anton    13254: 
                   13255: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   13256: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   13257: System dependent. On IEEE-FP based systems the number is converted into
                   13258: an infinity.
                   13259: 
1.29      crook    13260: @item @i{float}<1 (@code{FACOSH}):
                   13261: @cindex @code{FACOSH}, @i{float}<1
1.1       anton    13262: @cindex floating-point unidentified fault, @code{FACOSH}
1.80      anton    13263: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1       anton    13264: 
1.29      crook    13265: @item @i{float}=<-1 (@code{FLNP1}):
                   13266: @cindex @code{FLNP1}, @i{float}=<-1
1.1       anton    13267: @cindex floating-point unidentified fault, @code{FLNP1}
1.80      anton    13268: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
                   13269: negative infinity for @i{float}=-1).
1.1       anton    13270: 
1.29      crook    13271: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
                   13272: @cindex @code{FLN}, @i{float}=<0
                   13273: @cindex @code{FLOG}, @i{float}=<0
1.1       anton    13274: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80      anton    13275: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
                   13276: negative infinity for @i{float}=0).
1.1       anton    13277: 
1.29      crook    13278: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
                   13279: @cindex @code{FASINH}, @i{float}<0
                   13280: @cindex @code{FSQRT}, @i{float}<0
1.1       anton    13281: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80      anton    13282: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
                   13283: @code{fasinh} some platforms produce a NaN, others a number (bug in the
                   13284: C library?).
1.1       anton    13285: 
1.29      crook    13286: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
                   13287: @cindex @code{FACOS}, |@i{float}|>1
                   13288: @cindex @code{FASIN}, |@i{float}|>1
                   13289: @cindex @code{FATANH}, |@i{float}|>1
1.1       anton    13290: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80      anton    13291: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1       anton    13292: 
1.29      crook    13293: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
                   13294: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1       anton    13295: @cindex floating-point unidentified fault, @code{F>D}
1.80      anton    13296: Platform-dependent; typically, some double number is produced and no
                   13297: error is reported.
1.1       anton    13298: 
                   13299: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   13300: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80      anton    13301: @code{Precision} characters of the numeric output area are used.  If
                   13302: @code{precision} is too high, these words will smash the data or code
                   13303: close to @code{here}.
1.1       anton    13304: @end table
                   13305: 
                   13306: @c =====================================================================
                   13307: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   13308: @section The optional Locals word set
                   13309: @c =====================================================================
                   13310: @cindex system documentation, locals words
                   13311: @cindex locals words, system documentation
                   13312: 
                   13313: @menu
                   13314: * locals-idef::                 Implementation Defined Options                 
                   13315: * locals-ambcond::              Ambiguous Conditions              
                   13316: @end menu
                   13317: 
                   13318: 
                   13319: @c ---------------------------------------------------------------------
                   13320: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   13321: @subsection Implementation Defined Options
                   13322: @c ---------------------------------------------------------------------
                   13323: @cindex implementation-defined options, locals words
                   13324: @cindex locals words, implementation-defined options
                   13325: 
                   13326: @table @i
                   13327: @item maximum number of locals in a definition:
                   13328: @cindex maximum number of locals in a definition
                   13329: @cindex locals, maximum number in a definition
                   13330: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   13331: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   13332: characters. The number of locals in a definition is bounded by the size
                   13333: of locals-buffer, which contains the names of the locals.
                   13334: 
                   13335: @end table
                   13336: 
                   13337: 
                   13338: @c ---------------------------------------------------------------------
                   13339: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   13340: @subsection Ambiguous conditions
                   13341: @c ---------------------------------------------------------------------
                   13342: @cindex locals words, ambiguous conditions
                   13343: @cindex ambiguous conditions, locals words
                   13344: 
                   13345: @table @i
                   13346: @item executing a named local in interpretation state:
                   13347: @cindex local in interpretation state
                   13348: @cindex Interpreting a compile-only word, for a local
                   13349: Locals have no interpretation semantics. If you try to perform the
                   13350: interpretation semantics, you will get a @code{-14 throw} somewhere
                   13351: (Interpreting a compile-only word). If you perform the compilation
                   13352: semantics, the locals access will be compiled (irrespective of state).
                   13353: 
1.29      crook    13354: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1       anton    13355: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   13356: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   13357: @cindex Invalid name argument, @code{TO}
                   13358: @code{-32 throw} (Invalid name argument)
                   13359: 
                   13360: @end table
                   13361: 
                   13362: 
                   13363: @c =====================================================================
                   13364: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   13365: @section The optional Memory-Allocation word set
                   13366: @c =====================================================================
                   13367: @cindex system documentation, memory-allocation words
                   13368: @cindex memory-allocation words, system documentation
                   13369: 
                   13370: @menu
                   13371: * memory-idef::                 Implementation Defined Options                 
                   13372: @end menu
                   13373: 
                   13374: 
                   13375: @c ---------------------------------------------------------------------
                   13376: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   13377: @subsection Implementation Defined Options
                   13378: @c ---------------------------------------------------------------------
                   13379: @cindex implementation-defined options, memory-allocation words
                   13380: @cindex memory-allocation words, implementation-defined options
                   13381: 
                   13382: @table @i
1.29      crook    13383: @item values and meaning of @i{ior}:
                   13384: @cindex  @i{ior} values and meaning
                   13385: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    13386: intended as throw codes. They typically are in the range
                   13387: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    13388: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    13389: 
                   13390: @end table
                   13391: 
                   13392: @c =====================================================================
                   13393: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   13394: @section The optional Programming-Tools word set
                   13395: @c =====================================================================
                   13396: @cindex system documentation, programming-tools words
                   13397: @cindex programming-tools words, system documentation
                   13398: 
                   13399: @menu
                   13400: * programming-idef::            Implementation Defined Options            
                   13401: * programming-ambcond::         Ambiguous Conditions         
                   13402: @end menu
                   13403: 
                   13404: 
                   13405: @c ---------------------------------------------------------------------
                   13406: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   13407: @subsection Implementation Defined Options
                   13408: @c ---------------------------------------------------------------------
                   13409: @cindex implementation-defined options, programming-tools words
                   13410: @cindex programming-tools words, implementation-defined options
                   13411: 
                   13412: @table @i
                   13413: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   13414: @cindex @code{;CODE} ending sequence
                   13415: @cindex @code{CODE} ending sequence
                   13416: @code{END-CODE}
                   13417: 
                   13418: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   13419: @cindex @code{;CODE}, processing input
                   13420: @cindex @code{CODE}, processing input
                   13421: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   13422: the input is processed by the text interpreter, (starting) in interpret
                   13423: state.
                   13424: 
                   13425: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   13426: @cindex @code{ASSEMBLER}, search order capability
                   13427: The ANS Forth search order word set.
                   13428: 
                   13429: @item source and format of display by @code{SEE}:
                   13430: @cindex @code{SEE}, source and format of output
1.80      anton    13431: The source for @code{see} is the executable code used by the inner
1.1       anton    13432: interpreter.  The current @code{see} tries to output Forth source code
1.80      anton    13433: (and on some platforms, assembly code for primitives) as well as
                   13434: possible.
1.1       anton    13435: 
                   13436: @end table
                   13437: 
                   13438: @c ---------------------------------------------------------------------
                   13439: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   13440: @subsection Ambiguous conditions
                   13441: @c ---------------------------------------------------------------------
                   13442: @cindex programming-tools words, ambiguous conditions
                   13443: @cindex ambiguous conditions, programming-tools words
                   13444: 
                   13445: @table @i
                   13446: 
1.21      crook    13447: @item deleting the compilation word list (@code{FORGET}):
                   13448: @cindex @code{FORGET}, deleting the compilation word list
1.1       anton    13449: Not implemented (yet).
                   13450: 
1.29      crook    13451: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
                   13452: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
                   13453: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1       anton    13454: @cindex control-flow stack underflow
                   13455: This typically results in an @code{abort"} with a descriptive error
                   13456: message (may change into a @code{-22 throw} (Control structure mismatch)
                   13457: in the future). You may also get a memory access error. If you are
                   13458: unlucky, this ambiguous condition is not caught.
                   13459: 
1.29      crook    13460: @item @i{name} can't be found (@code{FORGET}):
                   13461: @cindex @code{FORGET}, @i{name} can't be found
1.1       anton    13462: Not implemented (yet).
                   13463: 
1.29      crook    13464: @item @i{name} not defined via @code{CREATE}:
                   13465: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1       anton    13466: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   13467: the execution semantics of the last defined word no matter how it was
                   13468: defined.
                   13469: 
                   13470: @item @code{POSTPONE} applied to @code{[IF]}:
                   13471: @cindex @code{POSTPONE} applied to @code{[IF]}
                   13472: @cindex @code{[IF]} and @code{POSTPONE}
                   13473: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   13474: equivalent to @code{[IF]}.
                   13475: 
                   13476: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   13477: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   13478: Continue in the same state of conditional compilation in the next outer
                   13479: input source. Currently there is no warning to the user about this.
                   13480: 
                   13481: @item removing a needed definition (@code{FORGET}):
                   13482: @cindex @code{FORGET}, removing a needed definition
                   13483: Not implemented (yet).
                   13484: 
                   13485: @end table
                   13486: 
                   13487: 
                   13488: @c =====================================================================
                   13489: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   13490: @section The optional Search-Order word set
                   13491: @c =====================================================================
                   13492: @cindex system documentation, search-order words
                   13493: @cindex search-order words, system documentation
                   13494: 
                   13495: @menu
                   13496: * search-idef::                 Implementation Defined Options                 
                   13497: * search-ambcond::              Ambiguous Conditions              
                   13498: @end menu
                   13499: 
                   13500: 
                   13501: @c ---------------------------------------------------------------------
                   13502: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   13503: @subsection Implementation Defined Options
                   13504: @c ---------------------------------------------------------------------
                   13505: @cindex implementation-defined options, search-order words
                   13506: @cindex search-order words, implementation-defined options
                   13507: 
                   13508: @table @i
                   13509: @item maximum number of word lists in search order:
                   13510: @cindex maximum number of word lists in search order
                   13511: @cindex search order, maximum depth
                   13512: @code{s" wordlists" environment? drop .}. Currently 16.
                   13513: 
                   13514: @item minimum search order:
                   13515: @cindex minimum search order
                   13516: @cindex search order, minimum
                   13517: @code{root root}.
                   13518: 
                   13519: @end table
                   13520: 
                   13521: @c ---------------------------------------------------------------------
                   13522: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   13523: @subsection Ambiguous conditions
                   13524: @c ---------------------------------------------------------------------
                   13525: @cindex search-order words, ambiguous conditions
                   13526: @cindex ambiguous conditions, search-order words
                   13527: 
                   13528: @table @i
1.21      crook    13529: @item changing the compilation word list (during compilation):
                   13530: @cindex changing the compilation word list (during compilation)
                   13531: @cindex compilation word list, change before definition ends
                   13532: The word is entered into the word list that was the compilation word list
1.1       anton    13533: at the start of the definition. Any changes to the name field (e.g.,
                   13534: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116     anton    13535: are applied to the latest defined word (as reported by @code{latest} or
                   13536: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1       anton    13537: 
                   13538: @item search order empty (@code{previous}):
                   13539: @cindex @code{previous}, search order empty
1.26      crook    13540: @cindex vocstack empty, @code{previous}
1.1       anton    13541: @code{abort" Vocstack empty"}.
                   13542: 
                   13543: @item too many word lists in search order (@code{also}):
                   13544: @cindex @code{also}, too many word lists in search order
1.26      crook    13545: @cindex vocstack full, @code{also}
1.1       anton    13546: @code{abort" Vocstack full"}.
                   13547: 
                   13548: @end table
                   13549: 
                   13550: @c ***************************************************************
1.65      anton    13551: @node Standard vs Extensions, Model, ANS conformance, Top
                   13552: @chapter Should I use Gforth extensions?
                   13553: @cindex Gforth extensions
                   13554: 
                   13555: As you read through the rest of this manual, you will see documentation
                   13556: for @i{Standard} words, and documentation for some appealing Gforth
                   13557: @i{extensions}. You might ask yourself the question: @i{``Should I
                   13558: restrict myself to the standard, or should I use the extensions?''}
                   13559: 
                   13560: The answer depends on the goals you have for the program you are working
                   13561: on:
                   13562: 
                   13563: @itemize @bullet
                   13564: 
                   13565: @item Is it just for yourself or do you want to share it with others?
                   13566: 
                   13567: @item
                   13568: If you want to share it, do the others all use Gforth?
                   13569: 
                   13570: @item
                   13571: If it is just for yourself, do you want to restrict yourself to Gforth?
                   13572: 
                   13573: @end itemize
                   13574: 
                   13575: If restricting the program to Gforth is ok, then there is no reason not
                   13576: to use extensions.  It is still a good idea to keep to the standard
                   13577: where it is easy, in case you want to reuse these parts in another
                   13578: program that you want to be portable.
                   13579: 
                   13580: If you want to be able to port the program to other Forth systems, there
                   13581: are the following points to consider:
                   13582: 
                   13583: @itemize @bullet
                   13584: 
                   13585: @item
                   13586: Most Forth systems that are being maintained support the ANS Forth
                   13587: standard.  So if your program complies with the standard, it will be
                   13588: portable among many systems.
                   13589: 
                   13590: @item
                   13591: A number of the Gforth extensions can be implemented in ANS Forth using
                   13592: public-domain files provided in the @file{compat/} directory. These are
                   13593: mentioned in the text in passing.  There is no reason not to use these
                   13594: extensions, your program will still be ANS Forth compliant; just include
                   13595: the appropriate compat files with your program.
                   13596: 
                   13597: @item
                   13598: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
                   13599: analyse your program and determine what non-Standard words it relies
                   13600: upon.  However, it does not check whether you use standard words in a
                   13601: non-standard way.
                   13602: 
                   13603: @item
                   13604: Some techniques are not standardized by ANS Forth, and are hard or
                   13605: impossible to implement in a standard way, but can be implemented in
                   13606: most Forth systems easily, and usually in similar ways (e.g., accessing
                   13607: word headers).  Forth has a rich historical precedent for programmers
                   13608: taking advantage of implementation-dependent features of their tools
                   13609: (for example, relying on a knowledge of the dictionary
                   13610: structure). Sometimes these techniques are necessary to extract every
                   13611: last bit of performance from the hardware, sometimes they are just a
                   13612: programming shorthand.
                   13613: 
                   13614: @item
                   13615: Does using a Gforth extension save more work than the porting this part
                   13616: to other Forth systems (if any) will cost?
                   13617: 
                   13618: @item
                   13619: Is the additional functionality worth the reduction in portability and
                   13620: the additional porting problems?
                   13621: 
                   13622: @end itemize
                   13623: 
                   13624: In order to perform these consideratios, you need to know what's
                   13625: standard and what's not.  This manual generally states if something is
1.81      anton    13626: non-standard, but the authoritative source is the
                   13627: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65      anton    13628: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
                   13629: into the thought processes of the technical committee.
                   13630: 
                   13631: Note also that portability between Forth systems is not the only
                   13632: portability issue; there is also the issue of portability between
                   13633: different platforms (processor/OS combinations).
                   13634: 
                   13635: @c ***************************************************************
                   13636: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1       anton    13637: @chapter Model
                   13638: 
                   13639: This chapter has yet to be written. It will contain information, on
                   13640: which internal structures you can rely.
                   13641: 
                   13642: @c ***************************************************************
                   13643: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   13644: @chapter Integrating Gforth into C programs
                   13645: 
                   13646: This is not yet implemented.
                   13647: 
                   13648: Several people like to use Forth as scripting language for applications
                   13649: that are otherwise written in C, C++, or some other language.
                   13650: 
                   13651: The Forth system ATLAST provides facilities for embedding it into
                   13652: applications; unfortunately it has several disadvantages: most
                   13653: importantly, it is not based on ANS Forth, and it is apparently dead
                   13654: (i.e., not developed further and not supported). The facilities
1.21      crook    13655: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1       anton    13656: making the switch should not be hard.
                   13657: 
                   13658: We also tried to design the interface such that it can easily be
                   13659: implemented by other Forth systems, so that we may one day arrive at a
                   13660: standardized interface. Such a standard interface would allow you to
                   13661: replace the Forth system without having to rewrite C code.
                   13662: 
                   13663: You embed the Gforth interpreter by linking with the library
                   13664: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   13665: global symbols in this library that belong to the interface, have the
                   13666: prefix @code{forth_}. (Global symbols that are used internally have the
                   13667: prefix @code{gforth_}).
                   13668: 
                   13669: You can include the declarations of Forth types and the functions and
                   13670: variables of the interface with @code{#include <forth.h>}.
                   13671: 
                   13672: Types.
                   13673: 
                   13674: Variables.
                   13675: 
                   13676: Data and FP Stack pointer. Area sizes.
                   13677: 
                   13678: functions.
                   13679: 
                   13680: forth_init(imagefile)
                   13681: forth_evaluate(string) exceptions?
                   13682: forth_goto(address) (or forth_execute(xt)?)
                   13683: forth_continue() (a corountining mechanism)
                   13684: 
                   13685: Adding primitives.
                   13686: 
                   13687: No checking.
                   13688: 
                   13689: Signals?
                   13690: 
                   13691: Accessing the Stacks
                   13692: 
1.26      crook    13693: @c ******************************************************************
1.1       anton    13694: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   13695: @chapter Emacs and Gforth
                   13696: @cindex Emacs and Gforth
                   13697: 
                   13698: @cindex @file{gforth.el}
                   13699: @cindex @file{forth.el}
                   13700: @cindex Rydqvist, Goran
1.107     dvdkhlng 13701: @cindex Kuehling, David
1.1       anton    13702: @cindex comment editing commands
                   13703: @cindex @code{\}, editing with Emacs
                   13704: @cindex debug tracer editing commands
                   13705: @cindex @code{~~}, removal with Emacs
                   13706: @cindex Forth mode in Emacs
1.107     dvdkhlng 13707: 
1.1       anton    13708: Gforth comes with @file{gforth.el}, an improved version of
                   13709: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26      crook    13710: improvements are:
                   13711: 
                   13712: @itemize @bullet
                   13713: @item
1.107     dvdkhlng 13714: A better handling of indentation.
                   13715: @item
                   13716: A custom hilighting engine for Forth-code.
1.26      crook    13717: @item
                   13718: Comment paragraph filling (@kbd{M-q})
                   13719: @item
                   13720: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
                   13721: @item
                   13722: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41      anton    13723: @item
                   13724: Support of the @code{info-lookup} feature for looking up the
                   13725: documentation of a word.
1.107     dvdkhlng 13726: @item
                   13727: Support for reading and writing blocks files.
1.26      crook    13728: @end itemize
                   13729: 
1.107     dvdkhlng 13730: To get a basic description of these features, enter Forth mode and
                   13731: type @kbd{C-h m}.
1.1       anton    13732: 
                   13733: @cindex source location of error or debugging output in Emacs
                   13734: @cindex error output, finding the source location in Emacs
                   13735: @cindex debugging output, finding the source location in Emacs
                   13736: In addition, Gforth supports Emacs quite well: The source code locations
                   13737: given in error messages, debugging output (from @code{~~}) and failed
                   13738: assertion messages are in the right format for Emacs' compilation mode
                   13739: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   13740: Manual}) so the source location corresponding to an error or other
                   13741: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   13742: @kbd{C-c C-c} for the error under the cursor).
                   13743: 
1.107     dvdkhlng 13744: @cindex viewing the documentation of a word in Emacs
                   13745: @cindex context-sensitive help
                   13746: Moreover, for words documented in this manual, you can look up the
                   13747: glossary entry quickly by using @kbd{C-h TAB}
                   13748: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
                   13749: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
                   13750: later and does not work for words containing @code{:}.
                   13751: 
                   13752: @menu
                   13753: * Installing gforth.el::        Making Emacs aware of Forth.
                   13754: * Emacs Tags::                  Viewing the source of a word in Emacs.
                   13755: * Hilighting::                  Making Forth code look prettier.
                   13756: * Auto-Indentation::            Customizing auto-indentation.
                   13757: * Blocks Files::                Reading and writing blocks files.
                   13758: @end menu
                   13759: 
                   13760: @c ----------------------------------
1.109     anton    13761: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107     dvdkhlng 13762: @section Installing gforth.el
                   13763: @cindex @file{.emacs}
                   13764: @cindex @file{gforth.el}, installation
                   13765: To make the features from @file{gforth.el} available in Emacs, add
                   13766: the following lines to your @file{.emacs} file:
                   13767: 
                   13768: @example
                   13769: (autoload 'forth-mode "gforth.el")
                   13770: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) 
                   13771:                            auto-mode-alist))
                   13772: (autoload 'forth-block-mode "gforth.el")
                   13773: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode) 
                   13774:                            auto-mode-alist))
                   13775: (add-hook 'forth-mode-hook (function (lambda ()
                   13776:    ;; customize variables here:
                   13777:    (setq forth-indent-level 4)
                   13778:    (setq forth-minor-indent-level 2)
                   13779:    (setq forth-hilight-level 3)
                   13780:    ;;; ...
                   13781: )))
                   13782: @end example
                   13783: 
                   13784: @c ----------------------------------
                   13785: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
                   13786: @section Emacs Tags
1.1       anton    13787: @cindex @file{TAGS} file
                   13788: @cindex @file{etags.fs}
                   13789: @cindex viewing the source of a word in Emacs
1.43      anton    13790: @cindex @code{require}, placement in files
                   13791: @cindex @code{include}, placement in files
1.107     dvdkhlng 13792: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
                   13793: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1       anton    13794: contains the definitions of all words defined afterwards. You can then
1.107     dvdkhlng 13795: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1       anton    13796: several tags files at the same time (e.g., one for the Gforth sources
                   13797: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   13798: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   13799: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43      anton    13800: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
                   13801: with @file{etags.fs}, you should avoid putting definitions both before
                   13802: and after @code{require} etc., otherwise you will see the same file
                   13803: visited several times by commands like @code{tags-search}.
1.1       anton    13804: 
1.107     dvdkhlng 13805: @c ----------------------------------
                   13806: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
                   13807: @section Hilighting
                   13808: @cindex hilighting Forth code in Emacs
                   13809: @cindex highlighting Forth code in Emacs
                   13810: @file{gforth.el} comes with a custom source hilighting engine.  When
                   13811: you open a file in @code{forth-mode}, it will be completely parsed,
                   13812: assigning faces to keywords, comments, strings etc.  While you edit
                   13813: the file, modified regions get parsed and updated on-the-fly. 
                   13814: 
                   13815: Use the variable `forth-hilight-level' to change the level of
                   13816: decoration from 0 (no hilighting at all) to 3 (the default).  Even if
                   13817: you set the hilighting level to 0, the parser will still work in the
                   13818: background, collecting information about whether regions of text are
                   13819: ``compiled'' or ``interpreted''.  Those information are required for
                   13820: auto-indentation to work properly.  Set `forth-disable-parser' to
                   13821: non-nil if your computer is too slow to handle parsing.  This will
                   13822: have an impact on the smartness of the auto-indentation engine,
                   13823: though.
                   13824: 
                   13825: Sometimes Forth sources define new features that should be hilighted,
                   13826: new control structures, defining-words etc.  You can use the variable
                   13827: `forth-custom-words' to make @code{forth-mode} hilight additional
                   13828: words and constructs.  See the docstring of `forth-words' for details
                   13829: (in Emacs, type @kbd{C-h v forth-words}).
                   13830: 
                   13831: `forth-custom-words' is meant to be customized in your
                   13832: @file{.emacs} file.  To customize hilighing in a file-specific manner,
                   13833: set `forth-local-words' in a local-variables section at the end of
                   13834: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
                   13835: 
                   13836: Example:
                   13837: @example
                   13838: 0 [IF]
                   13839:    Local Variables:
                   13840:    forth-local-words:
                   13841:       ((("t:") definition-starter (font-lock-keyword-face . 1)
                   13842:         "[ \t\n]" t name (font-lock-function-name-face . 3))
                   13843:        ((";t") definition-ender (font-lock-keyword-face . 1)))
                   13844:    End:
                   13845: [THEN]
                   13846: @end example
                   13847: 
                   13848: @c ----------------------------------
                   13849: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
                   13850: @section Auto-Indentation
                   13851: @cindex auto-indentation of Forth code in Emacs
                   13852: @cindex indentation of Forth code in Emacs
                   13853: @code{forth-mode} automatically tries to indent lines in a smart way,
                   13854: whenever you type @key{TAB} or break a line with @kbd{C-m}.
                   13855: 
                   13856: Simple customization can be achieved by setting
                   13857: `forth-indent-level' and `forth-minor-indent-level' in your
                   13858: @file{.emacs} file. For historical reasons @file{gforth.el} indents
                   13859: per default by multiples of 4 columns.  To use the more traditional
                   13860: 3-column indentation, add the following lines to your @file{.emacs}:
                   13861: 
                   13862: @example
                   13863: (add-hook 'forth-mode-hook (function (lambda ()
                   13864:    ;; customize variables here:
                   13865:    (setq forth-indent-level 3)
                   13866:    (setq forth-minor-indent-level 1)
                   13867: )))
                   13868: @end example
                   13869: 
                   13870: If you want indentation to recognize non-default words, customize it
                   13871: by setting `forth-custom-indent-words' in your @file{.emacs}.  See the
                   13872: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
                   13873: v forth-indent-words}).
                   13874: 
                   13875: To customize indentation in a file-specific manner, set
                   13876: `forth-local-indent-words' in a local-variables section at the end of
                   13877: your source file (@pxref{Local Variables in Files, Variables,,emacs,
                   13878: Emacs Manual}).
                   13879: 
                   13880: Example:
                   13881: @example
                   13882: 0 [IF]
                   13883:    Local Variables:
                   13884:    forth-local-indent-words:
                   13885:       ((("t:") (0 . 2) (0 . 2))
                   13886:        ((";t") (-2 . 0) (0 . -2)))
                   13887:    End:
                   13888: [THEN]
                   13889: @end example
                   13890: 
                   13891: @c ----------------------------------
1.109     anton    13892: @node Blocks Files,  , Auto-Indentation, Emacs and Gforth
1.107     dvdkhlng 13893: @section Blocks Files
                   13894: @cindex blocks files, use with Emacs
                   13895: @code{forth-mode} Autodetects blocks files by checking whether the
                   13896: length of the first line exceeds 1023 characters.  It then tries to
                   13897: convert the file into normal text format.  When you save the file, it
                   13898: will be written to disk as normal stream-source file.
                   13899: 
                   13900: If you want to write blocks files, use @code{forth-blocks-mode}.  It
                   13901: inherits all the features from @code{forth-mode}, plus some additions:
1.41      anton    13902: 
1.107     dvdkhlng 13903: @itemize @bullet
                   13904: @item
                   13905: Files are written to disk in blocks file format.
                   13906: @item
                   13907: Screen numbers are displayed in the mode line (enumerated beginning
                   13908: with the value of `forth-block-base')
                   13909: @item
                   13910: Warnings are displayed when lines exceed 64 characters.
                   13911: @item
                   13912: The beginning of the currently edited block is marked with an
                   13913: overlay-arrow. 
                   13914: @end itemize
1.41      anton    13915: 
1.107     dvdkhlng 13916: There are some restrictions you should be aware of.  When you open a
                   13917: blocks file that contains tabulator or newline characters, these
                   13918: characters will be translated into spaces when the file is written
                   13919: back to disk.  If tabs or newlines are encountered during blocks file
                   13920: reading, an error is output to the echo area. So have a look at the
                   13921: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1       anton    13922: 
1.107     dvdkhlng 13923: Please consult the docstring of @code{forth-blocks-mode} for more
                   13924: information by typing @kbd{C-h v forth-blocks-mode}).
1.1       anton    13925: 
1.26      crook    13926: @c ******************************************************************
1.1       anton    13927: @node Image Files, Engine, Emacs and Gforth, Top
                   13928: @chapter Image Files
1.26      crook    13929: @cindex image file
                   13930: @cindex @file{.fi} files
1.1       anton    13931: @cindex precompiled Forth code
                   13932: @cindex dictionary in persistent form
                   13933: @cindex persistent form of dictionary
                   13934: 
                   13935: An image file is a file containing an image of the Forth dictionary,
                   13936: i.e., compiled Forth code and data residing in the dictionary.  By
                   13937: convention, we use the extension @code{.fi} for image files.
                   13938: 
                   13939: @menu
1.18      anton    13940: * Image Licensing Issues::      Distribution terms for images.
                   13941: * Image File Background::       Why have image files?
1.67      anton    13942: * Non-Relocatable Image Files::  don't always work.
1.18      anton    13943: * Data-Relocatable Image Files::  are better.
1.67      anton    13944: * Fully Relocatable Image Files::  better yet.
1.18      anton    13945: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.29      crook    13946: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.18      anton    13947: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    13948: @end menu
                   13949: 
1.18      anton    13950: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   13951: @section Image Licensing Issues
                   13952: @cindex license for images
                   13953: @cindex image license
                   13954: 
                   13955: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   13956: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   13957: original image; i.e., according to copyright law it is a derived work of
                   13958: the original image.
                   13959: 
                   13960: Since Gforth is distributed under the GNU GPL, the newly created image
                   13961: falls under the GNU GPL, too. In particular, this means that if you
                   13962: distribute the image, you have to make all of the sources for the image
1.113     anton    13963: available, including those you wrote.  For details see @ref{Copying, ,
1.18      anton    13964: GNU General Public License (Section 3)}.
                   13965: 
                   13966: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   13967: contains only code compiled from the sources you gave it; if none of
                   13968: these sources is under the GPL, the terms discussed above do not apply
                   13969: to the image. However, if your image needs an engine (a gforth binary)
                   13970: that is under the GPL, you should make sure that you distribute both in
                   13971: a way that is at most a @emph{mere aggregation}, if you don't want the
                   13972: terms of the GPL to apply to the image.
                   13973: 
                   13974: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    13975: @section Image File Background
                   13976: @cindex image file background
                   13977: 
1.80      anton    13978: Gforth consists not only of primitives (in the engine), but also of
1.1       anton    13979: definitions written in Forth. Since the Forth compiler itself belongs to
                   13980: those definitions, it is not possible to start the system with the
1.80      anton    13981: engine and the Forth source alone. Therefore we provide the Forth
1.26      crook    13982: code as an image file in nearly executable form. When Gforth starts up,
                   13983: a C routine loads the image file into memory, optionally relocates the
                   13984: addresses, then sets up the memory (stacks etc.) according to
                   13985: information in the image file, and (finally) starts executing Forth
                   13986: code.
1.1       anton    13987: 
                   13988: The image file variants represent different compromises between the
                   13989: goals of making it easy to generate image files and making them
                   13990: portable.
                   13991: 
                   13992: @cindex relocation at run-time
1.26      crook    13993: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1       anton    13994: run-time. This avoids many of the complications discussed below (image
                   13995: files are data relocatable without further ado), but costs performance
                   13996: (one addition per memory access).
                   13997: 
                   13998: @cindex relocation at load-time
1.26      crook    13999: By contrast, the Gforth loader performs relocation at image load time. The
                   14000: loader also has to replace tokens that represent primitive calls with the
1.1       anton    14001: appropriate code-field addresses (or code addresses in the case of
                   14002: direct threading).
                   14003: 
                   14004: There are three kinds of image files, with different degrees of
                   14005: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   14006: image files.
                   14007: 
                   14008: @cindex image file loader
                   14009: @cindex relocating loader
                   14010: @cindex loader for image files
                   14011: These image file variants have several restrictions in common; they are
                   14012: caused by the design of the image file loader:
                   14013: 
                   14014: @itemize @bullet
                   14015: @item
                   14016: There is only one segment; in particular, this means, that an image file
                   14017: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26      crook    14018: them). The contents of the stacks are not represented, either.
1.1       anton    14019: 
                   14020: @item
                   14021: The only kinds of relocation supported are: adding the same offset to
                   14022: all cells that represent data addresses; and replacing special tokens
                   14023: with code addresses or with pieces of machine code.
                   14024: 
                   14025: If any complex computations involving addresses are performed, the
                   14026: results cannot be represented in the image file. Several applications that
                   14027: use such computations come to mind:
                   14028: @itemize @minus
                   14029: @item
                   14030: Hashing addresses (or data structures which contain addresses) for table
                   14031: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   14032: purpose, you will have no problem, because the hash tables are
                   14033: recomputed automatically when the system is started. If you use your own
                   14034: hash tables, you will have to do something similar.
                   14035: 
                   14036: @item
                   14037: There's a cute implementation of doubly-linked lists that uses
                   14038: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   14039: in the image file, and restore the doubly-linked representation on
                   14040: startup.@footnote{In my opinion, though, you should think thrice before
                   14041: using a doubly-linked list (whatever implementation).}
                   14042: 
                   14043: @item
                   14044: The code addresses of run-time routines like @code{docol:} cannot be
                   14045: represented in the image file (because their tokens would be replaced by
                   14046: machine code in direct threaded implementations). As a workaround,
                   14047: compute these addresses at run-time with @code{>code-address} from the
                   14048: executions tokens of appropriate words (see the definitions of
1.80      anton    14049: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1       anton    14050: 
                   14051: @item
                   14052: On many architectures addresses are represented in machine code in some
                   14053: shifted or mangled form. You cannot put @code{CODE} words that contain
                   14054: absolute addresses in this form in a relocatable image file. Workarounds
                   14055: are representing the address in some relative form (e.g., relative to
                   14056: the CFA, which is present in some register), or loading the address from
                   14057: a place where it is stored in a non-mangled form.
                   14058: @end itemize
                   14059: @end itemize
                   14060: 
                   14061: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   14062: @section Non-Relocatable Image Files
                   14063: @cindex non-relocatable image files
1.26      crook    14064: @cindex image file, non-relocatable
1.1       anton    14065: 
                   14066: These files are simple memory dumps of the dictionary. They are specific
                   14067: to the executable (i.e., @file{gforth} file) they were created
                   14068: with. What's worse, they are specific to the place on which the
                   14069: dictionary resided when the image was created. Now, there is no
                   14070: guarantee that the dictionary will reside at the same place the next
                   14071: time you start Gforth, so there's no guarantee that a non-relocatable
                   14072: image will work the next time (Gforth will complain instead of crashing,
                   14073: though).
                   14074: 
                   14075: You can create a non-relocatable image file with
                   14076: 
1.44      crook    14077: 
1.1       anton    14078: doc-savesystem
                   14079: 
1.44      crook    14080: 
1.1       anton    14081: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   14082: @section Data-Relocatable Image Files
                   14083: @cindex data-relocatable image files
1.26      crook    14084: @cindex image file, data-relocatable
1.1       anton    14085: 
                   14086: These files contain relocatable data addresses, but fixed code addresses
                   14087: (instead of tokens). They are specific to the executable (i.e.,
                   14088: @file{gforth} file) they were created with. For direct threading on some
                   14089: architectures (e.g., the i386), data-relocatable images do not work. You
                   14090: get a data-relocatable image, if you use @file{gforthmi} with a
                   14091: Gforth binary that is not doubly indirect threaded (@pxref{Fully
                   14092: Relocatable Image Files}).
                   14093: 
                   14094: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   14095: @section Fully Relocatable Image Files
                   14096: @cindex fully relocatable image files
1.26      crook    14097: @cindex image file, fully relocatable
1.1       anton    14098: 
                   14099: @cindex @file{kern*.fi}, relocatability
                   14100: @cindex @file{gforth.fi}, relocatability
                   14101: These image files have relocatable data addresses, and tokens for code
                   14102: addresses. They can be used with different binaries (e.g., with and
                   14103: without debugging) on the same machine, and even across machines with
                   14104: the same data formats (byte order, cell size, floating point
                   14105: format). However, they are usually specific to the version of Gforth
                   14106: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
                   14107: are fully relocatable.
                   14108: 
                   14109: There are two ways to create a fully relocatable image file:
                   14110: 
                   14111: @menu
1.29      crook    14112: * gforthmi::                    The normal way
1.1       anton    14113: * cross.fs::                    The hard way
                   14114: @end menu
                   14115: 
                   14116: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   14117: @subsection @file{gforthmi}
                   14118: @cindex @file{comp-i.fs}
                   14119: @cindex @file{gforthmi}
                   14120: 
                   14121: You will usually use @file{gforthmi}. If you want to create an
1.29      crook    14122: image @i{file} that contains everything you would load by invoking
                   14123: Gforth with @code{gforth @i{options}}, you simply say:
1.1       anton    14124: @example
1.29      crook    14125: gforthmi @i{file} @i{options}
1.1       anton    14126: @end example
                   14127: 
                   14128: E.g., if you want to create an image @file{asm.fi} that has the file
                   14129: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   14130: like this:
                   14131: 
                   14132: @example
                   14133: gforthmi asm.fi asm.fs
                   14134: @end example
                   14135: 
1.27      crook    14136: @file{gforthmi} is implemented as a sh script and works like this: It
                   14137: produces two non-relocatable images for different addresses and then
                   14138: compares them. Its output reflects this: first you see the output (if
1.62      crook    14139: any) of the two Gforth invocations that produce the non-relocatable image
1.27      crook    14140: files, then you see the output of the comparing program: It displays the
                   14141: offset used for data addresses and the offset used for code addresses;
1.1       anton    14142: moreover, for each cell that cannot be represented correctly in the
1.44      crook    14143: image files, it displays a line like this:
1.1       anton    14144: 
                   14145: @example
                   14146:      78DC         BFFFFA50         BFFFFA40
                   14147: @end example
                   14148: 
                   14149: This means that at offset $78dc from @code{forthstart}, one input image
                   14150: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   14151: cannot be represented correctly in the output image, you should examine
                   14152: these places in the dictionary and verify that these cells are dead
                   14153: (i.e., not read before they are written).
1.39      anton    14154: 
                   14155: @cindex --application, @code{gforthmi} option
                   14156: If you insert the option @code{--application} in front of the image file
                   14157: name, you will get an image that uses the @code{--appl-image} option
                   14158: instead of the @code{--image-file} option (@pxref{Invoking
                   14159: Gforth}). When you execute such an image on Unix (by typing the image
                   14160: name as command), the Gforth engine will pass all options to the image
                   14161: instead of trying to interpret them as engine options.
1.1       anton    14162: 
1.27      crook    14163: If you type @file{gforthmi} with no arguments, it prints some usage
                   14164: instructions.
                   14165: 
1.1       anton    14166: @cindex @code{savesystem} during @file{gforthmi}
                   14167: @cindex @code{bye} during @file{gforthmi}
                   14168: @cindex doubly indirect threaded code
1.44      crook    14169: @cindex environment variables
                   14170: @cindex @code{GFORTHD} -- environment variable
                   14171: @cindex @code{GFORTH} -- environment variable
1.1       anton    14172: @cindex @code{gforth-ditc}
1.29      crook    14173: There are a few wrinkles: After processing the passed @i{options}, the
1.1       anton    14174: words @code{savesystem} and @code{bye} must be visible. A special doubly
                   14175: indirect threaded version of the @file{gforth} executable is used for
1.62      crook    14176: creating the non-relocatable images; you can pass the exact filename of
1.1       anton    14177: this executable through the environment variable @code{GFORTHD}
                   14178: (default: @file{gforth-ditc}); if you pass a version that is not doubly
                   14179: indirect threaded, you will not get a fully relocatable image, but a
1.27      crook    14180: data-relocatable image (because there is no code address offset). The
                   14181: normal @file{gforth} executable is used for creating the relocatable
                   14182: image; you can pass the exact filename of this executable through the
                   14183: environment variable @code{GFORTH}.
1.1       anton    14184: 
                   14185: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   14186: @subsection @file{cross.fs}
                   14187: @cindex @file{cross.fs}
                   14188: @cindex cross-compiler
                   14189: @cindex metacompiler
1.47      crook    14190: @cindex target compiler
1.1       anton    14191: 
                   14192: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47      crook    14193: programming language (@pxref{Cross Compiler}).
1.1       anton    14194: 
1.47      crook    14195: @code{cross} allows you to create image files for machines with
1.1       anton    14196: different data sizes and data formats than the one used for generating
                   14197: the image file. You can also use it to create an application image that
                   14198: does not contain a Forth compiler. These features are bought with
                   14199: restrictions and inconveniences in programming. E.g., addresses have to
                   14200: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   14201: order to make the code relocatable.
                   14202: 
                   14203: 
                   14204: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   14205: @section Stack and Dictionary Sizes
                   14206: @cindex image file, stack and dictionary sizes
                   14207: @cindex dictionary size default
                   14208: @cindex stack size default
                   14209: 
                   14210: If you invoke Gforth with a command line flag for the size
                   14211: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   14212: dictionary. If you save the dictionary with @code{savesystem} or create
                   14213: an image with @file{gforthmi}, this size will become the default
                   14214: for the resulting image file. E.g., the following will create a
1.21      crook    14215: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1       anton    14216: 
                   14217: @example
                   14218: gforthmi gforth.fi -m 1M
                   14219: @end example
                   14220: 
                   14221: In other words, if you want to set the default size for the dictionary
                   14222: and the stacks of an image, just invoke @file{gforthmi} with the
                   14223: appropriate options when creating the image.
                   14224: 
                   14225: @cindex stack size, cache-friendly
                   14226: Note: For cache-friendly behaviour (i.e., good performance), you should
                   14227: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   14228: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   14229: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   14230: 
                   14231: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   14232: @section Running Image Files
                   14233: @cindex running image files
                   14234: @cindex invoking image files
                   14235: @cindex image file invocation
                   14236: 
                   14237: @cindex -i, invoke image file
                   14238: @cindex --image file, invoke image file
1.29      crook    14239: You can invoke Gforth with an image file @i{image} instead of the
1.1       anton    14240: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   14241: @example
1.29      crook    14242: gforth -i @i{image}
1.1       anton    14243: @end example
                   14244: 
                   14245: @cindex executable image file
1.26      crook    14246: @cindex image file, executable
1.1       anton    14247: If your operating system supports starting scripts with a line of the
                   14248: form @code{#! ...}, you just have to type the image file name to start
                   14249: Gforth with this image file (note that the file extension @code{.fi} is
1.29      crook    14250: just a convention). I.e., to run Gforth with the image file @i{image},
                   14251: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27      crook    14252: This works because every @code{.fi} file starts with a line of this
                   14253: format:
                   14254: 
                   14255: @example
                   14256: #! /usr/local/bin/gforth-0.4.0 -i
                   14257: @end example
                   14258: 
                   14259: The file and pathname for the Gforth engine specified on this line is
                   14260: the specific Gforth executable that it was built against; i.e. the value
                   14261: of the environment variable @code{GFORTH} at the time that
                   14262: @file{gforthmi} was executed.
1.1       anton    14263: 
1.27      crook    14264: You can make use of the same shell capability to make a Forth source
                   14265: file into an executable. For example, if you place this text in a file:
1.26      crook    14266: 
                   14267: @example
                   14268: #! /usr/local/bin/gforth
                   14269: 
                   14270: ." Hello, world" CR
                   14271: bye
                   14272: @end example
                   14273: 
                   14274: @noindent
1.27      crook    14275: and then make the file executable (chmod +x in Unix), you can run it
1.26      crook    14276: directly from the command line. The sequence @code{#!} is used in two
                   14277: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29      crook    14278: system@footnote{The Unix kernel actually recognises two types of files:
                   14279: executable files and files of data, where the data is processed by an
                   14280: interpreter that is specified on the ``interpreter line'' -- the first
                   14281: line of the file, starting with the sequence #!. There may be a small
                   14282: limit (e.g., 32) on the number of characters that may be specified on
                   14283: the interpreter line.} secondly it is treated as a comment character by
                   14284: Gforth. Because of the second usage, a space is required between
1.80      anton    14285: @code{#!} and the path to the executable (moreover, some Unixes
                   14286: require the sequence @code{#! /}).
1.27      crook    14287: 
                   14288: The disadvantage of this latter technique, compared with using
1.80      anton    14289: @file{gforthmi}, is that it is slightly slower; the Forth source code is
                   14290: compiled on-the-fly, each time the program is invoked.
1.26      crook    14291: 
1.1       anton    14292: doc-#!
                   14293: 
1.44      crook    14294: 
1.1       anton    14295: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   14296: @section Modifying the Startup Sequence
                   14297: @cindex startup sequence for image file
                   14298: @cindex image file initialization sequence
                   14299: @cindex initialization sequence of image file
                   14300: 
1.120     anton    14301: You can add your own initialization to the startup sequence of an image
                   14302: through the deferred word @code{'cold}. @code{'cold} is invoked just
                   14303: before the image-specific command line processing (i.e., loading files
                   14304: and evaluating (@code{-e}) strings) starts.
1.1       anton    14305: 
                   14306: A sequence for adding your initialization usually looks like this:
                   14307: 
                   14308: @example
                   14309: :noname
                   14310:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   14311:     ... \ your stuff
                   14312: ; IS 'cold
                   14313: @end example
                   14314: 
                   14315: @cindex turnkey image files
1.26      crook    14316: @cindex image file, turnkey applications
1.1       anton    14317: You can make a turnkey image by letting @code{'cold} execute a word
                   14318: (your turnkey application) that never returns; instead, it exits Gforth
                   14319: via @code{bye} or @code{throw}.
                   14320: 
1.121     anton    14321: You can access the (image-specific) command-line arguments through
                   14322: @code{argc}, @code{argv} and @code{arg} (@pxref{OS command line
                   14323: arguments}).
1.1       anton    14324: 
1.26      crook    14325: If @code{'cold} exits normally, Gforth processes the command-line
                   14326: arguments as files to be loaded and strings to be evaluated.  Therefore,
                   14327: @code{'cold} should remove the arguments it has used in this case.
                   14328: 
                   14329: doc-'cold
1.44      crook    14330: 
1.1       anton    14331: @c ******************************************************************
1.113     anton    14332: @node Engine, Cross Compiler, Image Files, Top
1.1       anton    14333: @chapter Engine
                   14334: @cindex engine
                   14335: @cindex virtual machine
                   14336: 
1.26      crook    14337: Reading this chapter is not necessary for programming with Gforth. It
1.1       anton    14338: may be helpful for finding your way in the Gforth sources.
                   14339: 
1.109     anton    14340: The ideas in this section have also been published in the following
                   14341: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
                   14342: Forth-Tagung '93; M. Anton Ertl,
                   14343: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
                   14344: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
                   14345: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
                   14346: Threaded code variations and optimizations (extended version)}},
                   14347: Forth-Tagung '02.
1.1       anton    14348: 
                   14349: @menu
                   14350: * Portability::                 
                   14351: * Threading::                   
                   14352: * Primitives::                  
                   14353: * Performance::                 
                   14354: @end menu
                   14355: 
                   14356: @node Portability, Threading, Engine, Engine
                   14357: @section Portability
                   14358: @cindex engine portability
                   14359: 
1.26      crook    14360: An important goal of the Gforth Project is availability across a wide
                   14361: range of personal machines. fig-Forth, and, to a lesser extent, F83,
                   14362: achieved this goal by manually coding the engine in assembly language
                   14363: for several then-popular processors. This approach is very
                   14364: labor-intensive and the results are short-lived due to progress in
                   14365: computer architecture.
1.1       anton    14366: 
                   14367: @cindex C, using C for the engine
                   14368: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   14369: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   14370: particularly popular for UNIX-based Forths due to the large variety of
                   14371: architectures of UNIX machines. Unfortunately an implementation in C
                   14372: does not mix well with the goals of efficiency and with using
                   14373: traditional techniques: Indirect or direct threading cannot be expressed
                   14374: in C, and switch threading, the fastest technique available in C, is
                   14375: significantly slower. Another problem with C is that it is very
                   14376: cumbersome to express double integer arithmetic.
                   14377: 
                   14378: @cindex GNU C for the engine
                   14379: @cindex long long
                   14380: Fortunately, there is a portable language that does not have these
                   14381: limitations: GNU C, the version of C processed by the GNU C compiler
                   14382: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   14383: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   14384: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   14385: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   14386: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109     anton    14387: double numbers on many systems.  GNU C is freely available on all
1.1       anton    14388: important (and many unimportant) UNIX machines, VMS, 80386s running
                   14389: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   14390: on all these machines.
                   14391: 
                   14392: Writing in a portable language has the reputation of producing code that
                   14393: is slower than assembly. For our Forth engine we repeatedly looked at
                   14394: the code produced by the compiler and eliminated most compiler-induced
                   14395: inefficiencies by appropriate changes in the source code.
                   14396: 
                   14397: @cindex explicit register declarations
                   14398: @cindex --enable-force-reg, configuration flag
                   14399: @cindex -DFORCE_REG
                   14400: However, register allocation cannot be portably influenced by the
                   14401: programmer, leading to some inefficiencies on register-starved
                   14402: machines. We use explicit register declarations (@pxref{Explicit Reg
                   14403: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   14404: improve the speed on some machines. They are turned on by using the
                   14405: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   14406: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   14407: machine, but also on the compiler version: On some machines some
                   14408: compiler versions produce incorrect code when certain explicit register
                   14409: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   14410: 
                   14411: @node Threading, Primitives, Portability, Engine
                   14412: @section Threading
                   14413: @cindex inner interpreter implementation
                   14414: @cindex threaded code implementation
                   14415: 
                   14416: @cindex labels as values
                   14417: GNU C's labels as values extension (available since @code{gcc-2.0},
                   14418: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29      crook    14419: makes it possible to take the address of @i{label} by writing
                   14420: @code{&&@i{label}}.  This address can then be used in a statement like
                   14421: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1       anton    14422: @code{goto x}.
                   14423: 
1.26      crook    14424: @cindex @code{NEXT}, indirect threaded
1.1       anton    14425: @cindex indirect threaded inner interpreter
                   14426: @cindex inner interpreter, indirect threaded
1.26      crook    14427: With this feature an indirect threaded @code{NEXT} looks like:
1.1       anton    14428: @example
                   14429: cfa = *ip++;
                   14430: ca = *cfa;
                   14431: goto *ca;
                   14432: @end example
                   14433: @cindex instruction pointer
                   14434: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   14435: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   14436: execution token and points to the code field of the next word to be
                   14437: executed; The @code{ca} (code address) fetched from there points to some
                   14438: executable code, e.g., a primitive or the colon definition handler
                   14439: @code{docol}.
                   14440: 
1.26      crook    14441: @cindex @code{NEXT}, direct threaded
1.1       anton    14442: @cindex direct threaded inner interpreter
                   14443: @cindex inner interpreter, direct threaded
                   14444: Direct threading is even simpler:
                   14445: @example
                   14446: ca = *ip++;
                   14447: goto *ca;
                   14448: @end example
                   14449: 
                   14450: Of course we have packaged the whole thing neatly in macros called
1.26      crook    14451: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1       anton    14452: 
                   14453: @menu
                   14454: * Scheduling::                  
                   14455: * Direct or Indirect Threaded?::  
1.109     anton    14456: * Dynamic Superinstructions::   
1.1       anton    14457: * DOES>::                       
                   14458: @end menu
                   14459: 
                   14460: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   14461: @subsection Scheduling
                   14462: @cindex inner interpreter optimization
                   14463: 
                   14464: There is a little complication: Pipelined and superscalar processors,
                   14465: i.e., RISC and some modern CISC machines can process independent
                   14466: instructions while waiting for the results of an instruction. The
                   14467: compiler usually reorders (schedules) the instructions in a way that
                   14468: achieves good usage of these delay slots. However, on our first tries
                   14469: the compiler did not do well on scheduling primitives. E.g., for
                   14470: @code{+} implemented as
                   14471: @example
                   14472: n=sp[0]+sp[1];
                   14473: sp++;
                   14474: sp[0]=n;
                   14475: NEXT;
                   14476: @end example
1.81      anton    14477: the @code{NEXT} comes strictly after the other code, i.e., there is
                   14478: nearly no scheduling. After a little thought the problem becomes clear:
                   14479: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21      crook    14480: addresses (and the version of @code{gcc} we used would not know it even
                   14481: if it was possible), so it could not move the load of the cfa above the
                   14482: store to the TOS. Indeed the pointers could be the same, if code on or
                   14483: very near the top of stack were executed. In the interest of speed we
                   14484: chose to forbid this probably unused ``feature'' and helped the compiler
1.81      anton    14485: in scheduling: @code{NEXT} is divided into several parts:
                   14486: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
                   14487: like:
1.1       anton    14488: @example
1.81      anton    14489: NEXT_P0;
1.1       anton    14490: n=sp[0]+sp[1];
                   14491: sp++;
                   14492: NEXT_P1;
                   14493: sp[0]=n;
                   14494: NEXT_P2;
                   14495: @end example
                   14496: 
1.81      anton    14497: There are various schemes that distribute the different operations of
                   14498: NEXT between these parts in several ways; in general, different schemes
                   14499: perform best on different processors.  We use a scheme for most
                   14500: architectures that performs well for most processors of this
1.109     anton    14501: architecture; in the future we may switch to benchmarking and chosing
1.81      anton    14502: the scheme on installation time.
                   14503: 
1.1       anton    14504: 
1.109     anton    14505: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1       anton    14506: @subsection Direct or Indirect Threaded?
                   14507: @cindex threading, direct or indirect?
                   14508: 
1.109     anton    14509: Threaded forth code consists of references to primitives (simple machine
                   14510: code routines like @code{+}) and to non-primitives (e.g., colon
                   14511: definitions, variables, constants); for a specific class of
                   14512: non-primitives (e.g., variables) there is one code routine (e.g.,
                   14513: @code{dovar}), but each variable needs a separate reference to its data.
                   14514: 
                   14515: Traditionally Forth has been implemented as indirect threaded code,
                   14516: because this allows to use only one cell to reference a non-primitive
                   14517: (basically you point to the data, and find the code address there).
                   14518: 
                   14519: @cindex primitive-centric threaded code
                   14520: However, threaded code in Gforth (since 0.6.0) uses two cells for
                   14521: non-primitives, one for the code address, and one for the data address;
                   14522: the data pointer is an immediate argument for the virtual machine
                   14523: instruction represented by the code address.  We call this
                   14524: @emph{primitive-centric} threaded code, because all code addresses point
                   14525: to simple primitives.  E.g., for a variable, the code address is for
                   14526: @code{lit} (also used for integer literals like @code{99}).
                   14527: 
                   14528: Primitive-centric threaded code allows us to use (faster) direct
                   14529: threading as dispatch method, completely portably (direct threaded code
                   14530: in Gforth before 0.6.0 required architecture-specific code).  It also
                   14531: eliminates the performance problems related to I-cache consistency that
                   14532: 386 implementations have with direct threaded code, and allows
                   14533: additional optimizations.
                   14534: 
                   14535: @cindex hybrid direct/indirect threaded code
                   14536: There is a catch, however: the @var{xt} parameter of @code{execute} can
                   14537: occupy only one cell, so how do we pass non-primitives with their code
                   14538: @emph{and} data addresses to them?  Our answer is to use indirect
                   14539: threaded dispatch for @code{execute} and other words that use a
                   14540: single-cell xt.  So, normal threaded code in colon definitions uses
                   14541: direct threading, and @code{execute} and similar words, which dispatch
                   14542: to xts on the data stack, use indirect threaded code.  We call this
                   14543: @emph{hybrid direct/indirect} threaded code.
                   14544: 
                   14545: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
                   14546: @cindex gforth engine
                   14547: @cindex gforth-fast engine
                   14548: The engines @command{gforth} and @command{gforth-fast} use hybrid
                   14549: direct/indirect threaded code.  This means that with these engines you
                   14550: cannot use @code{,} to compile an xt.  Instead, you have to use
                   14551: @code{compile,}.
                   14552: 
                   14553: @cindex gforth-itc engine
1.115     anton    14554: If you want to compile xts with @code{,}, use @command{gforth-itc}.
                   14555: This engine uses plain old indirect threaded code.  It still compiles in
                   14556: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109     anton    14557: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115     anton    14558: ... [}).  If you want to do that, you have to use @command{gforth-itc}
1.109     anton    14559: and execute @code{' , is compile,}.  Your program can check if it is
                   14560: running on a hybrid direct/indirect threaded engine or a pure indirect
                   14561: threaded engine with @code{threading-method} (@pxref{Threading Words}).
                   14562: 
                   14563: 
                   14564: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
                   14565: @subsection Dynamic Superinstructions
                   14566: @cindex Dynamic superinstructions with replication
                   14567: @cindex Superinstructions
                   14568: @cindex Replication
                   14569: 
                   14570: The engines @command{gforth} and @command{gforth-fast} use another
                   14571: optimization: Dynamic superinstructions with replication.  As an
                   14572: example, consider the following colon definition:
                   14573: 
                   14574: @example
                   14575: : squared ( n1 -- n2 )
                   14576:   dup * ;
                   14577: @end example
                   14578: 
                   14579: Gforth compiles this into the threaded code sequence
                   14580: 
                   14581: @example
                   14582: dup
                   14583: *
                   14584: ;s
                   14585: @end example
                   14586: 
                   14587: In normal direct threaded code there is a code address occupying one
                   14588: cell for each of these primitives.  Each code address points to a
                   14589: machine code routine, and the interpreter jumps to this machine code in
                   14590: order to execute the primitive.  The routines for these three
                   14591: primitives are (in @command{gforth-fast} on the 386):
                   14592: 
                   14593: @example
                   14594: Code dup  
                   14595: ( $804B950 )  add     esi , # -4  \ $83 $C6 $FC 
                   14596: ( $804B953 )  add     ebx , # 4  \ $83 $C3 $4 
                   14597: ( $804B956 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
                   14598: ( $804B959 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   14599: end-code
                   14600: Code *  
                   14601: ( $804ACC4 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
                   14602: ( $804ACC7 )  add     esi , # 4  \ $83 $C6 $4 
                   14603: ( $804ACCA )  add     ebx , # 4  \ $83 $C3 $4 
                   14604: ( $804ACCD )  imul    ecx , eax  \ $F $AF $C8 
                   14605: ( $804ACD0 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   14606: end-code
                   14607: Code ;s  
                   14608: ( $804A693 )  mov     eax , dword ptr [edi]  \ $8B $7 
                   14609: ( $804A695 )  add     edi , # 4  \ $83 $C7 $4 
                   14610: ( $804A698 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
                   14611: ( $804A69B )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   14612: end-code
                   14613: @end example
                   14614: 
                   14615: With dynamic superinstructions and replication the compiler does not
                   14616: just lay down the threaded code, but also copies the machine code
                   14617: fragments, usually without the jump at the end.
                   14618: 
                   14619: @example
                   14620: ( $4057D27D )  add     esi , # -4  \ $83 $C6 $FC 
                   14621: ( $4057D280 )  add     ebx , # 4  \ $83 $C3 $4 
                   14622: ( $4057D283 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
                   14623: ( $4057D286 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
                   14624: ( $4057D289 )  add     esi , # 4  \ $83 $C6 $4 
                   14625: ( $4057D28C )  add     ebx , # 4  \ $83 $C3 $4 
                   14626: ( $4057D28F )  imul    ecx , eax  \ $F $AF $C8 
                   14627: ( $4057D292 )  mov     eax , dword ptr [edi]  \ $8B $7 
                   14628: ( $4057D294 )  add     edi , # 4  \ $83 $C7 $4 
                   14629: ( $4057D297 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
                   14630: ( $4057D29A )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   14631: @end example
                   14632: 
                   14633: Only when a threaded-code control-flow change happens (e.g., in
                   14634: @code{;s}), the jump is appended.  This optimization eliminates many of
                   14635: these jumps and makes the rest much more predictable.  The speedup
                   14636: depends on the processor and the application; on the Athlon and Pentium
                   14637: III this optimization typically produces a speedup by a factor of 2.
                   14638: 
                   14639: The code addresses in the direct-threaded code are set to point to the
                   14640: appropriate points in the copied machine code, in this example like
                   14641: this:
1.1       anton    14642: 
1.109     anton    14643: @example
                   14644: primitive  code address
                   14645:    dup       $4057D27D
                   14646:    *         $4057D286
                   14647:    ;s        $4057D292
                   14648: @end example
                   14649: 
                   14650: Thus there can be threaded-code jumps to any place in this piece of
                   14651: code.  This also simplifies decompilation quite a bit.
                   14652: 
                   14653: @cindex --no-dynamic command-line option
                   14654: @cindex --no-super command-line option
                   14655: You can disable this optimization with @option{--no-dynamic}.  You can
                   14656: use the copying without eliminating the jumps (i.e., dynamic
                   14657: replication, but without superinstructions) with @option{--no-super};
                   14658: this gives the branch prediction benefit alone; the effect on
1.110     anton    14659: performance depends on the CPU; on the Athlon and Pentium III the
                   14660: speedup is a little less than for dynamic superinstructions with
                   14661: replication.
                   14662: 
                   14663: @cindex patching threaded code
                   14664: One use of these options is if you want to patch the threaded code.
                   14665: With superinstructions, many of the dispatch jumps are eliminated, so
                   14666: patching often has no effect.  These options preserve all the dispatch
                   14667: jumps.
1.109     anton    14668: 
                   14669: @cindex --dynamic command-line option
1.110     anton    14670: On some machines dynamic superinstructions are disabled by default,
                   14671: because it is unsafe on these machines.  However, if you feel
                   14672: adventurous, you can enable it with @option{--dynamic}.
1.109     anton    14673: 
                   14674: @node DOES>,  , Dynamic Superinstructions, Threading
1.1       anton    14675: @subsection DOES>
                   14676: @cindex @code{DOES>} implementation
                   14677: 
1.26      crook    14678: @cindex @code{dodoes} routine
                   14679: @cindex @code{DOES>}-code
1.1       anton    14680: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   14681: the chunk of code executed by every word defined by a
1.109     anton    14682: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
                   14683: this is only needed if the xt of the word is @code{execute}d. The main
                   14684: problem here is: How to find the Forth code to be executed, i.e. the
                   14685: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
                   14686: solutions:
1.1       anton    14687: 
1.21      crook    14688: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109     anton    14689: @code{DOES>}-code address is stored in the cell after the code address
                   14690: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
                   14691: illegal in the Forth-79 and all later standards, because in fig-Forth
                   14692: this address lies in the body (which is illegal in these
                   14693: standards). However, by making the code field larger for all words this
                   14694: solution becomes legal again.  We use this approach.  Leaving a cell
                   14695: unused in most words is a bit wasteful, but on the machines we are
                   14696: targeting this is hardly a problem.
                   14697: 
1.1       anton    14698: 
                   14699: @node Primitives, Performance, Threading, Engine
                   14700: @section Primitives
                   14701: @cindex primitives, implementation
                   14702: @cindex virtual machine instructions, implementation
                   14703: 
                   14704: @menu
                   14705: * Automatic Generation::        
                   14706: * TOS Optimization::            
                   14707: * Produced code::               
                   14708: @end menu
                   14709: 
                   14710: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   14711: @subsection Automatic Generation
                   14712: @cindex primitives, automatic generation
                   14713: 
                   14714: @cindex @file{prims2x.fs}
1.109     anton    14715: 
1.1       anton    14716: Since the primitives are implemented in a portable language, there is no
                   14717: longer any need to minimize the number of primitives. On the contrary,
                   14718: having many primitives has an advantage: speed. In order to reduce the
                   14719: number of errors in primitives and to make programming them easier, we
1.109     anton    14720: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
                   14721: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
                   14722: generates most (and sometimes all) of the C code for a primitive from
                   14723: the stack effect notation.  The source for a primitive has the following
                   14724: form:
1.1       anton    14725: 
                   14726: @cindex primitive source format
                   14727: @format
1.58      anton    14728: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
1.29      crook    14729: [@code{""}@i{glossary entry}@code{""}]
                   14730: @i{C code}
1.1       anton    14731: [@code{:}
1.29      crook    14732: @i{Forth code}]
1.1       anton    14733: @end format
                   14734: 
                   14735: The items in brackets are optional. The category and glossary fields
                   14736: are there for generating the documentation, the Forth code is there
                   14737: for manual implementations on machines without GNU C. E.g., the source
                   14738: for the primitive @code{+} is:
                   14739: @example
1.58      anton    14740: +    ( n1 n2 -- n )   core    plus
1.1       anton    14741: n = n1+n2;
                   14742: @end example
                   14743: 
                   14744: This looks like a specification, but in fact @code{n = n1+n2} is C
                   14745: code. Our primitive generation tool extracts a lot of information from
                   14746: the stack effect notations@footnote{We use a one-stack notation, even
                   14747: though we have separate data and floating-point stacks; The separate
                   14748: notation can be generated easily from the unified notation.}: The number
                   14749: of items popped from and pushed on the stack, their type, and by what
                   14750: name they are referred to in the C code. It then generates a C code
                   14751: prelude and postlude for each primitive. The final C code for @code{+}
                   14752: looks like this:
                   14753: 
                   14754: @example
1.46      pazsan   14755: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
1.1       anton    14756: /*  */                          /* documentation */
1.81      anton    14757: NAME("+")                       /* debugging output (with -DDEBUG) */
1.1       anton    14758: @{
                   14759: DEF_CA                          /* definition of variable ca (indirect threading) */
                   14760: Cell n1;                        /* definitions of variables */
                   14761: Cell n2;
                   14762: Cell n;
1.81      anton    14763: NEXT_P0;                        /* NEXT part 0 */
1.1       anton    14764: n1 = (Cell) sp[1];              /* input */
                   14765: n2 = (Cell) TOS;
                   14766: sp += 1;                        /* stack adjustment */
                   14767: @{
                   14768: n = n1+n2;                      /* C code taken from the source */
                   14769: @}
                   14770: NEXT_P1;                        /* NEXT part 1 */
                   14771: TOS = (Cell)n;                  /* output */
                   14772: NEXT_P2;                        /* NEXT part 2 */
                   14773: @}
                   14774: @end example
                   14775: 
                   14776: This looks long and inefficient, but the GNU C compiler optimizes quite
                   14777: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   14778: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   14779: using them as intermediate storage also adds no cost.
                   14780: 
1.26      crook    14781: There are also other optimizations that are not illustrated by this
                   14782: example: assignments between simple variables are usually for free (copy
1.1       anton    14783: propagation). If one of the stack items is not used by the primitive
                   14784: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   14785: (dead code elimination). On the other hand, there are some things that
                   14786: the compiler does not do, therefore they are performed by
                   14787: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   14788: a stack item to the place where it just came from (e.g., @code{over}).
                   14789: 
                   14790: While programming a primitive is usually easy, there are a few cases
                   14791: where the programmer has to take the actions of the generator into
                   14792: account, most notably @code{?dup}, but also words that do not (always)
1.26      crook    14793: fall through to @code{NEXT}.
1.109     anton    14794: 
                   14795: For more information
1.1       anton    14796: 
                   14797: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   14798: @subsection TOS Optimization
                   14799: @cindex TOS optimization for primitives
                   14800: @cindex primitives, keeping the TOS in a register
                   14801: 
                   14802: An important optimization for stack machine emulators, e.g., Forth
                   14803: engines, is keeping  one or more of the top stack items in
1.29      crook    14804: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
                   14805: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1       anton    14806: @itemize @bullet
                   14807: @item
1.29      crook    14808: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1       anton    14809: due to fewer loads from and stores to the stack.
1.29      crook    14810: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
                   14811: @i{y<n}, due to additional moves between registers.
1.1       anton    14812: @end itemize
                   14813: 
                   14814: @cindex -DUSE_TOS
                   14815: @cindex -DUSE_NO_TOS
                   14816: In particular, keeping one item in a register is never a disadvantage,
                   14817: if there are enough registers. Keeping two items in registers is a
                   14818: disadvantage for frequent words like @code{?branch}, constants,
                   14819: variables, literals and @code{i}. Therefore our generator only produces
                   14820: code that keeps zero or one items in registers. The generated C code
                   14821: covers both cases; the selection between these alternatives is made at
                   14822: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   14823: code for @code{+} is just a simple variable name in the one-item case,
                   14824: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   14825: GNU C compiler tries to keep simple variables like @code{TOS} in
                   14826: registers, and it usually succeeds, if there are enough registers.
                   14827: 
                   14828: @cindex -DUSE_FTOS
                   14829: @cindex -DUSE_NO_FTOS
                   14830: The primitive generator performs the TOS optimization for the
                   14831: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   14832: operations the benefit of this optimization is even larger:
                   14833: floating-point operations take quite long on most processors, but can be
                   14834: performed in parallel with other operations as long as their results are
                   14835: not used. If the FP-TOS is kept in a register, this works. If
                   14836: it is kept on the stack, i.e., in memory, the store into memory has to
                   14837: wait for the result of the floating-point operation, lengthening the
                   14838: execution time of the primitive considerably.
                   14839: 
                   14840: The TOS optimization makes the automatic generation of primitives a
                   14841: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   14842: @code{TOS} is not sufficient. There are some special cases to
                   14843: consider:
                   14844: @itemize @bullet
                   14845: @item In the case of @code{dup ( w -- w w )} the generator must not
                   14846: eliminate the store to the original location of the item on the stack,
                   14847: if the TOS optimization is turned on.
                   14848: @item Primitives with stack effects of the form @code{--}
1.29      crook    14849: @i{out1}...@i{outy} must store the TOS to the stack at the start.
                   14850: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1       anton    14851: must load the TOS from the stack at the end. But for the null stack
                   14852: effect @code{--} no stores or loads should be generated.
                   14853: @end itemize
                   14854: 
                   14855: @node Produced code,  , TOS Optimization, Primitives
                   14856: @subsection Produced code
                   14857: @cindex primitives, assembly code listing
                   14858: 
                   14859: @cindex @file{engine.s}
                   14860: To see what assembly code is produced for the primitives on your machine
                   14861: with your compiler and your flag settings, type @code{make engine.s} and
1.81      anton    14862: look at the resulting file @file{engine.s}.  Alternatively, you can also
                   14863: disassemble the code of primitives with @code{see} on some architectures.
1.1       anton    14864: 
                   14865: @node  Performance,  , Primitives, Engine
                   14866: @section Performance
                   14867: @cindex performance of some Forth interpreters
                   14868: @cindex engine performance
                   14869: @cindex benchmarking Forth systems
                   14870: @cindex Gforth performance
                   14871: 
                   14872: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112     anton    14873: impossible to write a significantly faster threaded-code engine.
1.1       anton    14874: 
                   14875: On register-starved machines like the 386 architecture processors
                   14876: improvements are possible, because @code{gcc} does not utilize the
                   14877: registers as well as a human, even with explicit register declarations;
                   14878: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   14879: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   14880: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40      anton    14881: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
                   14882: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
                   14883: registers fit in real registers (and we can even afford to use the TOS
                   14884: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112     anton    14885: earlier results.  And dynamic superinstructions provide another speedup
                   14886: (but only around a factor 1.2 on the 486).
1.1       anton    14887: 
                   14888: @cindex Win32Forth performance
                   14889: @cindex NT Forth performance
                   14890: @cindex eforth performance
                   14891: @cindex ThisForth performance
                   14892: @cindex PFE performance
                   14893: @cindex TILE performance
1.81      anton    14894: The potential advantage of assembly language implementations is not
1.112     anton    14895: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81      anton    14896: (direct threaded, compiled with @code{gcc-2.95.1} and
                   14897: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
                   14898: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
                   14899: (with and without peephole (aka pinhole) optimization of the threaded
                   14900: code); all these systems were written in assembly language. We also
                   14901: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
                   14902: with @code{gcc-2.6.3} with the default configuration for Linux:
                   14903: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
                   14904: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
                   14905: employs peephole optimization of the threaded code) and TILE (compiled
                   14906: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
                   14907: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
                   14908: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
                   14909: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
                   14910: then extended it to run the benchmarks, added the peephole optimizer,
                   14911: ran the benchmarks and reported the results.
1.40      anton    14912: 
1.1       anton    14913: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   14914: matrix multiplication come from the Stanford integer benchmarks and have
                   14915: been translated into Forth by Martin Fraeman; we used the versions
                   14916: included in the TILE Forth package, but with bigger data set sizes; and
                   14917: a recursive Fibonacci number computation for benchmarking calling
                   14918: performance. The following table shows the time taken for the benchmarks
                   14919: scaled by the time taken by Gforth (in other words, it shows the speedup
                   14920: factor that Gforth achieved over the other systems).
                   14921: 
                   14922: @example
1.112     anton    14923: relative       Win32-    NT       eforth       This-      
                   14924: time     Gforth Forth Forth eforth  +opt   PFE Forth  TILE
                   14925: sieve      1.00  2.16  1.78   2.16  1.32  2.46  4.96 13.37
                   14926: bubble     1.00  1.93  2.07   2.18  1.29  2.21        5.70
                   14927: matmul     1.00  1.92  1.76   1.90  0.96  2.06        5.32
                   14928: fib        1.00  2.32  2.03   1.86  1.31  2.64  4.55  6.54
1.1       anton    14929: @end example
                   14930: 
1.26      crook    14931: You may be quite surprised by the good performance of Gforth when
                   14932: compared with systems written in assembly language. One important reason
                   14933: for the disappointing performance of these other systems is probably
                   14934: that they are not written optimally for the 486 (e.g., they use the
                   14935: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
                   14936: but costly method for relocating the Forth image: like @code{cforth}, it
                   14937: computes the actual addresses at run time, resulting in two address
                   14938: computations per @code{NEXT} (@pxref{Image File Background}).
                   14939: 
1.1       anton    14940: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   14941: explained with the self-imposed restriction of the latter systems to
                   14942: standard C, which makes efficient threading impossible (however, the
1.4       anton    14943: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    14944: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   14945: Moreover, current C compilers have a hard time optimizing other aspects
                   14946: of the ThisForth and the TILE source.
                   14947: 
1.26      crook    14948: The performance of Gforth on 386 architecture processors varies widely
                   14949: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
                   14950: allocate any of the virtual machine registers into real machine
                   14951: registers by itself and would not work correctly with explicit register
1.112     anton    14952: declarations, giving a significantly slower engine (on a 486DX2/66
                   14953: running the Sieve) than the one measured above.
1.1       anton    14954: 
1.26      crook    14955: Note that there have been several releases of Win32Forth since the
                   14956: release presented here, so the results presented above may have little
1.40      anton    14957: predictive value for the performance of Win32Forth today (results for
                   14958: the current release on an i486DX2/66 are welcome).
1.1       anton    14959: 
                   14960: @cindex @file{Benchres}
1.66      anton    14961: In
                   14962: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
                   14963: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1       anton    14964: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66      anton    14965: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
                   14966: several native code systems; that version of Gforth is slower on a 486
1.112     anton    14967: than the version used here. You can find a newer version of these
                   14968: measurements at
1.47      crook    14969: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1       anton    14970: find numbers for Gforth on various machines in @file{Benchres}.
                   14971: 
1.26      crook    14972: @c ******************************************************************
1.113     anton    14973: @c @node Binding to System Library, Cross Compiler, Engine, Top
                   14974: @c @chapter Binding to System Library
1.13      pazsan   14975: 
1.113     anton    14976: @c ****************************************************************
                   14977: @node Cross Compiler, Bugs, Engine, Top
1.14      pazsan   14978: @chapter Cross Compiler
1.47      crook    14979: @cindex @file{cross.fs}
                   14980: @cindex cross-compiler
                   14981: @cindex metacompiler
                   14982: @cindex target compiler
1.13      pazsan   14983: 
1.46      pazsan   14984: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
                   14985: mostly written in Forth, including crucial parts like the outer
                   14986: interpreter and compiler, it needs compiled Forth code to get
                   14987: started. The cross compiler allows to create new images for other
                   14988: architectures, even running under another Forth system.
1.13      pazsan   14989: 
                   14990: @menu
1.67      anton    14991: * Using the Cross Compiler::    
                   14992: * How the Cross Compiler Works::  
1.13      pazsan   14993: @end menu
                   14994: 
1.21      crook    14995: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14      pazsan   14996: @section Using the Cross Compiler
1.46      pazsan   14997: 
                   14998: The cross compiler uses a language that resembles Forth, but isn't. The
                   14999: main difference is that you can execute Forth code after definition,
                   15000: while you usually can't execute the code compiled by cross, because the
                   15001: code you are compiling is typically for a different computer than the
                   15002: one you are compiling on.
                   15003: 
1.81      anton    15004: @c anton: This chapter is somewhat different from waht I would expect: I
                   15005: @c would expect an explanation of the cross language and how to create an
                   15006: @c application image with it.  The section explains some aspects of
                   15007: @c creating a Gforth kernel.
                   15008: 
1.46      pazsan   15009: The Makefile is already set up to allow you to create kernels for new
                   15010: architectures with a simple make command. The generic kernels using the
                   15011: GCC compiled virtual machine are created in the normal build process
                   15012: with @code{make}. To create a embedded Gforth executable for e.g. the
                   15013: 8086 processor (running on a DOS machine), type
                   15014: 
                   15015: @example
                   15016: make kernl-8086.fi
                   15017: @end example
                   15018: 
                   15019: This will use the machine description from the @file{arch/8086}
                   15020: directory to create a new kernel. A machine file may look like that:
                   15021: 
                   15022: @example
                   15023: \ Parameter for target systems                         06oct92py
                   15024: 
                   15025:     4 Constant cell             \ cell size in bytes
                   15026:     2 Constant cell<<           \ cell shift to bytes
                   15027:     5 Constant cell>bit         \ cell shift to bits
                   15028:     8 Constant bits/char        \ bits per character
                   15029:     8 Constant bits/byte        \ bits per byte [default: 8]
                   15030:     8 Constant float            \ bytes per float
                   15031:     8 Constant /maxalign        \ maximum alignment in bytes
                   15032: false Constant bigendian        \ byte order
                   15033: ( true=big, false=little )
                   15034: 
                   15035: include machpc.fs               \ feature list
                   15036: @end example
                   15037: 
                   15038: This part is obligatory for the cross compiler itself, the feature list
                   15039: is used by the kernel to conditionally compile some features in and out,
                   15040: depending on whether the target supports these features.
                   15041: 
                   15042: There are some optional features, if you define your own primitives,
                   15043: have an assembler, or need special, nonstandard preparation to make the
1.81      anton    15044: boot process work. @code{asm-include} includes an assembler,
1.46      pazsan   15045: @code{prims-include} includes primitives, and @code{>boot} prepares for
                   15046: booting.
                   15047: 
                   15048: @example
                   15049: : asm-include    ." Include assembler" cr
                   15050:   s" arch/8086/asm.fs" included ;
                   15051: 
                   15052: : prims-include  ." Include primitives" cr
                   15053:   s" arch/8086/prim.fs" included ;
                   15054: 
                   15055: : >boot          ." Prepare booting" cr
                   15056:   s" ' boot >body into-forth 1+ !" evaluate ;
                   15057: @end example
                   15058: 
                   15059: These words are used as sort of macro during the cross compilation in
1.81      anton    15060: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46      pazsan   15061: be possible --- but more complicated --- to write a new kernel project
                   15062: file, too.
                   15063: 
                   15064: @file{kernel/main.fs} expects the machine description file name on the
                   15065: stack; the cross compiler itself (@file{cross.fs}) assumes that either
                   15066: @code{mach-file} leaves a counted string on the stack, or
                   15067: @code{machine-file} leaves an address, count pair of the filename on the
                   15068: stack.
                   15069: 
                   15070: The feature list is typically controlled using @code{SetValue}, generic
                   15071: files that are used by several projects can use @code{DefaultValue}
                   15072: instead. Both functions work like @code{Value}, when the value isn't
                   15073: defined, but @code{SetValue} works like @code{to} if the value is
                   15074: defined, and @code{DefaultValue} doesn't set anything, if the value is
                   15075: defined.
                   15076: 
                   15077: @example
                   15078: \ generic mach file for pc gforth                       03sep97jaw
                   15079: 
                   15080: true DefaultValue NIL  \ relocating
                   15081: 
                   15082: >ENVIRON
                   15083: 
                   15084: true DefaultValue file          \ controls the presence of the
                   15085:                                 \ file access wordset
                   15086: true DefaultValue OS            \ flag to indicate a operating system
                   15087: 
                   15088: true DefaultValue prims         \ true: primitives are c-code
                   15089: 
                   15090: true DefaultValue floating      \ floating point wordset is present
                   15091: 
                   15092: true DefaultValue glocals       \ gforth locals are present
                   15093:                                 \ will be loaded
                   15094: true DefaultValue dcomps        \ double number comparisons
                   15095: 
                   15096: true DefaultValue hash          \ hashing primitives are loaded/present
                   15097: 
                   15098: true DefaultValue xconds        \ used together with glocals,
                   15099:                                 \ special conditionals supporting gforths'
                   15100:                                 \ local variables
                   15101: true DefaultValue header        \ save a header information
                   15102: 
                   15103: true DefaultValue backtrace     \ enables backtrace code
                   15104: 
                   15105: false DefaultValue ec
                   15106: false DefaultValue crlf
                   15107: 
                   15108: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
                   15109: 
                   15110: &16 KB          DefaultValue stack-size
                   15111: &15 KB &512 +   DefaultValue fstack-size
                   15112: &15 KB          DefaultValue rstack-size
                   15113: &14 KB &512 +   DefaultValue lstack-size
                   15114: @end example
1.13      pazsan   15115: 
1.48      anton    15116: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
1.14      pazsan   15117: @section How the Cross Compiler Works
1.13      pazsan   15118: 
                   15119: @node Bugs, Origin, Cross Compiler, Top
1.21      crook    15120: @appendix Bugs
1.1       anton    15121: @cindex bug reporting
                   15122: 
1.21      crook    15123: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1       anton    15124: 
1.103     anton    15125: If you find a bug, please submit a bug report through
                   15126: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21      crook    15127: 
                   15128: @itemize @bullet
                   15129: @item
1.81      anton    15130: A program (or a sequence of keyboard commands) that reproduces the bug.
                   15131: @item
                   15132: A description of what you think constitutes the buggy behaviour.
                   15133: @item
1.21      crook    15134: The Gforth version used (it is announced at the start of an
                   15135: interactive Gforth session).
                   15136: @item
                   15137: The machine and operating system (on Unix
                   15138: systems @code{uname -a} will report this information).
                   15139: @item
1.81      anton    15140: The installation options (you can find the configure options at the
                   15141: start of @file{config.status}) and configuration (@code{configure}
                   15142: output or @file{config.cache}).
1.21      crook    15143: @item
                   15144: A complete list of changes (if any) you (or your installer) have made to the
                   15145: Gforth sources.
                   15146: @end itemize
1.1       anton    15147: 
                   15148: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   15149: to Report Bugs, gcc.info, GNU C Manual}.
                   15150: 
                   15151: 
1.21      crook    15152: @node Origin, Forth-related information, Bugs, Top
                   15153: @appendix Authors and Ancestors of Gforth
1.1       anton    15154: 
                   15155: @section Authors and Contributors
                   15156: @cindex authors of Gforth
                   15157: @cindex contributors to Gforth
                   15158: 
                   15159: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81      anton    15160: Ertl. The third major author was Jens Wilke.  Neal Crook contributed a
                   15161: lot to the manual.  Assemblers and disassemblers were contributed by
                   15162: Andrew McKewan, Christian Pirker, and Bernd Thallner.  Lennart Benschop
                   15163: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
                   15164: inspired us with their continuous feedback. Lennart Benshop contributed
1.1       anton    15165: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
                   15166: support for calling C libraries. Helpful comments also came from Paul
                   15167: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.113     anton    15168: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, Robert
                   15169: Epprecht, Dennis Ruffer and David N. Williams. Since the release of
                   15170: Gforth-0.2.1 there were also helpful comments from many others; thank
                   15171: you all, sorry for not listing you here (but digging through my mailbox
                   15172: to extract your names is on my to-do list).
1.1       anton    15173: 
                   15174: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   15175: and autoconf, among others), and to the creators of the Internet: Gforth
1.21      crook    15176: was developed across the Internet, and its authors did not meet
1.20      pazsan   15177: physically for the first 4 years of development.
1.1       anton    15178: 
                   15179: @section Pedigree
1.26      crook    15180: @cindex pedigree of Gforth
1.1       anton    15181: 
1.81      anton    15182: Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
                   15183: significant part of the design of Gforth was prescribed by ANS Forth.
1.1       anton    15184: 
1.20      pazsan   15185: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1       anton    15186: 32 bit native code version of VolksForth for the Atari ST, written
                   15187: mostly by Dietrich Weineck.
                   15188: 
1.81      anton    15189: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
                   15190: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
                   15191: the mid-80s and ported to the Atari ST in 1986.  It descends from F83.
1.1       anton    15192: 
                   15193: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   15194: Forth-83 standard. !! Pedigree? When?
                   15195: 
                   15196: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   15197: 1979. Robert Selzer and Bill Ragsdale developed the original
                   15198: implementation of fig-Forth for the 6502 based on microForth.
                   15199: 
                   15200: The principal architect of microForth was Dean Sanderson. microForth was
                   15201: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   15202: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   15203: Z80.
                   15204: 
                   15205: All earlier Forth systems were custom-made, usually by Charles Moore,
                   15206: who discovered (as he puts it) Forth during the late 60s. The first full
                   15207: Forth existed in 1971.
                   15208: 
1.81      anton    15209: A part of the information in this section comes from
                   15210: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
                   15211: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
                   15212: Charles H. Moore, presented at the HOPL-II conference and preprinted in
                   15213: SIGPLAN Notices 28(3), 1993.  You can find more historical and
                   15214: genealogical information about Forth there.
1.1       anton    15215: 
1.81      anton    15216: @c ------------------------------------------------------------------
1.113     anton    15217: @node Forth-related information, Licenses, Origin, Top
1.21      crook    15218: @appendix Other Forth-related information
                   15219: @cindex Forth-related information
                   15220: 
1.81      anton    15221: @c anton: I threw most of this stuff out, because it can be found through
                   15222: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21      crook    15223: 
                   15224: @cindex comp.lang.forth
                   15225: @cindex frequently asked questions
1.81      anton    15226: There is an active news group (comp.lang.forth) discussing Forth
                   15227: (including Gforth) and Forth-related issues. Its
                   15228: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
                   15229: (frequently asked questions and their answers) contains a lot of
                   15230: information on Forth.  You should read it before posting to
                   15231: comp.lang.forth.
1.21      crook    15232: 
1.81      anton    15233: The ANS Forth standard is most usable in its
                   15234: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21      crook    15235: 
1.113     anton    15236: @c ---------------------------------------------------
                   15237: @node  Licenses, Word Index, Forth-related information, Top
                   15238: @appendix Licenses
                   15239: 
                   15240: @menu
                   15241: * GNU Free Documentation License::  License for copying this manual.
                   15242: * Copying::                         GPL (for copying this software).
                   15243: @end menu
                   15244: 
                   15245: @include fdl.texi
                   15246: 
                   15247: @include gpl.texi
                   15248: 
                   15249: 
                   15250: 
1.81      anton    15251: @c ------------------------------------------------------------------
1.113     anton    15252: @node Word Index, Concept Index, Licenses, Top
1.1       anton    15253: @unnumbered Word Index
                   15254: 
1.26      crook    15255: This index is a list of Forth words that have ``glossary'' entries
                   15256: within this manual. Each word is listed with its stack effect and
                   15257: wordset.
1.1       anton    15258: 
                   15259: @printindex fn
                   15260: 
1.81      anton    15261: @c anton: the name index seems superfluous given the word and concept indices.
                   15262: 
                   15263: @c @node Name Index, Concept Index, Word Index, Top
                   15264: @c @unnumbered Name Index
1.41      anton    15265: 
1.81      anton    15266: @c This index is a list of Forth words that have ``glossary'' entries
                   15267: @c within this manual.
1.41      anton    15268: 
1.81      anton    15269: @c @printindex ky
1.41      anton    15270: 
1.113     anton    15271: @c -------------------------------------------------------
1.81      anton    15272: @node Concept Index,  , Word Index, Top
1.1       anton    15273: @unnumbered Concept and Word Index
                   15274: 
1.26      crook    15275: Not all entries listed in this index are present verbatim in the
                   15276: text. This index also duplicates, in abbreviated form, all of the words
                   15277: listed in the Word Index (only the names are listed for the words here).
1.1       anton    15278: 
                   15279: @printindex cp
                   15280: 
                   15281: @bye
1.81      anton    15282: 
                   15283: 
1.1       anton    15284: 

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